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_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4716        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4717    if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4718        receipt.extend(extra);
4719    }
4720    if let Err(error) = crate::fold_evidence::atomic_write(
4721        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4722        &serde_json::to_vec(&receipt).expect("service receipt"),
4723    ) {
4724        tracing::warn!("retention service receipt failed: {error:#}");
4725    }
4726}
4727
4728/// What a retention pass reported, for the service receipt: the same report
4729/// `retention.json` holds, reduced to what says whether the pass ran. On a
4730/// platform without process containment this carries the refusal.
4731fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4732    let clip = |text: &String| text.chars().take(300).collect::<String>();
4733    serde_json::json!({"retention": {
4734        "checked_at": report.checked_at,
4735        "freed_bytes": report.freed_bytes,
4736        "retired": report.retired,
4737        "retained": report.retained.len(),
4738        "failure_count": report.failures.len(),
4739        "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4740    }})
4741}
4742
4743/// Why the finished-run folding turn exists, and what keeps it safe.
4744///
4745/// `housekeeping` (which folds finished runs through `clean::fold_due`) has
4746/// only ever been admitted on a fully idle machine: it was written as "the
4747/// janitor, called when a task just ended" (e2c10827, "the disk is quiet ...
4748/// folding worktrees and pruning a cache mid-build would race the very compile
4749/// the prune exists to keep"), and the idle gate survived when the loop was
4750/// split into services. Nothing in that reasoning is about folding: it is
4751/// about the shared cache prune, `fold_orphaned_worktrees` (a run that has no
4752/// `run.json` yet is indistinguishable from an orphan) and `worktree_prune`,
4753/// which stay idle-only. Folding a *finished* run is already done beside live
4754/// runs of the same repository by `Runner::fold_losers`, `magi fold` and the
4755/// phone's fold route, because `graph::fold_run_when` takes the run's owner lock
4756/// and execution lease, a per-worktree output lease and the repository
4757/// coordination lease itself, acts on the run record it reloads once it holds
4758/// them (a handover in between cannot be undone), and `clean::eligibility`
4759/// refuses anything a live claim holds. So a queue that is never empty must not
4760/// mean runs are never folded (issue 1275): this turn is admitted exactly where
4761/// housekeeping is not, in bounded passes (`clean::BUSY_FOLD_BOUNDS`).
4762const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4763
4764/// Idle housekeeping: no worker busy and nothing runnable.
4765fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4766    !busy && !runnable
4767}
4768
4769/// Exactly the machines [`housekeeping_eligible`] never reaches (see
4770/// [`FOLD_TURN_INTERVAL_SECS`] for why folding may run beside live work),
4771/// and only with a startup configuration that has `auto_fold` on (like the
4772/// cache and fetch services, an unreadable one means no service).
4773fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4774    !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4775}
4776
4777async fn start_service(
4778    home: &Path,
4779    opts: &Opts,
4780    queue: &Queue,
4781    worktrees_root: &Path,
4782    operation: &str,
4783    cfg: Option<&Config>,
4784    busy: bool,
4785) -> Result<()> {
4786    // Fetch policy is live configuration, unlike question recovery capacity.
4787    // Reload before both cadence and eligibility, including disabled -> enabled.
4788    let fetch_cfg = if operation == "fetch" {
4789        match prepare(&opts.repo, opts) {
4790            Ok(cfg) => Some(cfg),
4791            Err(error) => {
4792                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4793                return Ok(());
4794            }
4795        }
4796    } else {
4797        None
4798    };
4799    let cfg = fetch_cfg.as_ref().or(cfg);
4800    let ticks = home.join("service-ticks");
4801    std::fs::create_dir_all(&ticks)?;
4802    let receipt = ticks.join(format!("daemon-{operation}"));
4803    let last = std::fs::read(&receipt)
4804        .ok()
4805        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4806    let interval = match operation {
4807        "disk-pressure" => 30,
4808        "fold" => FOLD_TURN_INTERVAL_SECS,
4809        "chat-goals" => 60,
4810        "cache" => CACHE_CHECK_INTERVAL_SECS,
4811        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4812        _ => opts.poll.as_secs().max(1),
4813    };
4814    let now = Timestamp::now();
4815    if !cache_check_due(last, now, interval) {
4816        retention_service_receipt(
4817            home,
4818            operation,
4819            "dispatch",
4820            "skipped",
4821            "cadence not due",
4822            cfg,
4823        );
4824        return Ok(());
4825    }
4826    let key = format!("service:daemon-{operation}");
4827    let active = crate::worker::active(home)?;
4828    if active.iter().any(|job| job.key == key) {
4829        retention_service_receipt(
4830            home,
4831            operation,
4832            "dispatch",
4833            "skipped",
4834            "service worker already active",
4835            cfg,
4836        );
4837        return Ok(());
4838    }
4839    // Both fold the same runs; the run's owner lock already makes a collision
4840    // harmless, but one of them at a time keeps the receipts unambiguous.
4841    let sibling = match operation {
4842        "housekeeping" => Some("service:daemon-fold"),
4843        "fold" => Some("service:daemon-housekeeping"),
4844        _ => None,
4845    };
4846    if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4847        retention_service_receipt(
4848            home,
4849            operation,
4850            "dispatch",
4851            "skipped",
4852            "another finished-run folding service is active",
4853            cfg,
4854        );
4855        return Ok(());
4856    }
4857    let eligible = match operation {
4858        "conductor" => {
4859            let (queued, stalled, finished) = conductor_work(queue, home);
4860            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4861                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4862        }
4863        "maintenance" => {
4864            queue.list().iter().any(|task| {
4865                crate::triage::disk_wait_eligible(task)
4866                    && task
4867                        .disk_checked_at
4868                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4869            }) || Questions::at(home.join("questions"))
4870                .list_for_effects()
4871                .iter()
4872                .any(|q| {
4873                    q.chosen_action().is_some_and(|action| action.maintenance())
4874                        && !home
4875                            .join("choice-actions")
4876                            .join(format!("{}.json", q.id))
4877                            .exists()
4878                })
4879        }
4880        "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4881        "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4882        "cache" => {
4883            !busy
4884                && !runnable(queue).is_empty()
4885                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4886        }
4887        "disk-pressure" => busy,
4888        "fetch" => {
4889            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4890        }
4891        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4892            .list()
4893            .iter()
4894            .any(|talk| {
4895                talk.status.open()
4896                    && talk.pending.is_empty()
4897                    && talk.pending_attachments.is_empty()
4898                    && talk.goals.iter().any(|goal| goal.active())
4899            }),
4900        _ => false,
4901    };
4902    if !eligible {
4903        retention_service_receipt(
4904            home,
4905            operation,
4906            "dispatch",
4907            "skipped",
4908            match operation {
4909                "housekeeping" => "active work or runnable task queue",
4910                "fold" if cfg.is_none() => "startup configuration unavailable",
4911                "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
4912                "fold" => "idle machine; housekeeping owns finished-run folding",
4913                _ => "no active work; idle housekeeping owns scan",
4914            },
4915            cfg,
4916        );
4917        return Ok(());
4918    }
4919    retention_service_receipt(
4920        home,
4921        operation,
4922        "dispatch",
4923        "launching",
4924        "eligible and cadence due",
4925        cfg,
4926    );
4927    let request = ServiceWorker {
4928        opts: opts.absolute()?,
4929        queue: std::path::absolute(queue.root())?,
4930        worktrees_root: std::path::absolute(worktrees_root)?,
4931        operation: operation.to_owned(),
4932    };
4933    if let Err(error) = launch_service(home, &key, request).await {
4934        retention_service_receipt(
4935            home,
4936            operation,
4937            "dispatch",
4938            "error",
4939            &format!("worker launch: {error:#}"),
4940            cfg,
4941        );
4942        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4943    }
4944    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4945    Ok(())
4946}
4947
4948/// Hand `request` to a detached `daemon-service` worker reservation.
4949///
4950/// Unit tests have no `magi` executable to pin and exec as a worker, so they
4951/// may run the very same [`run_service_worker`] inline instead (and nothing
4952/// else differs: admission, cadence and receipts above are the production path).
4953async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
4954    #[cfg(test)]
4955    if INLINE_SERVICES.with(std::cell::Cell::get) {
4956        return run_service_worker(home, serde_json::to_value(request)?).await;
4957    }
4958    crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
4959    Ok(())
4960}
4961
4962#[cfg(test)]
4963thread_local! {
4964    static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4965}
4966
4967/// One bounded pass of finished-run folding (`clean::fold_turn`) with its
4968/// per-outcome counts and cursor in the service receipt. It reserves no agent
4969/// seat and takes only the locks `graph::fold_run` takes for one run at a time.
4970async fn fold_service_turn(home: &Path, opts: &Opts) {
4971    let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
4972        retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
4973    };
4974    let cfg = match prepare(&opts.repo, opts) {
4975        Ok(cfg) => cfg,
4976        Err(error) => {
4977            worker(
4978                "error",
4979                &format!("configuration: {error:#}"),
4980                None,
4981                serde_json::Value::Null,
4982            );
4983            return;
4984        }
4985    };
4986    if !cfg.disk.auto_fold {
4987        worker(
4988            "skipped",
4989            "auto_fold disabled",
4990            Some(&cfg),
4991            serde_json::Value::Null,
4992        );
4993        return;
4994    }
4995    worker(
4996        "running",
4997        "finished-run fold turn",
4998        Some(&cfg),
4999        serde_json::Value::Null,
5000    );
5001    let turn = clean::fold_turn(
5002        &home.join("runs"),
5003        home,
5004        &cfg.disk,
5005        Timestamp::now(),
5006        clean::BUSY_FOLD_BOUNDS,
5007    )
5008    .await;
5009    if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5010        tracing::info!(
5011            folded = turn.folded,
5012            failed = turn.failed,
5013            unreadable = turn.unreadable,
5014            "housekeep: finished-run fold turn"
5015        );
5016    }
5017    worker(
5018        "completed",
5019        "finished-run fold turn",
5020        Some(&cfg),
5021        serde_json::json!({ "fold": turn }),
5022    );
5023}
5024
5025/// Finite maintenance jobs survive scheduler replacement without duplicating
5026/// agent calls or cancelling an operation between its effect and receipt.
5027pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5028    let request: ServiceWorker = serde_json::from_value(payload)?;
5029    let opts = &request.opts;
5030    let queue = Queue::at(request.queue);
5031    let questions = Questions::at(home.join("questions"));
5032    match request.operation.as_str() {
5033        "chat-goals" => {
5034            let talks = crate::talk::Talks::at(home.join("talks"));
5035            crate::chat_goal_runtime::sweep(&talks, false).await;
5036        }
5037        "maintenance" => {
5038            apply_maintenance_choices(&queue, &questions, home).await;
5039            triage::monitor_disk_waits(
5040                &queue,
5041                &questions,
5042                opts.config.as_deref(),
5043                Timestamp::now(),
5044            );
5045        }
5046        "conductor" => {
5047            let path = home.join("conductor-state.json");
5048            let mut conductor = load_conductor(home)?;
5049            let (queued, stalled, finished) = conductor_work(&queue, home);
5050            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5051                && conductor.worth_a_look(&queue, &stalled, &finished)
5052            {
5053                let cfg = prepare(&opts.repo, opts)?;
5054                conductor
5055                    .maybe_run(
5056                        &cfg,
5057                        &opts.repo,
5058                        &queue,
5059                        &questions,
5060                        home,
5061                        &queued,
5062                        &stalled,
5063                        &finished,
5064                        opts.max_attempts,
5065                    )
5066                    .await;
5067                let temporary = path.with_extension("json.tmp");
5068                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5069                std::fs::rename(temporary, path)?;
5070            }
5071        }
5072        "fetch" => {
5073            let cfg = prepare(&opts.repo, opts)?;
5074            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5075                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5076                tracing::debug!("fetch origins: {outcome:?}");
5077            }
5078        }
5079        "cache" => {
5080            if task_jobs(home)?.is_empty() {
5081                let mut checked = None;
5082                maybe_prune_cache_between_runs(
5083                    &opts.repo,
5084                    opts,
5085                    home,
5086                    &Stop::new(),
5087                    &mut checked,
5088                    Timestamp::now(),
5089                )
5090                .await;
5091            }
5092        }
5093        "disk-pressure" => {
5094            if let Ok(cfg) = prepare(&opts.repo, opts) {
5095                retention_service_receipt(
5096                    home,
5097                    "disk-pressure",
5098                    "worker",
5099                    "running",
5100                    "retention sweep",
5101                    Some(&cfg),
5102                );
5103                let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5104                retention_service_receipt_with(
5105                    home,
5106                    "disk-pressure",
5107                    "worker",
5108                    "retention swept",
5109                    "retention sweep finished; cache cleanup follows",
5110                    Some(&cfg),
5111                    retention_summary(&report),
5112                );
5113                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5114                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5115                }
5116                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5117                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5118                }
5119                for current in current_work(home, Timestamp::now()) {
5120                    if let Ok(state) = RunState::load_under(&current.run, home)
5121                        && let Some(reason) = disk_gate(&state.repo, &state.config)
5122                    {
5123                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5124                            job.key.strip_prefix("task:") == Some(current.task.as_str())
5125                        }) {
5126                            request_task_park(
5127                                home,
5128                                &job,
5129                                crate::run::ParkCause::Interrupt {
5130                                    reason: reason.clone(),
5131                                },
5132                            )?;
5133                        }
5134                        notices::raise_in(
5135                            home,
5136                            Notice::warn(
5137                                "disk:pressure",
5138                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5139                            ),
5140                        );
5141                    }
5142                }
5143            } else {
5144                retention_service_receipt(
5145                    home,
5146                    "disk-pressure",
5147                    "worker",
5148                    "error",
5149                    "configuration could not be loaded",
5150                    None,
5151                );
5152            }
5153        }
5154        "fold" => fold_service_turn(home, opts).await,
5155        "housekeeping" => {
5156            if task_jobs(home)?.is_empty() {
5157                match prepare(&opts.repo, opts) {
5158                    Ok(cfg) => {
5159                        retention_service_receipt(
5160                            home,
5161                            "housekeeping",
5162                            "worker",
5163                            "running",
5164                            "retention sweep",
5165                            Some(&cfg),
5166                        );
5167                        let report =
5168                            crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5169                        retention_service_receipt_with(
5170                            home,
5171                            "housekeeping",
5172                            "worker",
5173                            "retention swept",
5174                            "retention sweep finished; janitor follows",
5175                            Some(&cfg),
5176                            retention_summary(&report),
5177                        );
5178                    }
5179                    Err(error) => retention_service_receipt(
5180                        home,
5181                        "housekeeping",
5182                        "worker",
5183                        "error",
5184                        &format!("configuration: {error:#}"),
5185                        None,
5186                    ),
5187                }
5188                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5189                resweep_superseded_attempts(&queue, home);
5190                triage_held(&queue, home, opts).await;
5191            } else {
5192                retention_service_receipt(
5193                    home,
5194                    "housekeeping",
5195                    "worker",
5196                    "skipped",
5197                    "task worker became active",
5198                    None,
5199                );
5200            }
5201        }
5202        operation => bail!("unknown daemon service {operation}"),
5203    }
5204    Ok(())
5205}
5206
5207/// Only a different request under the same key is a dispatch handoff race.
5208/// Our own unacknowledged reservation is a startup failure, not competing work:
5209/// stop dispatch without fencing it, so an already detached child may still run.
5210fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5211    let key = format!("task:{}", request.task);
5212    let payload = serde_json::to_value(request)?;
5213    if crate::worker::active(home)?
5214        .iter()
5215        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5216    {
5217        tracing::warn!(
5218            "task {} acquired a competing worker reservation: {error:#}",
5219            crate::run::short_of(&request.task)
5220        );
5221        return Ok(());
5222    }
5223    tracing::error!("task worker startup stopped dispatch: {error:#}");
5224    notices::raise_in(
5225        home,
5226        Notice::error(
5227            "loop:worker-startup",
5228            // Startup diagnostics may contain private child-process details;
5229            // keep them in the local error/log rather than the chat or notifier.
5230            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),
5231        ).link(Link::Task { id: request.task.clone() }),
5232    );
5233    Err(error).with_context(|| {
5234        format!(
5235            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5236            crate::run::short_of(&request.task)
5237        )
5238    })
5239}
5240
5241async fn poll(
5242    opts: &Opts,
5243    queue: &Queue,
5244    status: &Arc<Mutex<Status>>,
5245    home: &Path,
5246    worktrees_root: &Path,
5247    stop: &Stop,
5248    limits: DispatchLimits,
5249) -> Result<()> {
5250    let mut attempted = Vec::new();
5251    let mut settling_once_services = false;
5252    let interrupt_path = home.join("scheduler-interrupt.json");
5253    let mut interrupt = match std::fs::read(&interrupt_path) {
5254        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5255        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5256        Err(error) => return Err(error.into()),
5257    };
5258    let mut previous = std::collections::BTreeSet::<String>::new();
5259    let mut previous_skips = DispatchSkips::new();
5260    while !stop.stopped() {
5261        let jobs: Vec<_> = crate::worker::active(home)?
5262            .into_iter()
5263            .filter(|job| job.kind == "task")
5264            .collect();
5265        let requests: Vec<_> = jobs
5266            .iter()
5267            .map(|job| {
5268                serde_json::from_value::<TaskWorker>(job.payload.clone())
5269                    .with_context(|| format!("read live task worker {}", job.id))
5270            })
5271            .collect::<Result<_>>()?;
5272        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5273        let owned: std::collections::BTreeSet<_> = requests
5274            .iter()
5275            .filter(|r| !r.standalone)
5276            .map(|r| r.task.clone())
5277            .collect();
5278        let current: Vec<_> = requests
5279            .iter()
5280            .zip(&jobs)
5281            .filter(|(request, _)| !request.standalone)
5282            .map(|(request, job)| Current {
5283                worker: Some(job.id.clone()),
5284                task: request.task.clone(),
5285                run: queue
5286                    .get(&request.task)
5287                    .ok()
5288                    .and_then(|task| task.execution_runs().last().cloned())
5289                    .unwrap_or_default(),
5290            })
5291            .collect();
5292        {
5293            let mut snapshot = lock(status);
5294            snapshot.polls += 1;
5295            snapshot.completed += previous.difference(&owned).count();
5296            snapshot.current = current;
5297            snapshot.idle = owned.is_empty();
5298            snapshot.dispatch_wait = None;
5299        }
5300        previous = owned.clone();
5301        stop.busy.store(owned.len(), Ordering::SeqCst);
5302
5303        // Slots are reconstructed from durable reservations and OS-held worker
5304        // leases, not this scheduler's lifetime or mutable task urgency.
5305        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5306        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5307        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5308        let mut permits = Vec::new();
5309        sweep_stale_claims(queue, STALE_CLAIM);
5310        reclaim_orphaned_running(queue, opts.max_attempts, &live);
5311        reclaim_abandoned_runs(home, Timestamp::now());
5312        let questions = Questions::at(home.join("questions"));
5313
5314        // Deterministic: no model, run before the conductor sees anything so
5315        // its input reflects the queue's current, already-resolved state.
5316        crate::task_chat::sweep(
5317            queue,
5318            &crate::talk::Talks::at(home.join("talks")),
5319            &questions,
5320            home,
5321        );
5322        if let Err(error) = crate::task_inquiry::Outbox::at(home)
5323            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5324        {
5325            tracing::warn!("task inquiry delivery remains pending: {error:#}");
5326        }
5327        repair_choice_offers(&questions);
5328        resolve_blockers(queue, &questions);
5329        apply_task_choice_actions(queue, &questions, home);
5330        triage::apply_answers(queue, &questions);
5331        reconcile_task_questions(queue, &questions);
5332        let talks = crate::talk::Talks::at(home.join("talks"));
5333        crate::chat_notify::sweep(queue, &talks, home);
5334        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5335        crate::chat_watch::sweep(home, &talks);
5336        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5337            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5338        }
5339        let mut turns = tokio::task::JoinSet::new();
5340        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5341        // start_turns dispatches detached turns; no paid work lives in this set.
5342        while turns.join_next().await.is_some() {}
5343
5344        crate::consult::start_services(
5345            home,
5346            &opts.repo,
5347            limits.recovery_cfg.as_ref(),
5348            opts.config.as_deref(),
5349        )
5350        .await?;
5351        for operation in [
5352            "conductor",
5353            "maintenance",
5354            "housekeeping",
5355            "disk-pressure",
5356            "fold",
5357            "cache",
5358            "fetch",
5359            "chat-goals",
5360        ] {
5361            // Once an idle --once drain starts settling services, subsequent
5362            // scans only consume their effects. An expired cadence receipt
5363            // must not start another service and keep the drain alive.
5364            if settling_once_services {
5365                break;
5366            }
5367            if operation == "chat-goals" && stop.parking() {
5368                continue;
5369            }
5370            start_service(
5371                home,
5372                opts,
5373                queue,
5374                worktrees_root,
5375                operation,
5376                limits.recovery_cfg.as_ref(),
5377                !live.is_empty(),
5378            )
5379            .await?;
5380        }
5381        let latest = crate::worker::active(home)?;
5382        if latest.iter().any(|job| job.key == "service:daemon-cache")
5383            || latest
5384                .iter()
5385                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5386        {
5387            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5388            continue;
5389        }
5390        let candidates: Vec<Task> = runnable(queue)
5391            .into_iter()
5392            .filter(|task| !live.contains(&task.id))
5393            .filter(|task| !opts.once || !attempted.contains(&task.id))
5394            .collect();
5395        let in_flight: Vec<_> = owned.iter().cloned().collect();
5396        let prior_interrupt = std::mem::discriminant(&interrupt);
5397        interrupt = advance_interrupt_tick(
5398            limits.pause_for_interrupts,
5399            interrupt,
5400            &in_flight,
5401            &candidates,
5402        );
5403        // Same-variant transitions preserve their identities. Only an actual
5404        // transition needs a durable write, atomically before sending controls.
5405        if prior_interrupt != std::mem::discriminant(&interrupt) {
5406            let temporary = interrupt_path.with_extension("json.tmp");
5407            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5408            std::fs::rename(temporary, &interrupt_path)?;
5409        }
5410        if let Interrupt::Parking {
5411            parked,
5412            interrupt_task,
5413        } = &interrupt
5414        {
5415            for job in jobs.iter().filter(|job| {
5416                parked
5417                    .iter()
5418                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5419            }) {
5420                if crate::worker::control(home, &job.key)?.is_none() {
5421                    request_task_park(
5422                        home,
5423                        job,
5424                        crate::run::ParkCause::Interrupt {
5425                            reason: format!(
5426                                "task {} asked to run first",
5427                                crate::run::short_of(interrupt_task)
5428                            ),
5429                        },
5430                    )?;
5431                }
5432            }
5433        }
5434        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5435        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5436        let mut skips = interrupt_skips(&candidate_ids, &candidates);
5437        // Stable-partition immediate candidates ahead of non-immediate ones
5438        // for this poll scan only; shared `dispatch_order` stays unchanged so
5439        // upgrade-resume and ordinary priority ordering are preserved.
5440        let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5441            candidates.into_iter().partition(|task| task.immediate);
5442        immediate_candidates.extend(other_candidates);
5443        let candidates = immediate_candidates;
5444        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5445        let mut known_jobs: std::collections::BTreeSet<String> =
5446            jobs.iter().map(|job| job.id.clone()).collect();
5447        let mut started = false;
5448        let mut resync = false;
5449        for candidate in candidates {
5450            if stop.stopped() {
5451                break;
5452            }
5453            let DispatchClaim {
5454                task,
5455                claim,
5456                lane,
5457                permit,
5458            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5459                Ok(claim) => claim,
5460                Err(reason) => {
5461                    skips.insert((candidate.id, reason));
5462                    continue;
5463                }
5464            };
5465            if crate::worker::active(home)?
5466                .iter()
5467                .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5468            {
5469                drop(claim);
5470                resync = true;
5471                break;
5472            }
5473            let request = TaskWorker {
5474                opts: opts.absolute()?,
5475                queue: std::path::absolute(queue.root())?,
5476                task: task.id.clone(),
5477                lane,
5478                standalone: false,
5479            };
5480            // Keep the claim until spawn acknowledges the worker's durable
5481            // reservation. The worker then claims and re-reads before attempt.
5482            let job = match crate::worker::spawn(
5483                home,
5484                "task",
5485                &format!("task:{}", task.id),
5486                serde_json::to_value(&request)?,
5487            )
5488            .await
5489            {
5490                Ok(job) => job,
5491                Err(error) => {
5492                    task_worker_spawn_error(home, &request, error)?;
5493                    drop(claim);
5494                    resync = true;
5495                    break;
5496                }
5497            };
5498            known_jobs.insert(job.id);
5499            drop(claim);
5500            permits.extend(permit);
5501            attempted.push(task.id);
5502            started = true;
5503            // Interrupt transitions depend on the exact in-flight set (in
5504            // particular the transition from zero to one worker). Re-scan
5505            // before admitting another task, as for ordinary dispatch.
5506            if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5507                break;
5508            }
5509        }
5510        if !resync && !stop.stopped() {
5511            let per_task_skips: std::collections::BTreeMap<String, String> = skips
5512                .iter()
5513                .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5514                .collect();
5515            {
5516                let mut snapshot = lock(status);
5517                snapshot.dispatch_skips = per_task_skips;
5518                if !started {
5519                    snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5520                }
5521            }
5522            if changed_dispatch_skips(&mut previous_skips, skips) {
5523                if previous_skips.is_empty() {
5524                    tracing::info!("dispatch skips cleared");
5525                }
5526                for (task, reason) in &previous_skips {
5527                    tracing::info!(
5528                        task,
5529                        reason = reason.key(),
5530                        "task {} skipped: {}",
5531                        crate::run::short_of(task),
5532                        reason.describe()
5533                    );
5534                }
5535            }
5536        }
5537        if started || resync {
5538            continue;
5539        }
5540        if owned.is_empty() && opts.once {
5541            settling_once_services = true;
5542            // These finite services can own queue claims or publish answers.
5543            // A skipped claim is not an idle queue until they have finished;
5544            // scan again afterwards so their changes are actually scheduled.
5545            if crate::worker::active(home)?.iter().any(|job| {
5546                job.kind == "daemon-service"
5547                    && matches!(
5548                        job.key.as_str(),
5549                        "service:daemon-housekeeping"
5550                            | "service:daemon-conductor"
5551                            | "service:daemon-maintenance"
5552                    )
5553            }) {
5554                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5555                continue;
5556            }
5557            break;
5558        }
5559        stop.idle(if live.is_empty() {
5560            opts.poll
5561        } else {
5562            RECHECK_WHILE_BUSY.min(opts.poll)
5563        })
5564        .await;
5565    }
5566    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
5567    // every queue claim and Runner driver lease through outcome settlement.
5568    stop.busy.store(0, Ordering::SeqCst);
5569    {
5570        let mut snapshot = lock(status);
5571        snapshot.dispatch_wait = None;
5572        snapshot.dispatch_skips.clear();
5573    }
5574    Ok(())
5575}
5576
5577/// A maintenance pass may briefly own the same record while a worker starts.
5578/// Wait without blocking the executor or charging an agent attempt, then read
5579/// ownership again under the acquired lock. Other I/O failures still fail closed.
5580async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5581    let busy = |error: &anyhow::Error| {
5582        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5583            error.kind() == std::io::ErrorKind::WouldBlock
5584                || cfg!(windows) && error.raw_os_error() == Some(33)
5585        })
5586    };
5587    match crate::pr_head::owner_lock(home, id) {
5588        Ok(lock) => return Ok(lock),
5589        Err(error) if busy(&error) => {}
5590        Err(error) => return Err(error),
5591    }
5592    let wait = RunState::load_under(id, home)?
5593        .config
5594        .graph
5595        .timeout_resource_wait;
5596    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5597}
5598
5599/// Historical successors do not revoke a still-resumable public owner. Scan
5600/// under the same lock as publication/driver claims, and fail closed on unknown
5601/// history before spending another attempt.
5602async fn public_resume_owner(
5603    home: &Path,
5604    runs: &[String],
5605    repo: &Path,
5606) -> Result<Option<RunState>> {
5607    let mut owner = None;
5608    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5609        let _lock = resume_owner_lock(home, id).await?;
5610        let state = RunState::load_under(id, home)?;
5611        if state.released()
5612            || state.retired_to.is_some()
5613            || state.pr_taken_over_by.is_some()
5614            || !crate::handover::landing_checkpoint(&state)
5615        {
5616            continue;
5617        }
5618        anyhow::ensure!(
5619            crate::git::toplevel(&state.repo).await?.canonicalize()?
5620                == crate::git::toplevel(repo).await?.canonicalize()?,
5621            "public owner repository differs; inspect run lineage"
5622        );
5623        anyhow::ensure!(
5624            owner.is_none(),
5625            "multiple retained public owners; inspect run lineage"
5626        );
5627        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5628            anyhow::bail!(reason.diagnostic(&state));
5629        }
5630        let claimed = is_working_on_other(home, id, Timestamp::now())?;
5631        anyhow::ensure!(
5632            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5633            "public owner's driver is live or unknown; wait before retrying"
5634        );
5635        owner = Some(state);
5636    }
5637    Ok(owner)
5638}
5639
5640/// Run one claimed task to a terminal status and record the outcome.
5641///
5642/// Every transition is flushed to the queue as it happens, so the state on disk
5643/// is what actually occurred rather than what this process still intends to
5644/// write.
5645async fn attempt(
5646    opts: &Opts,
5647    queue: &Queue,
5648    status: &Arc<Mutex<Status>>,
5649    stop: &Stop,
5650    interrupt_pause: crate::graph::Pause,
5651    task: &mut Task,
5652) -> Vec<QuotaLoss> {
5653    if let Some(request) = task.sync_only.clone() {
5654        Box::pin(attempt_sync_only(
5655            queue,
5656            status,
5657            stop,
5658            interrupt_pause,
5659            task,
5660            request,
5661        ))
5662        .await;
5663        return Vec::new();
5664    }
5665    let repo = repo_for(task, &opts.repo);
5666    tracing::info!(
5667        "task {} — {} (repo {})",
5668        task.short(),
5669        task.title,
5670        repo.display()
5671    );
5672
5673    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
5674        Ok(owner) => owner,
5675        Err(e) => {
5676            task.hold_machine(Some(format!(
5677                "Cannot verify existing public owner: {e:#}; no attempt started."
5678            )));
5679            record(queue, task);
5680            return Vec::new();
5681        }
5682    };
5683    let resume_runs = public_owner
5684        .as_ref()
5685        .map(|s| vec![s.id.clone()])
5686        .unwrap_or_else(|| task.execution_runs().to_vec());
5687
5688    // A stop spends no agent resources and uses the saved landing owner.
5689    // Current roster edits, missing attachments or a failed config fetch must
5690    // never turn it into a new implementation, or prevent a PR from closing.
5691    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5692        && previous
5693            .merge_decision
5694            .as_ref()
5695            .is_some_and(|decision| !decision.closed)
5696        && previous.status != RunStatus::Landing
5697        && !crate::merge_decision::resumable_hold(&previous)
5698    {
5699        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)));
5700        record(queue, task);
5701        return Vec::new();
5702    }
5703    let stop_owner = resume_runs
5704        .last()
5705        .and_then(|id| RunState::load(id).ok())
5706        .filter(|state| {
5707            crate::merge_decision::resumable_hold(state)
5708                || state.status == RunStatus::Landing
5709                    && state.land_approval.as_ref().is_some_and(|binding| {
5710                        Questions::open()
5711                            .get_for_effects(&binding.question)
5712                            .is_ok_and(|q| {
5713                                q.run == state.id
5714                                    && q.resolution()
5715                                        .as_deref()
5716                                        .is_some_and(crate::merge_decision::stops)
5717                            })
5718                    })
5719        });
5720    if let Some(owner) = stop_owner {
5721        let mut runner = match Runner::resume(&owner.id) {
5722            Ok(runner) => runner,
5723            Err(e) => {
5724                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5725                record(queue, task);
5726                return Vec::new();
5727            }
5728        };
5729        runner.on_pause(stop.pause());
5730        runner.watch_interrupt(interrupt_pause);
5731        let quota_before = runner.state.quota.clone();
5732        let before_start = task.clone();
5733        task.start(owner.id.clone());
5734        if let Err(error) = queue.put(task) {
5735            *task = before_start;
5736            let error = runner.fail_startup("task-start", error);
5737            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5738                task.record_startup_failure(failure.clone());
5739            }
5740            task.hold_manual(Some(format!(
5741                "Could not persist task start; no agents dispatched: {error:#}"
5742            )));
5743            record(queue, task);
5744            return Vec::new();
5745        }
5746        lock(status).current.push(Current {
5747            worker: None,
5748            task: task.id.clone(),
5749            run: owner.id,
5750        });
5751        runner.state.carry_dispatched_resumes(task);
5752        runner.state.next_pass_task_entry = true;
5753        let result = runner.execute().await;
5754        return finish_attempt(
5755            opts.max_attempts,
5756            queue,
5757            task,
5758            &runner.state,
5759            &quota_before,
5760            result,
5761        );
5762    }
5763
5764    if let Some(owner) = &public_owner
5765        && (task.fresh_start || !may_resume_run(owner, task))
5766    {
5767        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)));
5768        record(queue, task);
5769        return Vec::new();
5770    }
5771
5772    if let Some(state) = task
5773        .execution_runs()
5774        .last()
5775        .and_then(|id| RunState::load(id).ok())
5776        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5777    {
5778        task.hold_machine(Some(reason));
5779        record(queue, task);
5780        return Vec::new();
5781    }
5782
5783    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5784        && !task.fresh_start
5785        && task.pr_recovery.is_none()
5786    {
5787        // A pinned infrastructure resume continues the saved reservation;
5788        // it does not authorize another base-sync interval.
5789        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5790            && task.review_branch.is_none()
5791            && task.assignment_accepts(&held)
5792            && compatible_run_instruction(&held, task)
5793            && task
5794                .resume_override
5795                .as_ref()
5796                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5797        // Exhaustion authorization still takes the owner lock and execution
5798        // lease and rechecks liveness, retained HEAD and ownership.
5799        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5800        {
5801            true
5802        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5803            let home = queue.root().parent().expect("queue has a home");
5804            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5805                Ok(()) => true,
5806                Err(error) => {
5807                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5808                    false
5809                }
5810            }
5811        } else {
5812            false
5813        };
5814        if !authorized {
5815            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())));
5816            // Retain the existing stop identity when an old release reached the queue.
5817            task.base_sync_notice(&held);
5818            task.resume_override = None;
5819            record(queue, task);
5820            return Vec::new();
5821        }
5822    }
5823    if !task.fresh_start && task.pr_recovery.is_none() {
5824        let home = queue.root().parent().expect("queue has a home");
5825        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5826            crate::land_sync_recovery::dispatch_check(queue, home, task).await
5827        {
5828            task.hold_machine(Some(reason));
5829            task.land_sync_notice(state.as_ref());
5830            task.resume_override = None;
5831            record(queue, task);
5832            return Vec::new();
5833        }
5834    }
5835    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5836        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5837            hold.apply(task);
5838            record(queue, task);
5839            return Vec::new();
5840        }
5841        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5842            run,
5843            stop_id,
5844            generation,
5845            approval_at,
5846        }) => Some((run, stop_id, generation, approval_at)),
5847        None => None,
5848    };
5849    let unfinished = (!task.fresh_start)
5850        .then(|| unfinished_run(&resume_runs, task.short()))
5851        .flatten()
5852        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5853    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5854    if task.repair_grants.last().is_some_and(|receipt| {
5855        task.execution_runs().last() == Some(&receipt.request.run)
5856            && task.operator_decided_at == receipt.decision
5857            && previous
5858                .as_ref()
5859                .is_none_or(|run| run.id != receipt.request.run)
5860    }) {
5861        task.hold_unrequested_retry(Some(
5862            "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(),
5863        ));
5864        record(queue, task);
5865        return Vec::new();
5866    }
5867    if let Some(id) = &task.disk_resume_run
5868        && unfinished.as_ref() != Some(id)
5869    {
5870        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()));
5871        record(queue, task);
5872        return Vec::new();
5873    }
5874
5875    if !task.fresh_start
5876        && task.pr_recovery.is_none()
5877        && task.review_branch.is_none()
5878        && task.resume_override.is_none()
5879        && previous
5880            .as_ref()
5881            .is_some_and(|run| run.retired_to.is_some())
5882        && unfinished.is_none()
5883    {
5884        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()));
5885        record(queue, task);
5886        return Vec::new();
5887    }
5888
5889    let saved_recovery = previous.as_ref().filter(|run| {
5890        task.replacement.is_none()
5891            && task.pr_recovery.as_ref().is_some_and(|selected| {
5892                selected
5893                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5894                    .is_ok()
5895                    && selected_starter(selected, Some(run), unfinished.as_deref())
5896                        == Starter::Resume(run.id.clone())
5897            })
5898    });
5899
5900    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
5901    // failure here is the network's or the operator's, not the task's: hold
5902    // without spending an attempt, never fall back to a possibly stale copy.
5903    let explicit = match &task.overrides {
5904        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5905        Some(_) => opts.config.as_deref(),
5906        None => opts.config.as_deref(),
5907    };
5908    let (mut config, layers) = if let Some(run) = saved_recovery {
5909        // A matching resume owns its resolved configuration and evidence;
5910        // current layers and inherited overrides only configure new work.
5911        let mut saved = run.clone();
5912        if let Err(e) = saved.configure_recovery_resume() {
5913            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5914            record(queue, task);
5915            return Vec::new();
5916        }
5917        (saved.config, Vec::new())
5918    } else {
5919        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5920            Ok(loaded) => loaded,
5921            Err(e) => {
5922                let reason = format!("[config] {e:#}");
5923                record_config_failure(task, &e);
5924                task.last_error = Some(reason.clone());
5925                task.hold_machine(Some(reason));
5926                record(queue, task);
5927                return Vec::new();
5928            }
5929        };
5930        if let Err(e) = apply_options(&mut config, opts, task) {
5931            task.hold_manual(Some(format!(
5932                "[config] {e:#}; correct the merge override before releasing the task"
5933            )));
5934            record(queue, task);
5935            return Vec::new();
5936        }
5937        if let Some(selected) = &task.pr_recovery
5938            && let Err(e) = selected.configure(&mut config)
5939        {
5940            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5941            record(queue, task);
5942            return Vec::new();
5943        }
5944        (config, layers)
5945    };
5946    let config_evidence = crate::pr_recovery::ConfigEvidence {
5947        layers,
5948        overrides: task.overrides.clone(),
5949        daemon_merge: task
5950            .overrides
5951            .as_ref()
5952            .is_none_or(|o| o.inherit_daemon_options)
5953            .then(|| opts.merge.clone())
5954            .flatten(),
5955    };
5956    apply_task_implementers(&mut config, task);
5957    if let Some(replacement) = &task.replacement {
5958        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5959            old.liveness(false) == Liveness::Dead
5960                && old.merge_decision.as_ref().is_some_and(|d| {
5961                    d.closed
5962                        && d.question == replacement.question
5963                        && d.replacement_run.as_ref().is_none_or(|run| {
5964                            task.execution_runs().last() == Some(run)
5965                                && RunState::load(run).is_ok_and(|current| {
5966                                    current.replaces.as_ref().is_some_and(|pin| {
5967                                        pin.question == replacement.question
5968                                            && pin.agent == replacement.agent
5969                                    })
5970                                })
5971                        })
5972                })
5973        });
5974        if !safe {
5975            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()));
5976            record(queue, task);
5977            return Vec::new();
5978        }
5979        match config.agent(&replacement.agent) {
5980            Ok(agent) if crate::agent::installed(agent) => {}
5981            _ => {
5982                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)));
5983                record(queue, task);
5984                return Vec::new();
5985            }
5986        }
5987        config.graph.implementers = 1;
5988        config.graph.land_approval = true;
5989        config.merge.mode = MergeMode::Pr;
5990        config.graph.selected_implementer = Some(replacement.agent.clone());
5991    }
5992    let p = phrases(&config.graph.language);
5993    let start_failed = p.could_not_start;
5994    // Resolve once for both admission and settlement. The inputs are the
5995    // task's explicit sources (never prose), plus an explicit review source's
5996    // current head; review-only runs may rebase later, and neither fact can
5997    // refund a failed automatic generation.
5998    if let Ok(base) =
5999        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6000            .await
6001        && let Ok(head) =
6002            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6003    {
6004        let mut inputs = crate::queue::recovery_inputs(&task.sources);
6005        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6006            let source = crate::git::rev_parse(&repo, branch)
6007                .await
6008                .unwrap_or_default();
6009            inputs.push_str(&format!(";review:{branch}:{source}"));
6010        }
6011        if let Some(reason) = task
6012            .recovery_exhausted(
6013                &head,
6014                &inputs,
6015                task.attempt_limit
6016                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6017            )
6018            .filter(|_| {
6019                !task.repair_grants.last().is_some_and(|receipt| {
6020                    RunState::load(&receipt.request.run)
6021                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6022                })
6023            })
6024        {
6025            task.hold_recovery_budget(
6026                reason,
6027                crate::queue::RecoveryAdmission { base: head, inputs },
6028            );
6029            record(queue, task);
6030            return Vec::new();
6031        }
6032        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6033    }
6034
6035    // A resumable run of this task is carried on, never re-competed. The
6036    // candidates are built and paid for, and a fresh competition races a
6037    // second implementation against them.
6038    //
6039    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
6040    // started 3cbf on the same task a moment later, duplicating two and a
6041    // half hours of agent work. Then b25f stalled on a judge that timed out
6042    // and one that answered with no JSON - `quota: 0`, so nothing the machine
6043    // was to blame for - and 4043 started **one second** later, buying three
6044    // fresh implementations to reach the same panel. `RunStatus::resumable`
6045    // rather than `!done()` is what catches the second case: a stall is
6046    // terminal, and its cheap recovery re-asks only the absent seats.
6047    //
6048    // A load failure is warned about rather than silently read as "not
6049    // resumable": the alternative is exactly what let a schema mismatch on
6050    // run `eba2` fall through to a full re-competition with nobody told why.
6051    // `crate::conduct` is what actually offers a better answer than
6052    // `Runner::start` here (see `Recovery::Review`), once this task's next
6053    // failure shows it up as `held`/`failed` with the run state unreadable.
6054    // Keep a retained review selection intact until disk admission succeeds.
6055    let consume_review = !previous
6056        .as_ref()
6057        .is_some_and(|state| crate::repair_budget::pending(task, state));
6058    let review_branch = consume_review
6059        .then(|| review_branch_for(task, previous.as_ref()))
6060        .flatten();
6061    let branch_exists = match review_branch {
6062        Some(branch) => crate::git::branch_exists(&repo, branch)
6063            .await
6064            .unwrap_or(false),
6065        None => false,
6066    };
6067    // An explicit `magi review <branch>` is reviewed whatever happens to the
6068    // branch unless an explicit implementer change requires fresh work. An
6069    // unfinished run of the same task still wins, so a retry resumes.
6070    let proposed = review_retry_starter(
6071        task,
6072        previous.as_ref(),
6073        review_branch,
6074        branch_exists,
6075        unfinished.as_deref(),
6076    );
6077    let retry_selected = task.replacement.is_some()
6078        && task.resumption.is_some()
6079        && !task.fresh_start
6080        && previous.as_ref().is_some_and(|run| {
6081            run.replaces.is_some()
6082                && ((run.status == RunStatus::Failed && run.viable().is_empty())
6083                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
6084        });
6085    let stop_pin = task
6086        .resume_override
6087        .as_ref()
6088        .filter(|pin| {
6089            Questions::open()
6090                .get_for_effects(&pin.question_id)
6091                .is_ok_and(|q| {
6092                    q.node == land::APPROVAL_NODE
6093                        && q.resolution()
6094                            .as_deref()
6095                            .is_some_and(crate::merge_decision::stops)
6096                })
6097        })
6098        .and_then(|pin| pin.pinned_run.clone());
6099    let granted_run = task.repair_grants.last().and_then(|receipt| {
6100        let state = RunState::load(&receipt.request.run).ok()?;
6101        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6102    });
6103    let starter = if let Some(run) = granted_run {
6104        Starter::Resume(run)
6105    } else if let Some(owner) = &public_owner {
6106        Starter::Resume(owner.id.clone())
6107    } else if let Some(run) = stop_pin {
6108        // Stop actions resume their exact owner even after seat-count edits;
6109        // they must never fall through to implementation or a takeover.
6110        Starter::Resume(run)
6111    } else if retry_selected {
6112        Starter::Resume(previous.as_ref().unwrap().id.clone())
6113    } else if let Some(selected) = &task.pr_recovery {
6114        if selected
6115            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
6116            .is_ok()
6117        {
6118            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6119        } else {
6120            Starter::Review(selected.branch.clone())
6121        }
6122    } else {
6123        starter_with_implementers(task, previous.as_ref(), proposed)
6124    };
6125    // A retained execution still writes to its saved output volume. A newer
6126    // repository policy only selects the volume for a fresh run.
6127    let disk_reason = match &starter {
6128        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6129            || {
6130                RunState::load(id)
6131                    .ok()
6132                    .and_then(|run| disk_gate(&run.repo, &run.config))
6133            },
6134            |run| disk_gate(&run.repo, &run.config),
6135        ),
6136        _ => disk_gate(&repo, &config),
6137    };
6138    if let Some(reason) = disk_reason {
6139        task.notice_cause("disk-space", None, None);
6140        task.last_error = Some(reason.clone());
6141        let disk_checked_at = task.disk_checked_at;
6142        task.hold_machine(Some(reason.clone()));
6143        if matches!(starter, Starter::Resume(_)) {
6144            task.mark_disk_capacity();
6145        } else {
6146            task.mark_startup_disk_capacity();
6147        }
6148        task.disk_checked_at = disk_checked_at;
6149        record(queue, task);
6150        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6151        notices::raise(
6152            Notice::warn(
6153                &format!("disk:{}", repo.display()),
6154                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6155            )
6156            .link(Link::Task {
6157                id: task.id.clone(),
6158            }),
6159        );
6160        return Vec::new();
6161    }
6162    let review_branch = if consume_review {
6163        let valid = review_branch.is_some();
6164        task.review_instruction = None;
6165        task.review_branch.take().filter(|_| valid)
6166    } else {
6167        None
6168    };
6169    // An explicit resume pin must never degrade into a new competition or
6170    // takeover, including when its run stops being eligible after the answer.
6171    if let Some(pin) = &task.resume_override
6172        && let Some(run) = &pin.pinned_run
6173        && starter != Starter::Resume(run.clone())
6174    {
6175        let run = run.clone();
6176        task.notice_cause("resume-owner", Some(&run), None);
6177        task.hold_machine(Some(format!(
6178            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6179            task.id
6180        )));
6181        record(queue, task);
6182        return Vec::new();
6183    }
6184    // Automatic disk recovery resumes its retained run or stops: a changed
6185    // seat count or review branch must not turn it into a new competition.
6186    // No attempt is spent here.
6187    if let Some(run) = &task.disk_resume_run
6188        && starter != Starter::Resume(run.clone())
6189    {
6190        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()));
6191        record(queue, task);
6192        return Vec::new();
6193    }
6194    if task.replacement.is_some()
6195        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6196        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6197    {
6198        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()));
6199        record(queue, task);
6200        return Vec::new();
6201    }
6202    if let Some((ref run, ..)) = head_e2e_approval
6203        && starter != Starter::Resume(run.clone())
6204    {
6205        task.hold_machine(Some(format!(
6206            "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."
6207        )));
6208        record(queue, task);
6209        return Vec::new();
6210    }
6211    if let Some(reason) = retained_attempt_hold(
6212        task,
6213        &starter,
6214        config.disk.retained_attempt_limit,
6215        RunState::load,
6216    ) {
6217        // The review choice was consumed above. Preserve it across this hold
6218        // so a later release cannot silently become a fresh implementation.
6219        if let Starter::Review(branch) = &starter {
6220            task.review_branch = Some(branch.clone());
6221        }
6222        task.hold_unrequested_retry(Some(reason));
6223        record(queue, task);
6224        return Vec::new();
6225    }
6226    // Absolute paths of the files the task was filed with, re-read from the
6227    // task now so a file attached while it was held reaches a resumed run
6228    // too. A stored name whose file has gone is an error before any agent is
6229    // paid for, never a silent omission the implementer cannot notice.
6230    let attachments = match task_attachments(queue, task) {
6231        Ok(a) => a,
6232        Err(e) => {
6233            task.attempts += 1;
6234            task.fail_startup_target(
6235                "startup-attachments",
6236                e.name.clone(),
6237                format!("{start_failed}{e:#}"),
6238                opts.max_attempts,
6239            );
6240            record(queue, task);
6241            return Vec::new();
6242        }
6243    };
6244    let startup_pause = stop.pause();
6245    let startup_interrupt = interrupt_pause.clone();
6246    let wait = crate::repo_lock::WaitPolicy::new(
6247        Duration::from_secs(config.graph.timeout_resource_wait),
6248        move || startup_pause.parked() || startup_interrupt.parked(),
6249    );
6250    // Startup includes review takeover and recovery. Do not embed its large
6251    // future in both the wait scope and the surrounding attempt stack frame.
6252    let started = wait.scope(Box::pin(async { match &starter {
6253        Starter::Review(_) if task.pr_recovery.is_some() => {
6254            let selected = task.pr_recovery.clone().expect("selected recovery");
6255            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
6256                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6257                    .await
6258                    .map(|mut r| {
6259                        r.state.attachments = attachments.clone();
6260                        r
6261                    }),
6262                Err(e) => Err(e),
6263            }
6264        }
6265        Starter::Review(branch) => {
6266            tracing::info!(
6267                "task {} reopens `{branch}` as a review-only pass",
6268                task.short()
6269            );
6270            // Every earlier attempt is superseded by the one being minted
6271            // now, so a branch one of them still holds may be taken over.
6272            let takeover = crate::handover::Takeover {
6273                earlier: task.earlier_attempts().to_vec(),
6274                home: crate::run::home(),
6275                choice: take_divergence_answer(branch, &config.merge.remote, task),
6276                task_instruction: Some(instruction_for(task)),
6277            };
6278            Runner::review_taking_over(
6279                &repo,
6280                branch,
6281                config,
6282                Some(takeover),
6283                crate::run::Origin::queue(&task.id),
6284            )
6285            .await
6286        }
6287        Starter::Resume(id) => {
6288            tracing::info!("resuming run {id} rather than competing again");
6289            Runner::resume(id).and_then(|mut r| {
6290                if retry_selected {
6291                    // The explicit queue release retries this same pinned
6292                    // implementation, preserving the attempt and worktrees.
6293                    for candidate in &mut r.state.candidates {
6294                        candidate.failed = None;
6295                        candidate.empty = false;
6296                        candidate.commits = 0;
6297                    }
6298                    r.state.status = RunStatus::Implementing;
6299                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6300                }
6301                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6302                    r.state.sources = task.sources.clone();
6303                }
6304                if r.state.prep_failure.is_some() {
6305                    let approval = task
6306                        .resumption
6307                        .as_ref()
6308                        .context("preparation retry requires an explicit task release")?;
6309                    r.retry_preparation(approval.at)?;
6310                }
6311                if let Some(instruction) =
6312                    prepare_instruction(&starter, Some(&r.state.instruction), task)
6313                {
6314                    r.state.instruction = instruction;
6315                }
6316                r.state.attachments = attachments.clone();
6317                if task.replacement.is_some() {
6318                    r.state.config.merge.mode = MergeMode::Pr;
6319                    r.state.config.graph.land_approval = true;
6320                }
6321                // Replacements publish a new PR and ask again. Selected PR
6322                // recoveries keep their saved disposition; ordinary runs can
6323                // retain the task's merge override.
6324                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6325                    .overrides
6326                    .as_ref()
6327                    .and_then(|o| o.merge.as_deref())
6328                    .and_then(|m| merge_mode(m).ok())
6329                {
6330                    r.state.config.merge.mode = mode;
6331                }
6332                Ok(r)
6333            })
6334        }
6335        Starter::Start => {
6336            if let Some(branch) = &review_branch {
6337                tracing::warn!(
6338                    "conductor chose review for task {} but branch `{branch}` no longer \
6339                     exists; requeuing as a fresh competition instead",
6340                    task.short()
6341                );
6342            }
6343            let instruction = prepare_instruction(&starter, None, task)
6344                .unwrap_or_else(|| task.instruction.clone());
6345            Runner::start_naming(
6346                &repo,
6347                instruction,
6348                &task.title,
6349                config,
6350                crate::run::Origin::queue(&task.id),
6351            )
6352            .await
6353            .map(|mut r| {
6354                r.state.attachments = attachments.clone();
6355                r.state.sources = task.sources.clone();
6356                r
6357            })
6358        }
6359    }})).await;
6360    if let Err(error) = &started
6361        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6362    {
6363        task.record_startup_failure(failure.clone());
6364    }
6365    let mut runner = match started {
6366        Ok(r) => r,
6367        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6368            let detail = format!("{e:#}");
6369            task.last_error = Some(detail.clone());
6370            if e.is::<crate::build_target::AdmissionDiskWait>()
6371                && let Starter::Review(branch) = &starter
6372                && review_branch.is_some()
6373            {
6374                task.review_branch = Some(branch.clone());
6375                task.review_instruction = Some(task.instruction.clone());
6376            }
6377            if stop.parking() || interrupt_pause.parked() {
6378                let attempts = task.attempts;
6379                task.park(e.to_string());
6380                // Startup has not spent an attempt to refund.
6381                task.attempts = attempts;
6382            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6383                let disk_checked_at = task.disk_checked_at;
6384                task.hold_machine(Some(detail));
6385                task.mark_startup_disk_capacity();
6386                task.disk_checked_at = disk_checked_at;
6387            } else {
6388                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6389            }
6390            record(queue, task);
6391            return Vec::new();
6392        }
6393        // A branch an earlier attempt still holds and magi will not release
6394        // by itself is the operator's call, not a failed attempt: hold the
6395        // task with the reason, spend nothing, and say so on the bell.
6396        Err(e) if task.pr_recovery.is_some() => {
6397            task.startup_notice_cause("startup-public-head");
6398            task.attempts += 1;
6399            task.last_error = Some(format!("{start_failed}{e:#}"));
6400            task.hold_unrequested_retry(Some(format!(
6401                "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."
6402            )));
6403            record(queue, task);
6404            return Vec::new();
6405        }
6406        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6407            let detail = match e.downcast_ref::<crate::handover::Refused>() {
6408                Some(r) => (p.handover_refused)(r),
6409                None => format!("{e:#}"),
6410            };
6411            task.startup_notice_cause("startup-handover");
6412            let reason = format!("{start_failed}{detail}");
6413            task.last_error = Some(reason.clone());
6414            // Consumed above by `take`; keep it so the released task retries
6415            // as a review of this same branch.
6416            let branch = match &starter {
6417                Starter::Review(branch) => Some(branch.clone()),
6418                _ => None,
6419            };
6420            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
6421            // one page; the guidance rides in the reason, fixed per state so a
6422            // re-put never changes the wording and relights it.
6423            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6424            record(queue, task);
6425            tracing::warn!(
6426                "holding {} for a branch it cannot take over: {e:#}",
6427                task.short()
6428            );
6429            return Vec::new();
6430        }
6431        // A branch that differs between here and the remote in ways magi
6432        // cannot prove are the same change is a decision for the owner, not a
6433        // failed attempt: ask with both sides laid out, spend no attempt, and
6434        // let the answer requeue the task.
6435        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6436            let d = e
6437                .downcast_ref::<crate::reconcile::Diverged>()
6438                .expect("checked by the guard");
6439            let mut q = ask::Question::new(
6440                task.id.clone(),
6441                crate::reconcile::NODE.to_owned(),
6442                crate::reconcile::SEAT.to_owned(),
6443                d.summary(),
6444                d.detail(),
6445                d.choices(),
6446            );
6447            match Questions::open().put(&mut q) {
6448                Ok(()) => {
6449                    task.last_error = Some(format!("{e:#}"));
6450                    // Consumed above by `take`; the answer has to reach a review
6451                    // of this same branch, so keep pointing the task at it.
6452                    task.review_branch = Some(d.branch.clone());
6453                    task.review_instruction = Some(task.instruction.clone());
6454                    task.block(vec![q.id.clone()], Some(d.summary()));
6455                }
6456                Err(put) => {
6457                    tracing::warn!("could not file the divergence question: {put:#}");
6458                    task.attempts += 1;
6459                    task.fail_startup(
6460                        "startup-question-store",
6461                        format!("{start_failed}{e:#}"),
6462                        opts.max_attempts,
6463                    );
6464                }
6465            }
6466            record(queue, task);
6467            return Vec::new();
6468        }
6469        Err(e) => {
6470            // The answer was stale and nothing was applied: keep pointing at
6471            // the branch so the next attempt asks again against its new tips.
6472            // Nothing went wrong with the task, so no attempt is spent: a
6473            // budget one short of its limit must not hold it instead of
6474            // letting the question be asked again.
6475            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6476                && let Starter::Review(branch) = &starter
6477            {
6478                task.review_branch = Some(branch.clone());
6479                task.review_instruction = Some(task.instruction.clone());
6480                task.last_error = Some(format!("{start_failed}{e:#}"));
6481                task.status = crate::queue::TaskStatus::Failed;
6482                record(queue, task);
6483                return Vec::new();
6484            }
6485            task.attempts += 1;
6486            task.last_error = Some(format!("{start_failed}{e:#}"));
6487            task.startup_notice_cause("startup-source");
6488            task.hold_unrequested_retry(Some(format!(
6489                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6490            )));
6491            record(queue, task);
6492            return Vec::new();
6493        }
6494    };
6495    if !matches!(starter, Starter::Resume(_))
6496        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6497    {
6498        runner
6499            .state
6500            .event("build-cache", format!("{mode} selected by {source}"));
6501    }
6502    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6503        runner.state.recovery_config = Some(config_evidence);
6504    }
6505    if let Some(replacement) = &task.replacement {
6506        if matches!(starter, Starter::Start) {
6507            runner.state.instruction.push_str(&format!(
6508                "\n\n# Replacement review context\n{}",
6509                replacement.context
6510            ));
6511        }
6512        runner.state.replaces = Some(replacement.clone());
6513        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6514        if let Ok(mut old) = RunState::load(&replacement.run)
6515            && let Some(d) = &mut old.merge_decision
6516        {
6517            d.replacement_run = Some(runner.state.id.clone());
6518            old.event(
6519                "replacement",
6520                format!(
6521                    "replacement run {} owns the next attempt; old PR remains closed",
6522                    runner.state.id
6523                ),
6524            );
6525            if let Err(e) = old.save() {
6526                let error = runner.fail_startup("replacement-history", e);
6527                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6528                    task.record_startup_failure(failure.clone());
6529                }
6530                task.hold_manual(Some(format!(
6531                    "Could not link replacement history: {error:#}; no agents dispatched"
6532                )));
6533                record(queue, task);
6534                return Vec::new();
6535            }
6536        }
6537    }
6538    runner.state.task_instruction = Some(task.instruction.clone());
6539    // The follow-up depth is fixed now, while the task certainly exists:
6540    // deleting it later must not reset the cap (`crate::followup`).
6541    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6542    if runner.state.origin_chat.is_none() {
6543        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6544    }
6545    // A stop that means "park" reaches the graph through this handle.
6546    runner.on_pause(stop.pause());
6547    // `poll`'s interrupt scheduler reaches this one run - and no other -
6548    // through this handle. See `Pause`'s own doc for why these are never
6549    // the same one.
6550    runner.watch_interrupt(interrupt_pause);
6551
6552    // `start` has minted the run, so the task can now point at it. Persisting
6553    // `Running` before `execute` is what makes a crash mid-run legible.
6554    let run = runner.state.id.clone();
6555    let before_start = task.clone();
6556    task.start(run.clone());
6557    if let Err(error) = queue.put(task) {
6558        *task = before_start;
6559        let error = runner.fail_startup("task-start", error);
6560        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6561            task.record_startup_failure(failure.clone());
6562        }
6563        task.hold_manual(Some(format!(
6564            "Could not persist task start; no agents dispatched: {error:#}"
6565        )));
6566        record(queue, task);
6567        return Vec::new();
6568    }
6569    if task.status != TaskStatus::Running {
6570        // Queue::put kept a newer hold or continuation instead of this start.
6571        return Vec::new();
6572    }
6573    lock(status).current.push(Current {
6574        worker: None,
6575        task: task.id.clone(),
6576        run,
6577    });
6578
6579    // `RunState::quota` is the run's whole history across every resume, so
6580    // only what this execution added may arm the cooldown or earn a refund.
6581    let quota_before = runner.state.quota.clone();
6582    runner.state.carry_dispatched_resumes(task);
6583    runner.state.entry_resumption_generation =
6584        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6585    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6586        && runner.state.id == run
6587    {
6588        crate::head_e2e_stop::record_consumed_approval(
6589            &mut runner.state,
6590            &task.id,
6591            &stop_id,
6592            generation,
6593            approval_at,
6594        );
6595    }
6596    runner.state.next_pass_task_entry = true;
6597    let result = runner.execute().await;
6598    finish_attempt(
6599        opts.max_attempts,
6600        queue,
6601        task,
6602        &runner.state,
6603        &quota_before,
6604        result,
6605    )
6606}
6607
6608async fn attempt_sync_only(
6609    queue: &Queue,
6610    status: &Arc<Mutex<Status>>,
6611    stop: &Stop,
6612    interrupt: crate::graph::Pause,
6613    task: &mut Task,
6614    request: crate::base_sync_only::Request,
6615) {
6616    let result = async {
6617        anyhow::ensure!(
6618            task.status == TaskStatus::Queued
6619                && task.execution_runs().last() == Some(&request.run)
6620                && task.resume_override.as_ref().is_some_and(
6621                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6622                ),
6623            "sync-base-only request no longer owns the exact queued run"
6624        );
6625        let mut runner = Runner::resume(&request.run)?;
6626        anyhow::ensure!(
6627            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6628                .await?
6629                .is_none(),
6630            "the task still has a public execution owner"
6631        );
6632        anyhow::ensure!(
6633            !stop.parking() && !interrupt.parked(),
6634            "paused before base synchronization"
6635        );
6636        let original = task.clone();
6637        task.start(request.run.clone());
6638        task.attempts = original.attempts;
6639        if let Err(error) = queue.put(task) {
6640            *task = original;
6641            return Err(error);
6642        }
6643        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6644            return Ok(());
6645        }
6646        lock(status).current.push(Current {
6647            worker: None,
6648            task: task.id.clone(),
6649            run: request.run.clone(),
6650        });
6651        runner.on_pause(stop.pause());
6652        runner.watch_interrupt(interrupt);
6653        runner.execute_sync_only(request.clone()).await
6654    }
6655    .await;
6656    if task.sync_only.as_ref() == Some(&request) {
6657        let saved = RunState::load(&request.run).ok();
6658        let detail = result.err().map(|error| {
6659            format!("Base synchronization only: {error:#}; verification was not allowed")
6660        });
6661        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6662        record(queue, task);
6663    }
6664}
6665
6666/// Settle `task` after its run executed: the verdict, the diagnosis, the
6667/// supersession of earlier attempts and the save. Shared by the loop and by
6668/// `magi run --resume`, so an attempt is counted one way wherever it ran.
6669/// Returns the quota losses this execution added to the run.
6670pub fn finish_attempt(
6671    max_attempts: usize,
6672    queue: &Queue,
6673    task: &mut Task,
6674    state: &RunState,
6675    quota_before: &[QuotaLoss],
6676    result: Result<()>,
6677) -> Vec<QuotaLoss> {
6678    let detail = match result {
6679        Ok(()) => describe(state),
6680        Err(e) => format!("{e:#}"),
6681    };
6682    let fresh = losses_this_attempt(quota_before, &state.quota);
6683    let verdict = Verdict {
6684        status: state.status,
6685        // A run that opened a pull request handed its work over, whatever the
6686        // gate then decided about merging it.
6687        left_pr: state.pr.is_some(),
6688        // Only a rate limit earns the task its attempt back - and only one
6689        // suffered now: a refund justified by a previous session's loss is
6690        // the same mistake as re-arming the cooldown from it. A stalled run
6691        // resumed without hitting quota again therefore spends its attempt,
6692        // like any other failure of the task's own.
6693        quota_hit: !fresh.is_empty(),
6694        // A run that parked was asked to stop; that is not a failure and must
6695        // not spend an attempt, or replacing the binary a few times would
6696        // exhaust a task's budget without an agent ever misbehaving.
6697        parked: state.parked,
6698        // A quota loss that left nothing viable is the same machine fact as a
6699        // `Stalled` quota loss; see `settle`'s doc table.
6700        no_viable_candidates: state.viable().is_empty(),
6701    };
6702    if let Some(replacement) = &state.replaces
6703        && let Some(pr) = &state.pr
6704        && let Ok(mut old) = RunState::load(&replacement.run)
6705        && let Some(d) = &mut old.merge_decision
6706    {
6707        d.replacement_pr = Some(pr.url.clone());
6708        let _ = old.save();
6709    }
6710    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6711    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6712        task.hold_unrequested_retry(Some(format!(
6713            "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.",
6714            task.short()
6715        )));
6716    }
6717    if task.status == TaskStatus::Done {
6718        supersede_prior_runs(task, &crate::run::home());
6719    }
6720    record(queue, task);
6721    tracing::info!(
6722        "task {} is {} after run {} ({})",
6723        task.short(),
6724        task.status.as_str(),
6725        state.short(),
6726        label(state.status)
6727    );
6728    fresh
6729}
6730
6731/// A task a hand-started run leaves runnable (failed with attempts to spare,
6732/// or requeued) is **held**: nobody asked for a retry, and a loop starting
6733/// later must not spend agent calls on it. `magi task release` retries.
6734pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6735    // Parked work (including legacy Failed records with a parked run) is a
6736    // checkpoint or owner handoff, not an unrequested retry.
6737    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6738        && !awaiting_resume_with(task, RunState::load)
6739        // A run parked on the owner's word about a withheld PR title/body
6740        // resumes via `land_resume_state`, including review-only tasks that
6741        // `awaiting_resume_with` does not consider.
6742        && withheld_text_wait(task).is_none()
6743        && !(task.fresh_start && task.replacement.is_some())
6744    {
6745        let why = task.last_error.clone().map_or_else(
6746            || "the run did not finish".to_owned(),
6747            |e| format!("the run did not finish: {e}"),
6748        );
6749        task.hold_unrequested_retry(Some(format!(
6750            "{why}. It was started by hand, so it is not retried \
6751             automatically; `magi task release` retries it."
6752        )));
6753        record(queue, task);
6754    }
6755}
6756
6757/// Whether an attempt at a task whose newest run is `run` would resume that
6758/// run rather than start a fresh competition. `magi run --resume` hands a run
6759/// to a live loop only when this holds.
6760#[must_use]
6761pub fn loop_would_resume(run: &str) -> bool {
6762    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6763}
6764
6765/// A loop in another process that is alive right now: a fresh heartbeat in
6766/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
6767/// carries the pid it published (`None` inside when it published none - a
6768/// fresh heartbeat is still evidence of a live loop).
6769///
6770/// The one judgement of "is somebody else serving this queue", shared by the
6771/// web UI's refusal to start a second loop and by `magi run` / `magi review`
6772/// deciding whether to hand a task to the loop. A claim file proves nothing
6773/// here: whether a claim succeeds says nothing about whether its owner lives.
6774#[must_use]
6775pub fn foreign_loop(
6776    reading: Option<&Reading>,
6777    now: Timestamp,
6778    own_pid: u32,
6779) -> Option<Option<u32>> {
6780    let reading = reading.filter(|r| r.running(now))?;
6781    match reading.pid {
6782        Some(pid) if pid == own_pid => None,
6783        pid => Some(pid),
6784    }
6785}
6786
6787fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6788    reading.worker_protocol != Some(1)
6789        && (foreign_loop(Some(reading), now, own_pid).is_some()
6790            || reading
6791                .pid
6792                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6793}
6794
6795/// Low-level claimed-task execution shared by the detached standalone worker
6796/// and focused lifecycle fixtures. The caller must retain the queue claim for
6797/// this entire call. CLI callers transfer ownership through
6798/// [`run_detached_claimed`] instead of executing inside their own runtime.
6799///
6800/// The one deliberate difference from the loop: a task the attempt leaves
6801/// runnable (failed with attempts to spare, or requeued) is **held** instead.
6802/// Nobody asked for a retry, and a daemon starting later must not spend agent
6803/// calls re-running a hand-started task behind the operator's back;
6804/// `magi task release` is the explicit retry.
6805pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6806    run_claimed_until(opts, queue, task, &Stop::new()).await;
6807}
6808
6809async fn run_claimed_until(
6810    opts: &Opts,
6811    queue: &Queue,
6812    task: &mut Task,
6813    stop: &Stop,
6814) -> Vec<QuotaLoss> {
6815    let status = Arc::new(Mutex::new(Status::new()));
6816    // An attempt embeds startup and graph futures. Keep it off the standalone
6817    // caller's stack, on both the initial execution and withheld-text resume.
6818    let mut quota = Box::pin(attempt(
6819        opts,
6820        queue,
6821        &status,
6822        stop,
6823        crate::graph::Pause::new(),
6824        task,
6825    ))
6826    .await;
6827    // A run parked on the owner's word about a withheld PR title/body has no
6828    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
6829    // here with the claim still held, and resume once the question is settled
6830    // (answered, or abandoned at its deadline -> the neutral text).
6831    // A rejected reply files one more question (the gate asks at most twice),
6832    // so after a resume the run may be waiting again: keep going, with a fresh
6833    // limit for the new question. `resumes` bounds it even if a resume parks
6834    // without asking anything new.
6835    let mut resumes = 0;
6836    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6837        let Some(timeout) = withheld_text_wait(task) else {
6838            break;
6839        };
6840        eprintln!(
6841            "waiting for the owner's answer on a withheld pull request text \
6842             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6843        );
6844        // The deadline abandons the question itself; the extra margin only
6845        // covers an abandon that could not be saved.
6846        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6847        let ready = loop {
6848            match land_resume_state(task) {
6849                LandResume::StillWaiting
6850                    if !stop.parking() && std::time::Instant::now() < limit =>
6851                {
6852                    tokio::time::sleep(WITHHELD_POLL).await;
6853                }
6854                LandResume::Ready => break true,
6855                _ => break false,
6856            }
6857        };
6858        if !ready || stop.parking() {
6859            break;
6860        }
6861        resumes += 1;
6862        quota.extend(
6863            Box::pin(attempt(
6864                opts,
6865                queue,
6866                &status,
6867                stop,
6868                crate::graph::Pause::new(),
6869                task,
6870            ))
6871            .await,
6872        );
6873    }
6874    hold_if_runnable(queue, task);
6875    quota
6876}
6877
6878/// Resumes an in-process run makes for withheld-text questions: the gate asks
6879/// at most twice, plus one for a resume that asks nothing new.
6880const MAX_WITHHELD_RESUMES: u32 = 3;
6881
6882/// How often an in-process run rechecks its withheld-text question.
6883const WITHHELD_POLL: Duration = Duration::from_secs(15);
6884
6885/// The `answer_timeout` (seconds) of the task's last run when that run is
6886/// parked on an unresolved withheld-text question; `None` otherwise.
6887fn withheld_text_wait(task: &Task) -> Option<u64> {
6888    let id = task.execution_runs().last()?;
6889    let s = RunState::load(id).ok()?;
6890    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6891        .then_some(s.config.graph.answer_timeout)
6892}
6893
6894/// The quota losses `after` holds that `before` did not: what one execution
6895/// suffered, as opposed to the run's history.
6896///
6897/// Compared by value rather than by length or position because
6898/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
6899/// the vector can shrink and shift under a resume. A retried seat that hits
6900/// quota again is a `push` with a new `at`, so it shows up as new here.
6901/// Crash recovery uses the recorded pass start as its boundary when available;
6902/// legacy records without passes retain their original history-based policy.
6903fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6904    after
6905        .iter()
6906        .filter(|q| !before.contains(q))
6907        .cloned()
6908        .collect()
6909}
6910
6911/// When the loop-wide quota cooldown should end, given this attempt's losses;
6912/// `None` when there were none. Reset-hint parsing and the cap live here.
6913fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6914    let quota: Vec<_> = quota
6915        .iter()
6916        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6917        .collect();
6918    if quota.is_empty() {
6919        return None;
6920    }
6921    let with_hint = quota.iter().find(|q| q.reset.is_some());
6922    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6923    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6924    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6925    Some(
6926        now.checked_add(jiff::SignedDuration::from_secs(secs))
6927            .unwrap_or(Timestamp::MAX),
6928    )
6929}
6930
6931/// An explicit task count must agree with a run before any resume.
6932fn implementers_match(task: &Task, state: &RunState) -> bool {
6933    task.replacement.as_ref().map_or_else(
6934        || {
6935            task.implementers()
6936                .is_none_or(|n| n == state.config.graph.implementers)
6937        },
6938        |replacement| {
6939            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6940                && state.config.graph.implementers == 1
6941        },
6942    )
6943}
6944
6945/// Never resume or take over candidate work built for a different seat count.
6946fn starter_with_implementers(
6947    task: &Task,
6948    previous: Option<&RunState>,
6949    proposed: Starter,
6950) -> Starter {
6951    if previous.is_some_and(|s| !implementers_match(task, s)) {
6952        task.review_of
6953            .as_ref()
6954            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6955    } else {
6956        proposed
6957    }
6958}
6959
6960/// Apply this task's explicit count to the new attempt, without changing defaults.
6961fn apply_task_implementers(config: &mut Config, task: &Task) {
6962    if let Some(n) = task.implementers() {
6963        config.graph.implementers = n;
6964    }
6965}
6966
6967/// [`prepare`] for one task: its own `--config` and command-line overrides
6968/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
6969/// over the loop's, so handing a hand-started task to a daemon changes nothing
6970/// about what it does.
6971#[cfg(test)]
6972fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6973    let explicit = match &task.overrides {
6974        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6975        _ => opts.config.as_deref(),
6976    };
6977    let (mut config, _) = Config::discover(repo, explicit)?;
6978    apply_options(&mut config, opts, task)?;
6979    Ok(config)
6980}
6981
6982fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6983    if task
6984        .overrides
6985        .as_ref()
6986        .is_none_or(|o| o.inherit_daemon_options)
6987        && let Some(mode) = opts.merge.as_deref()
6988    {
6989        config.merge.mode = merge_mode(mode)?;
6990    }
6991    if let Some(o) = &task.overrides {
6992        o.apply(config);
6993    }
6994    if let Some((mode, _)) = task.build_cache_override(config) {
6995        config.verify.build_cache = mode;
6996    }
6997    Ok(())
6998}
6999
7000/// Load the config for a task's repository, with the merge override applied.
7001fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7002    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7003    if let Some(mode) = &opts.merge {
7004        config.merge.mode = merge_mode(mode)?;
7005    }
7006    Ok(config)
7007}
7008
7009/// Prune the shared build cache at a between-runs boundary. The detached cache
7010/// service checks authoritative task jobs first; dispatch waits for that finite
7011/// service, so scheduler replacement cannot turn a compile into idle cleanup.
7012/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
7013async fn maybe_prune_cache_between_runs(
7014    repo: &Path,
7015    opts: &Opts,
7016    home: &Path,
7017    stop: &Stop,
7018    last_checked: &mut Option<Timestamp>,
7019    now: Timestamp,
7020) {
7021    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7022        return;
7023    }
7024    *last_checked = Some(now);
7025    let cfg = match prepare(repo, opts) {
7026        Ok(cfg) => cfg,
7027        Err(e) => {
7028            tracing::warn!("cache check: no config: {e:#}");
7029            return;
7030        }
7031    };
7032    match clean::prune_cache_if_over_limit(&cfg, home) {
7033        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7034            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7035            pruned.files,
7036            pruned.freed
7037        ),
7038        Ok(_) => {}
7039        Err(e) => {
7040            tracing::warn!("housekeep: prune cache: {e:#}");
7041            notices::raise_in(
7042                home,
7043                Notice::warn(
7044                    "housekeep:cache",
7045                    format!(
7046                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7047                        e.to_string()
7048                            .lines()
7049                            .next()
7050                            .unwrap_or("unknown cleanup error")
7051                    ),
7052                ),
7053            );
7054        }
7055    }
7056}
7057
7058/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
7059/// now, given when it last did (if ever). Pure, so the cadence is asserted
7060/// directly rather than by waiting out real minutes in a test.
7061fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7062    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7063}
7064
7065/// The disk janitor, with its housekeeping logged rather than fatal.
7066///
7067/// Called only at the loop's idle points, for the reason the caller documents:
7068/// a prune racing a live compile would delete files mid-build. The config is
7069/// re-read on every call because the repository that just ran may not be the
7070/// daemon's own default, and the cache directory is a repository fact.
7071///
7072/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
7073/// and [`crate::run::default_worktree_root`] read here, for the same reason
7074/// [`drive`] takes its queue and status file rather than resolving them: a
7075/// test driving the loop must not reach through to the operator's real home
7076/// or worktree bay just because the janitor runs on every idle tick.
7077/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
7078/// to get wrong silently - a test's `home` was already isolated, but nothing
7079/// exercised the parameter next to it, so a real worktree bay stayed wired in
7080/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
7081/// it for real, every test in this file that drives the loop at all started
7082/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
7083async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7084    let cfg = match prepare(repo, opts) {
7085        Ok(cfg) => cfg,
7086        Err(e) => {
7087            tracing::warn!("housekeep: no config: {e:#}");
7088            return;
7089        }
7090    };
7091    // A run's own worktree lives under `config.graph.worktree_root` when the
7092    // repository sets one - the same precedence `RunState::worktree_root`
7093    // uses - and `worktrees_root` only stands in for the *default* an
7094    // unconfigured repository resolves to (see this function's own
7095    // parameter, or the test fixture wiring one to a fake path). Housekeeping
7096    // that always swept the default regardless of this override would never
7097    // see, and so never reclaim, a single worktree for a repository that
7098    // relocated them elsewhere.
7099    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7100    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7101    // Reported whenever there is anything to say, not only when `folded > 0`:
7102    // the incident this exists to prevent was 90 of 93 runs skipped and 0
7103    // folded, on every single pass, for months - a report gated on `folded`
7104    // would have stayed silent through every one of them.
7105    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7106        let mut extra = Vec::new();
7107        if out.unreadable > 0 {
7108            extra.push(format!("{} unreadable", out.unreadable));
7109        }
7110        if out.orphaned_worktrees > 0 {
7111            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7112        }
7113        let detail = if extra.is_empty() {
7114            String::new()
7115        } else {
7116            format!(" ({})", extra.join(", "))
7117        };
7118        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7119    }
7120    if out.external_merges_recorded > 0 {
7121        tracing::info!(
7122            "housekeep: recorded {} run(s) as merged externally",
7123            out.external_merges_recorded
7124        );
7125    }
7126    if out.stale_pr_states_repaired > 0 {
7127        tracing::info!(
7128            "housekeep: rewrote {} run record(s) whose pull request had already settled",
7129            out.stale_pr_states_repaired
7130        );
7131    }
7132    if out.cache_files > 0 {
7133        tracing::info!(
7134            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7135            out.cache_files,
7136            out.cache_freed
7137        );
7138    }
7139    if out.questions_abandoned > 0 {
7140        tracing::info!(
7141            "housekeep: abandoned {} question(s) left open by a finished run",
7142            out.questions_abandoned
7143        );
7144    }
7145}
7146
7147/// Run [`triage::run_once`] and log whatever it did, the same "only when
7148/// there is something to say" rule [`janitor`] follows for its own report.
7149///
7150/// Called at the same idle points as [`janitor`] - once per full poll
7151/// interval, never mid-attempt - for the same reason: it is not liveness
7152/// critical, and a task's own `hold_reason` string is the one thing this
7153/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
7154/// tick for no benefit.
7155async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7156    let questions = Questions::at(home.join("questions"));
7157    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7158    if report.is_empty() {
7159        return;
7160    }
7161    if !report.quarantined.is_empty() {
7162        tracing::info!(
7163            "triage: held {} blocked task(s) whose blocked-on task or \
7164             question no longer exists: {}",
7165            report.quarantined.len(),
7166            report.quarantined.join(", ")
7167        );
7168    }
7169    if !report.resumed.is_empty() {
7170        tracing::info!(
7171            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7172            report.resumed.len(),
7173            report.resumed.join(", ")
7174        );
7175    }
7176    if !report.asked.is_empty() {
7177        tracing::info!(
7178            "triage: asked about {} held task(s): {}",
7179            report.asked.len(),
7180            report.asked.join(", ")
7181        );
7182    }
7183    if !report.answered.is_empty() {
7184        tracing::info!(
7185            "triage: applied {} operator answer(s): {}",
7186            report.answered.len(),
7187            report.answered.join(", ")
7188        );
7189    }
7190}
7191
7192/// The free-space gate: what stands between this task and a new run, if
7193/// anything. `Some(reason)` holds the task; `None` lets it start.
7194///
7195/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
7196/// the operator opted out. A measurement failure is a gate, not a pass: both
7197/// sides of "cannot tell" are served by not starting.
7198pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7199    disk_gate_at(repo, config, crate::run::home)
7200}
7201
7202pub(crate) fn disk_gate_at(
7203    repo: &Path,
7204    config: &Config,
7205    home: impl FnOnce() -> PathBuf,
7206) -> Option<String> {
7207    let measure = if crate::build_target::isolated(config) {
7208        crate::disk::managed_free_bytes
7209    } else {
7210        crate::disk::free_bytes
7211    };
7212    disk_gate_with(repo, config, home, measure)
7213}
7214
7215/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
7216/// test can assert the exact wiring `attempt` runs - config's threshold in,
7217/// task-holding reason out - without asking the real machine's disk anything.
7218fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7219    repo: &Path,
7220    config: &Config,
7221    home: impl FnOnce() -> PathBuf,
7222    free_bytes: F,
7223) -> Option<String> {
7224    let min = config.disk.min_free_bytes;
7225    if min == 0 {
7226        return None;
7227    }
7228    let output = match config.verify.build_cache {
7229        BuildCache::Shared => config.cache_dir(),
7230        BuildCache::Isolated => Some(home()),
7231    };
7232    let default_worktree_root;
7233    let worktree_root = match config.graph.worktree_root.as_deref() {
7234        Some(root) => root,
7235        None => {
7236            default_worktree_root = crate::run::default_worktree_root();
7237            &default_worktree_root
7238        }
7239    };
7240    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7241        .into_iter()
7242        .flatten()
7243    {
7244        let probe = if path == repo {
7245            path
7246        } else {
7247            path.ancestors().find(|p| p.exists()).unwrap_or(path)
7248        };
7249        let reason = match free_bytes(probe) {
7250            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7251            Err(e) => Some(crate::disk::unmeasured_in(
7252                probe,
7253                &e,
7254                &config.graph.language,
7255            )),
7256        };
7257        if reason.is_some() {
7258            return reason;
7259        }
7260    }
7261    None
7262}
7263
7264/// How long to wait before offering another task when a run lost a seat to a
7265/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
7266/// could read, or carried nothing at all. Long enough that a quota outage
7267/// cannot burn through a whole backlog in the few seconds each doomed attempt
7268/// takes to fail; short enough that a quota which clears early is not left
7269/// idle for the fallback's sake.
7270const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7271
7272/// Longest a parsed reset hint may push the wait out to. The hint comes from
7273/// the CLI's own words, not a contract, so a parsing slip that lands a day
7274/// away must not leave the loop asleep for a day.
7275const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7276
7277/// How long [`poll`] should wait before offering the next task, after a run
7278/// lost at least one seat to a rate limit.
7279///
7280/// Pure and separate from the loop so the policy can be exercised without a
7281/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
7282/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
7283/// nothing to parse, or the parsed time has already passed; `cap` bounds how
7284/// far a parsed hint is trusted to push the wait out.
7285fn quota_wait(
7286    reset_at: Option<Timestamp>,
7287    now: Timestamp,
7288    fallback: Duration,
7289    cap: Duration,
7290) -> Duration {
7291    match reset_at {
7292        Some(at) if at > now => {
7293            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7294            Duration::from_secs(secs).min(cap)
7295        }
7296        _ => fallback,
7297    }
7298}
7299
7300/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
7301///
7302/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
7303/// explains why parsing it exactly "would be a bug factory" — so this only
7304/// recognises the shapes actually observed in the wild, and returns `None`
7305/// for anything else rather than guess at a format nobody has seen.
7306///
7307/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
7308/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
7309/// said it, not from whenever this loop happens to read it: anchoring on `now`
7310/// would push the reset later on every read and would read an already-elapsed
7311/// reset as still in the future. (A long hint is still clamped by
7312/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
7313fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7314    parse_reset_hint_zoned(text, now)
7315        .or_else(|| parse_reset_hint_dated(text))
7316        .or_else(|| parse_reset_hint_relative(text, recorded))
7317}
7318
7319/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
7320/// optional but at least one required, in that order. A bare number or any
7321/// unknown unit is refused.
7322fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7323    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7324    let mut rest = rest.trim();
7325    if rest.is_empty() {
7326        return None;
7327    }
7328    let mut total: i64 = 0;
7329    let mut matched = false;
7330    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7331        if let Some((digits, tail)) = rest.split_once(unit)
7332            && !digits.is_empty()
7333            && digits.bytes().all(|b| b.is_ascii_digit())
7334        {
7335            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7336            rest = tail;
7337            matched = true;
7338        }
7339    }
7340    if !rest.is_empty() || !matched {
7341        return None;
7342    }
7343    recorded
7344        .checked_add(jiff::SignedDuration::from_secs(total))
7345        .ok()
7346}
7347
7348/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
7349/// case-insensitive) into a 24-hour hour and minute. Shared by every
7350/// reset-hint shape below.
7351fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7352    let clock = clock.trim().to_lowercase();
7353    let (digits, pm) = clock
7354        .strip_suffix("am")
7355        .map(|d| (d, false))
7356        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7357    let (h, m) = digits.trim().split_once(':')?;
7358    let mut hour: i8 = h.trim().parse().ok()?;
7359    let minute: i8 = m.trim().parse().ok()?;
7360    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7361        return None;
7362    }
7363    if pm && hour != 12 {
7364        hour += 12;
7365    } else if !pm && hour == 12 {
7366        hour = 0;
7367    }
7368    Some((hour, minute))
7369}
7370
7371/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
7372/// and a zone, never a date. A clock reading already past today is read as
7373/// tomorrow's: a CLI naming a same-day reset that has already gone by means
7374/// the window rolled over while nothing was watching.
7375fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7376    let open = text.find('(')?;
7377    let close = text.rfind(')')?;
7378    if close <= open {
7379        return None;
7380    }
7381    let zone = text[open + 1..close].trim();
7382    let (hour, minute) = parse_12h_clock(&text[..open])?;
7383    let tz = jiff::tz::TimeZone::get(zone).ok()?;
7384    let candidate = now
7385        .to_zoned(tz)
7386        .with()
7387        .hour(hour)
7388        .minute(minute)
7389        .second(0)
7390        .millisecond(0)
7391        .microsecond(0)
7392        .nanosecond(0)
7393        .build()
7394        .ok()?;
7395    let mut at = candidate.timestamp();
7396    if at <= now {
7397        at += jiff::SignedDuration::from_hours(24);
7398    }
7399    Some(at)
7400}
7401
7402/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
7403/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
7404/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
7405/// "already past today" correction to make: the year already disambiguates
7406/// it. Scanned as a five-word window so it can be pulled out of the middle
7407/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
7408/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
7409/// any other timestamp with no zone attached.
7410fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7411    let words: Vec<&str> = text.split_whitespace().collect();
7412    if words.len() < 5 {
7413        return None;
7414    }
7415    (0..=words.len() - 5)
7416        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7417}
7418
7419/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
7420/// parenthesis right after the window is refused rather than ignored — it
7421/// reads as an explicit zone annotation on a shape that otherwise carries
7422/// none, and guessing UTC anyway would be exactly the silent misread this
7423/// module's parsing otherwise avoids.
7424fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7425    if trailing.is_some_and(|next| next.starts_with('(')) {
7426        return None;
7427    }
7428    let month = month_number(window[0])?;
7429    let day_token = window[1].strip_suffix(',')?.to_lowercase();
7430    let day_digits = ["st", "nd", "rd", "th"]
7431        .iter()
7432        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7433    let day: i8 = day_digits.parse().ok()?;
7434    let year_token = window[2];
7435    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7436        return None;
7437    }
7438    let year: i16 = year_token.parse().ok()?;
7439    // The am/pm word carries the sentence's own trailing punctuation, e.g.
7440    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
7441    // reusing the same 12-hour clock reader the bracketed shape uses.
7442    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7443    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7444    let date = jiff::civil::Date::new(year, month, day).ok()?;
7445    let candidate = date
7446        .at(hour, minute, 0, 0)
7447        .to_zoned(jiff::tz::TimeZone::UTC)
7448        .ok()?;
7449    Some(candidate.timestamp())
7450}
7451
7452/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
7453/// case-insensitively, into a 1-based month number.
7454fn month_number(name: &str) -> Option<i8> {
7455    const NAMES: [&str; 12] = [
7456        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7457    ];
7458    let lower = name.to_lowercase();
7459    NAMES
7460        .iter()
7461        .position(|n| *n == lower.as_str())
7462        .map(|i| i as i8 + 1)
7463}
7464
7465/// Test probe for the shared resume policy's review-budget exclusion.
7466#[cfg(test)]
7467fn exhausted_review_budget(state: &RunState) -> bool {
7468    // A run whose task-head publication failed has nothing left to review:
7469    // resuming it only retries the publication, so it is never "exhausted".
7470    !crate::handover::can_resume(state)
7471        && state.status == RunStatus::Blocked
7472        && !state.released()
7473        && state.retired_to.is_none()
7474}
7475
7476/// This task's *most recent* run, if resuming it would actually make
7477/// progress. `short` is only for the warning's own message.
7478///
7479/// Only ever `runs.last()` — never a search back through older history.
7480/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
7481/// mint, oldest first, and every entry before the last one was already
7482/// superseded at the moment it was minted: the daemon only ever starts a new
7483/// run when the previous one was not worth resuming (unresumable, exhausted,
7484/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
7485/// opens a fresh review-only run alongside an older, already-failed
7486/// competition. Searching further back would let an old run that merely
7487/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
7488/// behind, say — get resumed instead of the fresh competition
7489/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
7490/// nothing asked to revisit.
7491///
7492/// Two runs paid for the "prefer resuming over restarting" half of this
7493/// lesson, which is why this still checks `runs.last()` rather than always
7494/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
7495/// task a moment later, duplicating two and a half hours of agent work. Then
7496/// b25f stalled on a judge that timed out and one that answered with no JSON
7497/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
7498/// **one second** later, buying three fresh implementations to reach the
7499/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
7500/// the second case: a stall is terminal, and its cheap recovery re-asks only
7501/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
7502/// that is technically `resumable()` but provably cannot progress must not
7503/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
7504/// no-op instead of the fresh competition it promises.
7505///
7506/// A load failure is warned about rather than silently read as "not
7507/// resumable": the alternative is exactly what let a schema mismatch on run
7508/// `eba2` fall through to a full re-competition with nobody told why.
7509/// `crate::conduct` is what actually offers a better answer than
7510/// `Runner::start` here (see `Recovery::Review`), once this task's next
7511/// failure shows it up as `held`/`failed` with the run state unreadable.
7512fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7513    unfinished_run_with(runs, short, RunState::load)
7514}
7515
7516/// [`unfinished_run`] with an injected state reader. Tests provide their
7517/// fixtures directly rather than touching the process-global run home.
7518pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7519where
7520    F: FnMut(&str) -> Result<RunState>,
7521{
7522    let mut id = runs.last()?.clone();
7523    let mut visited = std::collections::BTreeSet::new();
7524    let mut repo = None;
7525    loop {
7526        if !runs.contains(&id) || !visited.insert(id.clone()) {
7527            tracing::warn!("invalid or cyclic recovery authority for task {short}");
7528            return None;
7529        }
7530        let state = match load(&id) {
7531            Ok(state) if state.id == id => state,
7532            Ok(_) => return None,
7533            Err(e) => {
7534                tracing::warn!("could not read run {id} for task {short}: {e:#}");
7535                return None;
7536            }
7537        };
7538        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7539            return None;
7540        }
7541        repo = Some(state.repo.clone());
7542        if let Some(authority) = state.retired_to {
7543            id = authority;
7544            continue;
7545        }
7546        return (crate::handover::can_resume(&state)
7547            && state.liveness(false) != crate::run::Liveness::Live)
7548            .then_some(id);
7549    }
7550}
7551
7552/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
7553/// that [`attempt`] will resume it on its own?
7554///
7555/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
7556/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
7557/// injected reader like its sibling. An unreadable run is not awaiting
7558/// anything: it keeps going to the conductor as before.
7559fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7560where
7561    F: FnOnce(&str) -> Result<RunState>,
7562{
7563    // `Failed` stays: a record an older build wrote for a parked run.
7564    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7565        || task.fresh_start
7566        || task.review_branch.is_some()
7567    {
7568        return false;
7569    }
7570    let Some(id) = task.execution_runs().last() else {
7571        return false;
7572    };
7573    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7574}
7575
7576/// Which of the three ways [`attempt`] can mint or continue a run this task
7577/// should use.
7578#[derive(Debug, Clone, PartialEq, Eq)]
7579enum Starter {
7580    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
7581    /// and that still exists.
7582    Review(String),
7583    /// `crate::graph::Runner::resume` on an unfinished run of this task.
7584    Resume(String),
7585    /// `crate::graph::Runner::start`: a fresh competition.
7586    Start,
7587}
7588
7589/// A second bound independent of inputs and the resettable failure counter.
7590/// Count execution and failed-startup recovery records once per run. Startup
7591/// failures can retain unrecorded preparation assets without an execution pass.
7592/// Unknown history is not evidence that a new set of worktrees is affordable.
7593fn retained_attempt_hold(
7594    task: &Task,
7595    starter: &Starter,
7596    limit: usize,
7597    mut load: impl FnMut(&str) -> Result<RunState>,
7598) -> Option<String> {
7599    if limit == 0 || matches!(starter, Starter::Resume(_)) {
7600        return None;
7601    }
7602    let mut retained = 0;
7603    for id in task
7604        .runs
7605        .iter()
7606        .chain(task.startup_failures.iter().map(|failure| &failure.run))
7607        .collect::<std::collections::BTreeSet<_>>()
7608    {
7609        let state = match load(id) {
7610            Ok(state) if state.id == *id => state,
7611            _ => {
7612                return Some(format!(
7613                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7614                ));
7615            }
7616        };
7617        if state.retired_to.is_some() || state.released() {
7618            continue;
7619        }
7620        // Neither a completed status nor an empty candidate array proves that
7621        // all recovery sources (including unrecorded preparation) were retired.
7622        retained += 1;
7623    }
7624    (retained >= limit).then(|| format!(
7625        "[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."
7626    ))
7627}
7628
7629/// A selected public implementation overrides every historical candidate and pin.
7630fn selected_starter(
7631    selected: &crate::pr_recovery::Selection,
7632    previous: Option<&RunState>,
7633    unfinished: Option<&str>,
7634) -> Starter {
7635    if let Some(id) = unfinished
7636        && previous.is_some_and(|r| {
7637            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7638        })
7639    {
7640        Starter::Resume(id.to_owned())
7641    } else {
7642        Starter::Review(selected.branch.clone())
7643    }
7644}
7645
7646/// The owner's answer to this branch's divergence question, consumed from the
7647/// task so a later, different divergence asks again. The runner applies it
7648/// (see `Runner::review_taking_over`), after the earlier worktree is released.
7649fn take_divergence_answer(
7650    branch: &str,
7651    remote: &str,
7652    task: &mut Task,
7653) -> Option<crate::reconcile::Choice> {
7654    let summary = crate::reconcile::summary_for(branch, remote);
7655    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7656        (a.question == summary)
7657            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7658            .flatten()
7659            .map(|c| (i, c))
7660    })?;
7661    task.answers.remove(idx);
7662    Some(choice)
7663}
7664
7665/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
7666/// this attempt should use. Pure, and separate from [`attempt`], so the
7667/// routing itself is assertable without spawning a real graph or a git
7668/// process: `attempt`'s own `crate::git::branch_exists` call has already
7669/// happened by the time this is called.
7670///
7671/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
7672/// whose branch is gone falls all the way through to [`Starter::Start`], not
7673/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
7674/// old (likely `Blocked`) run in the first place, and a branch that vanished
7675/// out from under that choice is not evidence resuming it would fare better.
7676fn choose_starter(
7677    review_branch: Option<&str>,
7678    branch_exists: bool,
7679    unfinished: Option<&str>,
7680) -> Starter {
7681    match review_branch {
7682        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7683        Some(_) => Starter::Start,
7684        None => match unfinished {
7685            Some(id) => Starter::Resume(id.to_owned()),
7686            None => Starter::Start,
7687        },
7688    }
7689}
7690
7691/// Reuse a compatible latest review owner instead of taking its checked-out
7692/// branch into a new run. Different branches and changed criteria still use
7693/// the ordinary review/takeover policy.
7694fn review_retry_starter(
7695    task: &Task,
7696    previous: Option<&RunState>,
7697    branch: Option<&str>,
7698    exists: bool,
7699    unfinished: Option<&str>,
7700) -> Starter {
7701    if let Some(run) = previous
7702        && unfinished == Some(run.id.as_str())
7703        && run.reviewed_commits.is_some()
7704        && branch.is_some_and(|branch| {
7705            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7706        })
7707        && may_resume_run(run, task)
7708    {
7709        return Starter::Resume(run.id.clone());
7710    }
7711    match (branch, unfinished, &task.review_of) {
7712        (None, None, Some(branch)) => Starter::Review(branch.clone()),
7713        _ => choose_starter(branch, exists, unfinished),
7714    }
7715}
7716
7717/// A retained review is valid only while its authored criteria still match.
7718fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7719    task.review_branch
7720        .as_deref()
7721        .filter(|&branch| match &task.review_instruction {
7722            Some(authored) => *authored == task.instruction,
7723            // Legacy retained branches must agree with their prior run; only an
7724            // explicitly pinned review can proceed without recoverable provenance.
7725            None => previous.map_or_else(
7726                || task.review_of.as_deref() == Some(branch),
7727                |run| compatible_run_instruction(run, task),
7728            ),
7729        })
7730}
7731
7732/// A current explicit pin can select an otherwise incompatible run. Edits
7733/// and subsequent approvals invalidate pins selected for earlier criteria.
7734fn may_resume_run(run: &RunState, task: &Task) -> bool {
7735    if !task.assignment_accepts(run) {
7736        return false;
7737    }
7738    task.resume_override
7739        .as_ref()
7740        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7741        || compatible_run_instruction(run, task)
7742}
7743
7744/// Review scaffolding is execution context, not evidence of an operator edit.
7745pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7746    if let Some(authored) = &run.task_instruction {
7747        return compatible_instruction(authored, task);
7748    }
7749    if compatible_instruction(&run.instruction, task) {
7750        return true;
7751    }
7752    // Recognize only the existing generated review shapes on legacy runs.
7753    // Ordinary authored text with a similar heading is left intact.
7754    if run.reviewed_commits.is_some() {
7755        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7756            return strip_answers_block(authored, task).trim() == task.instruction.trim();
7757        }
7758        if let Some(branch) = &task.review_of {
7759            let canonical = format!(
7760                "Review the branch `{branch}` (review-only: no implementation, no judging)."
7761            );
7762            let generated = format!(
7763                "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"
7764            );
7765            return task.instruction == canonical && run.instruction.starts_with(&generated);
7766        }
7767    }
7768    false
7769}
7770
7771/// Compare authored instructions, excluding answer blocks appended by the daemon.
7772pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7773    strip_answers_block(old, task) == task.instruction
7774}
7775
7776/// Which repository a task runs in. A task that names none — the normal case
7777/// for one filed from a phone — runs in the daemon's own default.
7778fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7779    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7780        return fallback.to_path_buf();
7781    }
7782    task.repo.clone()
7783}
7784
7785/// The header [`append_answers`] appends operator answers under. Shared with
7786/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
7787/// rather than grown a new block on every resume.
7788const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7789
7790/// Render the first `count` answers in the block appended to an instruction.
7791fn answers_block(task: &Task, count: usize) -> String {
7792    let mut s = ANSWERS_HEADER.to_owned();
7793    for a in &task.answers[..count] {
7794        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7795    }
7796    s
7797}
7798
7799/// Render the approval independently of transient task state, so historical
7800/// suffixes remain recognizable after another explicit release.
7801fn resumption_block(r: &crate::queue::Resumption) -> String {
7802    format!(
7803        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7804         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7805        r.generation, r.at, r.instruction, r.answers_through,
7806    )
7807}
7808
7809/// Append audit answers and the latest explicit approval to the instruction.
7810fn append_answers(base: &str, task: &Task) -> String {
7811    let mut s = base.to_owned();
7812    if !task.answers.is_empty() {
7813        s.push_str(&answers_block(task, task.answers.len()));
7814    }
7815    if let Some(r) = &task.resumption {
7816        s.push_str(&resumption_block(r));
7817    }
7818    s
7819}
7820
7821/// Drop the prior answer block only when it is exactly the suffix this task
7822/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
7823/// the task author is ordinary instruction text, not a block to remove.
7824fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7825    let mut instruction = instruction;
7826    for approval in task
7827        .resumption
7828        .iter()
7829        .chain(task.resumption_history.iter().rev())
7830    {
7831        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7832            instruction = base;
7833            break;
7834        }
7835    }
7836    for count in (1..=task.answers.len()).rev() {
7837        let block = answers_block(task, count);
7838        if let Some(base) = instruction.strip_suffix(&block) {
7839            return base;
7840        }
7841    }
7842    instruction
7843}
7844
7845/// The instruction handed to `Runner::start`: the task's own text, plus any
7846/// operator answers `crate::conduct` collected for it (see
7847/// [`Task::answers`]), so a decision the operator actually made reaches the
7848/// implementers rather than only clearing the block that was waiting on it.
7849///
7850/// Appended rather than merged into [`Task::instruction`] itself, so the
7851/// task's own record stays exactly what its author wrote.
7852fn instruction_for(task: &Task) -> String {
7853    append_answers(&task.instruction, task)
7854}
7855
7856/// The instruction a resumed run should carry on with: whatever it already
7857/// had, refreshed with the task's *current* operator answers.
7858///
7859/// A resumable run's own `RunState::instruction` predates any answer
7860/// `crate::conduct` collects after the run parks, so resuming it unchanged —
7861/// the behaviour before this function existed — silently drops the very
7862/// decision the operator made to unblock it. Re-stripping any block this
7863/// function appended on an earlier resume before re-appending the current
7864/// list (rather than blindly appending again) is what keeps a task resumed
7865/// three times over three answered questions from carrying the same answer
7866/// three times.
7867fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
7868    append_answers(strip_answers_block(old_instruction, task), task)
7869}
7870
7871/// Preserve the producer's verified boundary and target, independent of prose.
7872fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
7873    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
7874    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
7875    if let Some(cause) = task.hold_notice_cause.as_mut() {
7876        cause.target = failure.map(|f| f.target.clone());
7877    }
7878}
7879
7880#[derive(Debug, thiserror::Error)]
7881#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7882struct MissingAttachment {
7883    name: String,
7884    path: PathBuf,
7885}
7886
7887/// The task's attachments as absolute paths, each checked to still exist.
7888fn task_attachments(
7889    queue: &Queue,
7890    task: &Task,
7891) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7892    let paths = queue.attachment_paths(task);
7893    for (name, path) in task.attachments.iter().zip(&paths) {
7894        if !path.is_file() {
7895            return Err(MissingAttachment {
7896                name: name.clone(),
7897                path: path.clone(),
7898            });
7899        }
7900    }
7901    Ok(paths)
7902}
7903
7904/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
7905/// answers before handing it to `Runner` — the actual boundary between
7906/// [`choose_starter`]'s routing and the graph, factored out so it is
7907/// assertable without a real repository, git branch, or agent CLI.
7908///
7909/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
7910/// instruction from the reviewed branch's own commit log because there is no
7911/// task statement to speak of for hand-written work, and splicing operator
7912/// answers into that text would contradict the very message it sends
7913/// reviewers ("there is no task statement").
7914fn prepare_instruction(
7915    starter: &Starter,
7916    old_instruction: Option<&str>,
7917    task: &Task,
7918) -> Option<String> {
7919    match starter {
7920        Starter::Start => Some(instruction_for(task)),
7921        Starter::Resume(_) => Some(resumed_instruction(
7922            old_instruction.expect("a resumed run always has a prior instruction"),
7923            task,
7924        )),
7925        Starter::Review(_) => None,
7926    }
7927}
7928
7929/// Persist a transition. A queue write failure is logged rather than fatal: the
7930/// run already happened, and taking the daemon down would only add a lost
7931/// backlog to a full disk.
7932fn record(queue: &Queue, task: &mut Task) {
7933    if let Err(e) = queue.put(task) {
7934        tracing::error!("could not record task {}: {e:#}", task.short());
7935        let notice = Notice::error(
7936            "loop:record",
7937            format!(
7938                "Task {} state could not be saved: {}. Check the disk.",
7939                task.id,
7940                e.to_string().lines().next().unwrap_or("unknown save error")
7941            ),
7942        )
7943        .link(Link::Task {
7944            id: task.id.clone(),
7945        });
7946        // The queue lives at `<home>/queue`, so its parent is the home.
7947        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7948            Some(home) => notices::raise_in(home, notice),
7949            None => notices::raise(notice),
7950        }
7951    }
7952}
7953
7954/// Every runnable task, in the order the loop should try them.
7955///
7956/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
7957/// tail exists so that a claim somebody else holds costs the loop the next
7958/// candidate rather than a whole poll interval of idleness.
7959fn runnable(queue: &Queue) -> Vec<Task> {
7960    let mut tasks: Vec<Task> = queue
7961        .list()
7962        .into_iter()
7963        .filter(|t| t.status.runnable())
7964        .collect();
7965    tasks.sort_unstable_by(crate::queue::dispatch_order);
7966    tasks
7967}
7968
7969/// Why a run ended where it did, in one line, for [`Task::last_error`].
7970///
7971/// A stalled run names the seats the quota took out: "out of quota" is not
7972/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
7973/// agent to replace or which plan to top up.
7974///
7975/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
7976/// purpose: unlike `label`'s other callers (an internal log line, an
7977/// already-a-bug fallback message), this string becomes `Task::last_error`
7978/// verbatim, which the phone renders in the same alarm-styled box an
7979/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
7980/// `.err` styling. A bare `verified_noop` there would read exactly like the
7981/// failure this whole feature exists to tell apart from one.
7982fn describe(state: &RunState) -> String {
7983    let p = phrases(&state.config.graph.language);
7984    let mut detail = if state.status == RunStatus::Stalled {
7985        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7986        seats.sort_unstable();
7987        seats.dedup();
7988        if seats.is_empty() {
7989            p.quorum_lost.to_owned()
7990        } else {
7991            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7992        }
7993    } else {
7994        format!("{}{}", p.run_ended, state.status.display_label())
7995    };
7996    if let Some(cause) = state.verification_blocking_cause() {
7997        detail.push_str(&format!(" ({cause})"));
7998    } else if let Some(last) = state.events.last() {
7999        // The review loop's "never answered" stop is the one event worth
8000        // translating; it is recognised from structured state, not by
8001        // matching the English event text (which stays as recorded).
8002        let unanswered = state
8003            .reviews
8004            .last()
8005            .filter(|r| {
8006                state.status == RunStatus::Blocked
8007                    && last.node == "review"
8008                    && r.incomplete()
8009                    && r.blocking == 0
8010                    && r.round == state.config.graph.review_rounds
8011                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8012            })
8013            .map(|r| (r.expected - r.answered, r.round));
8014        match unanswered {
8015            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8016                detail.push_str(&format!(
8017                    " ({}: {})",
8018                    last.node,
8019                    (p.reviewers_never_answered)(missing, rounds)
8020                ));
8021            }
8022            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8023        }
8024    }
8025    detail.push_str(&format!(" [run {}]", state.id));
8026    detail
8027}
8028
8029/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
8030///
8031/// The task file lives in the backlog indefinitely; a diagnostic is an
8032/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
8033/// stay small regardless of how much a gate command or a candidate printed.
8034const DIAGNOSTIC_MAX: usize = 4_000;
8035
8036/// Tail kept from a single failing command's output inside a diagnostic.
8037/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
8038/// pointer for a human deciding whether to go read the full artifact by hand,
8039/// not a replacement for reading it.
8040const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8041
8042/// Assemble a bounded diagnostic excerpt from a held task's own run, so
8043/// `magi task show` says more than the one-line reason in [`describe`].
8044///
8045/// The one-liner answers "where did the run stop"; this answers "what would a
8046/// human have found opening `artifacts/` by hand" — the point of the whole
8047/// feature is the case that one-liner actively misleads on: a run held as "no
8048/// candidate produced a change" can mean the implementer actually finished
8049/// the task (opened a PR, merged it, tagged a release) and only left a clean
8050/// local worktree behind, which reads as "nothing happened" unless someone
8051/// goes and reads what the agent actually said. `None` when the run carries
8052/// none of the three shapes this recognises — an ordinary run held for
8053/// something not diagnosable from `RunState` alone still explains itself
8054/// through `Task::last_error`.
8055pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8056    diagnostic(state)
8057}
8058
8059fn diagnostic(state: &RunState) -> Option<String> {
8060    let mut parts: Vec<String> = Vec::new();
8061
8062    if let Some(e2e) = &state.head_e2e
8063        && !e2e.passed
8064    {
8065        for o in e2e
8066            .outcomes
8067            .iter()
8068            .filter(|o| !o.ok() && !o.resource_blocked)
8069        {
8070            parts.push(format!(
8071                "head_e2e `{}` failed on {} ({}):\n{}",
8072                o.command,
8073                e2e.head.chars().take(7).collect::<String>(),
8074                notices::exit_status(o.code),
8075                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8076            ));
8077        }
8078    }
8079
8080    // Gate failure: which check(s), and the tail of what each printed.
8081    for o in state.gate.iter().filter(|o| !o.ok()) {
8082        parts.push(format!(
8083            "gate `{}` failed ({}):\n{}",
8084            o.command,
8085            notices::exit_status(o.code),
8086            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8087        ));
8088    }
8089
8090    // The land loop gave up because the fixer declined while checks were
8091    // still red: the message already names them (see `land::run`).
8092    if let Some(last) = state
8093        .events
8094        .iter()
8095        .rev()
8096        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8097    {
8098        parts.push(last.message.clone());
8099    }
8100
8101    // No viable candidate: every implementer's own final word, sanitized the
8102    // same way a judge would have read it, so a run that actually finished
8103    // the job does not read as an unexplained failure. A verified no-op is
8104    // called out ahead of its own summary and apart from an ordinary
8105    // failure's `why` — this is the one candidate shape whose diagnostic a
8106    // human is expected to actually judge, not just skim.
8107    if state.viable().is_empty() {
8108        for c in &state.candidates {
8109            if c.has_valid_verified_noop()
8110                && let Some(evidence) = c.verified_noop_display()
8111            {
8112                parts.push(format!(
8113                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8114                    c.label
8115                ));
8116            } else if !c.summary.trim().is_empty() {
8117                if let Some(why) = &c.failed {
8118                    parts.push(format!(
8119                        "candidate {} ({why}): {}",
8120                        c.label,
8121                        c.summary.trim()
8122                    ));
8123                } else {
8124                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8125                }
8126            } else if let Some(why) = &c.failed {
8127                parts.push(format!("candidate {}: {why}", c.label));
8128            }
8129        }
8130    }
8131
8132    if parts.is_empty() {
8133        return None;
8134    }
8135    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
8136    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
8137    // back slightly over. Leave it enough room to always land under the
8138    // limit.
8139    Some(crate::run::tail(
8140        &parts.join("\n\n"),
8141        DIAGNOSTIC_MAX.saturating_sub(100),
8142    ))
8143}
8144
8145/// Stable lower-case name for a run status, for an internal log line and the
8146/// "graph stopped without reaching a terminal status" bug message in
8147/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
8148/// doc for why that one reads [`RunStatus::display_label`] instead. One
8149/// definition of a status's name, on the type that owns it: this table used
8150/// to live here as a second copy, and a status renamed in one place would
8151/// have gone on reading correctly in the other.
8152fn label(status: RunStatus) -> &'static str {
8153    status.as_str()
8154}
8155
8156/// Parse a merge mode override.
8157pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8158    match mode {
8159        "none" => Ok(MergeMode::None),
8160        "local" => Ok(MergeMode::Local),
8161        "pr" => Ok(MergeMode::Pr),
8162        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8163    }
8164}
8165
8166/// Take the status lock, recovering from a poisoned one.
8167///
8168/// A panic elsewhere must not silently stop the heartbeat: the status is plain
8169/// data, and the worst a poisoned lock can hold is a stale timestamp.
8170fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8171    mutex
8172        .lock()
8173        .unwrap_or_else(std::sync::PoisonError::into_inner)
8174}
8175
8176#[cfg(test)]
8177mod tests {
8178    use super::*;
8179    use crate::queue::{Source, TaskStatus};
8180    use crate::run::{Candidate, CommandOutcome};
8181    use pretty_assertions::assert_eq;
8182
8183    fn task() -> Task {
8184        Task::new(
8185            "add retries".to_owned(),
8186            "add retries".to_owned(),
8187            PathBuf::from("/repo"),
8188            Source::Human,
8189        )
8190    }
8191
8192    #[test]
8193    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8194        let skips = DispatchSkips::from([
8195            ("a".into(), SkipReason::CoolingDown),
8196            ("b".into(), SkipReason::WaitingOnLanding),
8197            ("c".into(), SkipReason::WaitingOnLanding),
8198            ("d".into(), SkipReason::OrdinaryCapacity),
8199        ]);
8200        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8201        assert_eq!(wait.runnable, 4);
8202        assert_eq!(
8203            wait.reasons
8204                .iter()
8205                .map(|r| (r.reason.as_str(), r.count))
8206                .collect::<Vec<_>>(),
8207            [
8208                ("waiting_on_landing", 2),
8209                ("cooling_down", 1),
8210                ("ordinary_capacity", 1)
8211            ]
8212        );
8213        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8214        assert!(
8215            aggregate_dispatch_wait(2, &DispatchSkips::new())
8216                .unwrap()
8217                .reasons
8218                .is_empty()
8219        );
8220    }
8221
8222    #[test]
8223    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8224        let before = vec!["a".into(), "b".into(), "c".into()];
8225        let allowed = vec![task_with_id("b")];
8226        let skips = interrupt_skips(&before, &allowed);
8227        assert_eq!(
8228            skips,
8229            DispatchSkips::from([
8230                ("a".into(), SkipReason::InterruptGate),
8231                ("c".into(), SkipReason::InterruptGate),
8232            ])
8233        );
8234        let mut previous = DispatchSkips::new();
8235        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8236        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8237        assert!(!changed_dispatch_skips(&mut previous, skips));
8238        assert!(changed_dispatch_skips(
8239            &mut previous,
8240            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8241        ));
8242        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8243    }
8244
8245    #[test]
8246    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8247        let mut value = serde_json::to_value(Status::new()).unwrap();
8248        value.as_object_mut().unwrap().remove("dispatch_wait");
8249        assert!(
8250            serde_json::from_value::<Status>(value.clone())
8251                .unwrap()
8252                .dispatch_wait
8253                .is_none()
8254        );
8255        assert!(
8256            serde_json::from_value::<Reading>(value.clone())
8257                .unwrap()
8258                .dispatch_wait
8259                .is_none()
8260        );
8261        value["dispatch_wait"] = serde_json::json!({
8262            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8263        });
8264        let reading = serde_json::from_value::<Reading>(value).unwrap();
8265        assert_eq!(
8266            reading.dispatch_wait.unwrap().reasons[0].reason,
8267            "future_reason"
8268        );
8269    }
8270
8271    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8272        let job = crate::worker::Job {
8273            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8274            sequence: 1,
8275            kind: "task".into(),
8276            key: format!("task:{}", request.task),
8277            payload: serde_json::to_value(request).unwrap(),
8278            generation: "a".repeat(64),
8279            version: None,
8280            status: crate::worker::Status::Starting,
8281            result: None,
8282            pid: None,
8283            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8284            finished_at: None,
8285        };
8286        let dir = home.join("workers/jobs").join(&job.id);
8287        std::fs::create_dir_all(&dir).unwrap();
8288        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8289        job
8290    }
8291
8292    #[test]
8293    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8294        let home = tempfile::tempdir().unwrap();
8295        let request = TaskWorker {
8296            opts: Opts::default(),
8297            queue: home.path().join("queue"),
8298            task: "startup".into(),
8299            lane: PermitKind::Ordinary,
8300            standalone: false,
8301        };
8302        let job = starting_task_reservation(home.path(), &request);
8303        let error = task_worker_spawn_error(
8304            home.path(),
8305            &request,
8306            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8307        )
8308        .expect_err("our own reservation must not turn a failed spawn into a resync");
8309        let active = crate::worker::active(home.path()).unwrap();
8310        assert_eq!(active.len(), 1);
8311        assert_eq!(active[0].id, job.id);
8312        assert_eq!(active[0].status, crate::worker::Status::Starting);
8313        assert!(
8314            crate::worker::control(home.path(), &job.key)
8315                .unwrap()
8316                .is_none()
8317        );
8318        let notices = notices::Notices::at(home.path().join("notifications")).list();
8319        assert_eq!(notices.len(), 1);
8320        assert_eq!(notices[0].key, "loop:worker-startup");
8321        assert!(!notices[0].message.contains("private-error-detail"));
8322        assert!(notices[0].message.contains(&request.task));
8323        assert!(
8324            notices[0]
8325                .message
8326                .contains("could not be started or acknowledged")
8327        );
8328        assert!(notices[0].message.contains("worker.log"));
8329        assert_eq!(
8330            notices[0].link,
8331            Some(Link::Task {
8332                id: request.task.clone()
8333            })
8334        );
8335        assert!(format!("{error:#}").contains("private-error-detail"));
8336    }
8337
8338    #[test]
8339    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8340        let home = tempfile::tempdir().unwrap();
8341        let mut request = TaskWorker {
8342            opts: Opts::default(),
8343            queue: home.path().join("queue"),
8344            task: "handoff".into(),
8345            lane: PermitKind::Ordinary,
8346            standalone: true,
8347        };
8348        let job = starting_task_reservation(home.path(), &request);
8349        request.standalone = false;
8350        task_worker_spawn_error(
8351            home.path(),
8352            &request,
8353            anyhow::anyhow!("operation key is already reserved for a different request"),
8354        )
8355        .expect("a different standalone request is the handoff race, not our startup failure");
8356        let active = crate::worker::active(home.path()).unwrap();
8357        assert_eq!(active.len(), 1);
8358        assert_eq!(active[0].id, job.id);
8359        assert_eq!(active[0].payload, job.payload);
8360        assert!(
8361            notices::Notices::at(home.path().join("notifications"))
8362                .list()
8363                .is_empty()
8364        );
8365    }
8366
8367    #[test]
8368    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8369        let home = tempfile::tempdir().unwrap();
8370        let queue = Queue::at(home.path().join("queue"));
8371        let mut task = task();
8372        task.runs = vec!["previous".into()];
8373        queue.put(&mut task).unwrap();
8374        let request = TaskWorker {
8375            opts: Opts::default(),
8376            queue: home.path().join("queue"),
8377            task: task.id.clone(),
8378            lane: PermitKind::Ordinary,
8379            standalone: false,
8380        };
8381        let job = starting_task_reservation(home.path(), &request);
8382        let claims = current_work(home.path(), Timestamp::now());
8383        assert_eq!(claims.len(), 1);
8384        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8385        assert_eq!(claims[0].run, "previous");
8386        assert!(other_claims_run(&claims, "previous", None));
8387        // Only after confirming the executing caller may admission ignore
8388        // this exact projection. Cleanup continues to observe it as live.
8389        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8390        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8391    }
8392
8393    #[test]
8394    fn admission_excludes_only_the_callers_exact_reservation() {
8395        let own = Current {
8396            worker: Some("own".into()),
8397            task: "same-task".into(),
8398            run: "previous".into(),
8399        };
8400        assert!(!other_claims_run(
8401            std::slice::from_ref(&own),
8402            "previous",
8403            Some("own")
8404        ));
8405        assert!(other_claims_run(
8406            std::slice::from_ref(&own),
8407            "previous",
8408            None
8409        ));
8410        for worker in [None, Some("other".into())] {
8411            let other = Current {
8412                worker,
8413                ..own.clone()
8414            };
8415            assert!(other_claims_run(
8416                &[own.clone(), other],
8417                "previous",
8418                Some("own")
8419            ));
8420        }
8421        let legacy: Current =
8422            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8423        assert!(other_claims_run(&[legacy], "previous", Some("own")));
8424    }
8425
8426    #[test]
8427    fn os_leased_task_worker_survives_wall_clock_advance() {
8428        let home = tempfile::tempdir().unwrap();
8429        let queue = Queue::at(home.path().join("queue"));
8430        let mut task = task();
8431        let run = "20260903-100000-abcd";
8432        task.start(run.into());
8433        queue.put(&mut task).unwrap();
8434        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8435        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8436        assert!(
8437            current_work(home.path(), future)
8438                .iter()
8439                .any(
8440                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8441                        && claim.run == run
8442                )
8443        );
8444        worker.release_lease();
8445        assert!(worker.dir.join("job.json").is_file());
8446        assert!(!is_working_on(home.path(), run, future));
8447        let dir = worker.dir.clone();
8448        drop(worker);
8449        assert!(!dir.exists());
8450    }
8451
8452    #[test]
8453    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8454        let mut task = task();
8455        let mut run = run_state(RunStatus::Reviewing);
8456        run.task_instruction = Some(task.instruction.clone());
8457        run.reviewed_commits = Some(vec!["committed-fix".into()]);
8458        let branch = "magi/test/B";
8459        run.candidates.push(crate::run::Candidate {
8460            branch: branch.into(),
8461            ..candidate('B', "preserved work", false, None)
8462        });
8463        task.runs = vec![run.id.clone()];
8464        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8465        assert_eq!(
8466            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8467            Starter::Resume(run.id.clone())
8468        );
8469        assert!(matches!(
8470            review_retry_starter(
8471                &task,
8472                Some(&run),
8473                Some("different"),
8474                true,
8475                unfinished.as_deref()
8476            ),
8477            Starter::Review(_)
8478        ));
8479        assert_eq!(
8480            review_retry_starter(
8481                &task,
8482                Some(&run),
8483                Some(branch),
8484                false,
8485                unfinished.as_deref()
8486            ),
8487            Starter::Start
8488        );
8489        task.instruction.push_str(" changed criteria");
8490        assert!(matches!(
8491            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8492            Starter::Review(_)
8493        ));
8494        assert!(matches!(
8495            review_retry_starter(&task, Some(&run), Some(branch), true, None),
8496            Starter::Review(_)
8497        ));
8498    }
8499
8500    #[test]
8501    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8502        let dir = tempfile::tempdir().unwrap();
8503        let queue = Queue::at(dir.path().join("queue"));
8504        let mut task = task();
8505        task.status = TaskStatus::Running;
8506        task.attempts = 1;
8507        queue.put(&mut task).unwrap();
8508        let live = std::collections::BTreeSet::from([task.id.clone()]);
8509        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8510        drop(queue.claim(&task.id).unwrap());
8511        let saved = queue.get(&task.id).unwrap();
8512        assert_eq!(saved.status, TaskStatus::Running);
8513        assert_eq!(saved.attempts, 1);
8514        assert!(saved.last_error.is_none());
8515    }
8516
8517    #[test]
8518    fn standalone_workers_do_not_consume_scheduler_lanes() {
8519        let request = |task: &str, lane, standalone| TaskWorker {
8520            opts: Opts::default(),
8521            queue: PathBuf::from("/queue"),
8522            task: task.to_owned(),
8523            lane,
8524            standalone,
8525        };
8526        let mut jobs = vec![
8527            request("ordinary", PermitKind::Ordinary, false),
8528            request("standalone-urgent", PermitKind::Urgent, true),
8529            request("standalone-ordinary", PermitKind::Ordinary, true),
8530            request("decision", PermitKind::None, false),
8531        ];
8532        assert_eq!(available_slots(&jobs, 2), (1, 1));
8533        jobs.push(request("urgent", PermitKind::Urgent, false));
8534        assert_eq!(available_slots(&jobs, 2), (1, 0));
8535        assert_eq!(available_slots(&jobs, 0), (0, 0));
8536    }
8537
8538    #[test]
8539    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8540        let now = Timestamp::now();
8541        let mut reading = Reading {
8542            pid: Some(std::process::id()),
8543            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8544            ..Reading::default()
8545        };
8546        assert!(!reading.running(now));
8547        assert!(legacy_scheduler_running(&reading, now, 0));
8548        reading.worker_protocol = Some(1);
8549        assert!(!legacy_scheduler_running(&reading, now, 0));
8550    }
8551
8552    #[test]
8553    fn selected_public_head_overrides_historical_resume_and_pin() {
8554        let mut t = task();
8555        let mut old = run_state(RunStatus::Blocked);
8556        let selection = crate::pr_recovery::Selection {
8557            url: "url".into(),
8558            branch: format!("magi/task-{}", t.id),
8559            head: "a".repeat(40),
8560            source_head: None,
8561            source_run: None,
8562            source_proof: None,
8563            disposition: Some(crate::pr_recovery::Disposition::Review),
8564            instruction: t.instruction.clone(),
8565            approved_at: Timestamp::now(),
8566        };
8567        t.resume_override = Some(crate::queue::OperatorResume {
8568            pinned_run: Some(old.id.clone()),
8569            question_id: "choice".into(),
8570            at: Timestamp::now(),
8571            conductor_rehold: None,
8572            forced: false,
8573        });
8574        assert_eq!(
8575            selected_starter(&selection, Some(&old), Some(&old.id)),
8576            Starter::Review(selection.branch.clone())
8577        );
8578        old.pr_recovery = Some(selection.clone());
8579        assert_eq!(
8580            selected_starter(&selection, Some(&old), Some(&old.id)),
8581            Starter::Review(selection.branch.clone())
8582        );
8583        old.reviewed_commits = Some(vec!["implementation".into()]);
8584        assert_eq!(
8585            selected_starter(&selection, Some(&old), Some(&old.id)),
8586            Starter::Resume(old.id.clone())
8587        );
8588        let mut changed = selection.clone();
8589        changed.head = "b".repeat(40);
8590        assert_eq!(
8591            selected_starter(&changed, Some(&old), Some(&old.id)),
8592            Starter::Review(changed.branch)
8593        );
8594    }
8595
8596    #[test]
8597    fn candidate_transplant_failure_is_one_actionable_hold() {
8598        let dir = tempfile::tempdir().unwrap();
8599        let q = Queue::at(dir.path().join("queue"));
8600        let mut t = task();
8601        let mut state = run_state(RunStatus::Blocked);
8602        state.event("prep", "cannot apply referenced commit: conflict");
8603        state.prep_failure = Some("conflict".into());
8604        t.start(state.id.clone());
8605        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8606        assert_eq!(t.attempts, 1);
8607        assert_eq!(t.status, TaskStatus::Held);
8608        assert!(t.operator_held());
8609        assert!(!t.status.runnable());
8610        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8611        let first = t.chat_notice_key().unwrap();
8612        t.chat_notices.push(first.clone());
8613        t.release_operator("test", None);
8614        state.id = "another-unprepared-run".into();
8615        t.start(state.id.clone());
8616        finish_attempt(
8617            3,
8618            &q,
8619            &mut t,
8620            &state,
8621            &[],
8622            Err(anyhow::anyhow!("still conflicts")),
8623        );
8624        assert_eq!(
8625            t.chat_notice_key().as_ref(),
8626            Some(&first),
8627            "no work happened"
8628        );
8629        t.release_operator("test", None);
8630        state.prep_failure = None;
8631        state.status = RunStatus::Failed;
8632        state.begin_pass();
8633        t.start(state.id.clone());
8634        finish_attempt(
8635            1,
8636            &q,
8637            &mut t,
8638            &state,
8639            &[],
8640            Err(anyhow::anyhow!("new gate failure")),
8641        );
8642        let failure = t.chat_notice_key().unwrap();
8643        assert_ne!(failure, first, "approved recovery reached a real failure");
8644        t.release_operator("test", None);
8645        state.begin_pass();
8646        t.start(state.id.clone());
8647        finish_attempt(
8648            1,
8649            &q,
8650            &mut t,
8651            &state,
8652            &[],
8653            Err(anyhow::anyhow!("new failure on resume")),
8654        );
8655        assert_ne!(
8656            t.chat_notice_key().as_ref(),
8657            Some(&failure),
8658            "a new settled pass"
8659        );
8660    }
8661
8662    #[test]
8663    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8664        for source in ["cli", "web"] {
8665            let mut t = task();
8666            let mut run = run_state(RunStatus::Blocked);
8667            run.instruction = "Run A original criteria".into();
8668            run.task_instruction = Some(run.instruction.clone());
8669            t.start(run.id.clone());
8670            t.release_operator("choice", Some("resume-question"));
8671            t.resume_override = Some(crate::queue::OperatorResume {
8672                question_id: "resume-question".into(),
8673                at: Timestamp::now(),
8674                conductor_rehold: None,
8675                forced: true,
8676                pinned_run: Some(run.id.clone()),
8677            });
8678            t.hold_machine(Some("not enough free space to start a run".into()));
8679            let mut unchanged = t.clone();
8680            unchanged
8681                .edit("title changed".into(), unchanged.instruction.clone())
8682                .unwrap();
8683            unchanged.release_operator(source, None);
8684            assert_eq!(
8685                unchanged
8686                    .resume_override
8687                    .as_ref()
8688                    .unwrap()
8689                    .pinned_run
8690                    .as_deref(),
8691                Some(run.id.as_str())
8692            );
8693            assert!(!compatible_run_instruction(&run, &unchanged));
8694            assert!(may_resume_run(&run, &unchanged));
8695
8696            t.edit(
8697                "approved recovery".into(),
8698                "Reuse measured PR head B; fix Clippy; review".into(),
8699            )
8700            .unwrap();
8701            assert!(t.resume_override.is_none());
8702            t.release_operator(source, None);
8703            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8704            assert!(reloaded.resume_override.is_none());
8705            assert!(!may_resume_run(&run, &reloaded));
8706            let unfinished =
8707                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8708                    .filter(|_| may_resume_run(&run, &reloaded));
8709            assert_eq!(
8710                choose_starter(None, false, unfinished.as_deref()),
8711                Starter::Start
8712            );
8713            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8714            assert_eq!(
8715                reloaded.resumption_history[0].question_id.as_deref(),
8716                Some("resume-question")
8717            );
8718
8719            // A revision already persisted with the old approval/pin is also
8720            // invalidated when the new operator release is recorded.
8721            unchanged.instruction = "Reuse measured PR head B".into();
8722            unchanged.hold_machine(Some("disk hold".into()));
8723            unchanged.release_operator(source, None);
8724            assert!(unchanged.resume_override.is_none());
8725            assert!(!may_resume_run(&run, &unchanged));
8726        }
8727    }
8728
8729    #[test]
8730    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8731        let mut t = task();
8732        let mut run = run_state(RunStatus::Blocked);
8733        t.review_of = Some("approved-head".into());
8734        t.instruction =
8735            "Review the branch `approved-head` (review-only: no implementation, no judging)."
8736                .into();
8737        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();
8738        run.reviewed_commits = Some(vec!["Commit log".into()]);
8739        t.start(run.id.clone());
8740        t.hold_machine(Some("interrupted review".into()));
8741        t.release_operator("cli", None);
8742        assert!(
8743            compatible_run_instruction(&run, &t),
8744            "legacy explicit review remains resumable"
8745        );
8746        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8747            .filter(|_| compatible_run_instruction(&run, &t));
8748        assert_eq!(
8749            choose_starter(None, false, unfinished.as_deref()),
8750            Starter::Resume(run.id.clone())
8751        );
8752        run.task_instruction = Some(t.instruction.clone());
8753        assert!(compatible_run_instruction(&run, &t));
8754        let reloaded: RunState =
8755            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8756        assert!(compatible_run_instruction(&reloaded, &t));
8757        t.edit(
8758            "new approved head".into(),
8759            "Reuse measured PR head B".into(),
8760        )
8761        .unwrap();
8762        assert!(!compatible_run_instruction(&run, &t));
8763
8764        // Legacy recovery reviews retain the task criteria ahead of the log.
8765        t.review_of = None;
8766        t.instruction = "Fix Clippy on approved head".into();
8767        run.task_instruction = None;
8768        run.instruction = format!(
8769            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8770            t.instruction
8771        );
8772        assert!(compatible_run_instruction(&run, &t));
8773        t.instruction.push('\n');
8774        assert!(
8775            compatible_run_instruction(&run, &t),
8776            "legacy generated review trimmed the original criteria"
8777        );
8778        t.hold_for_handover(Some("approved-head".into()), "refused".into());
8779        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8780        t.edit("new plan".into(), "Reuse measured PR head B".into())
8781            .unwrap();
8782        assert!(review_branch_for(&t, Some(&run)).is_none());
8783        assert!(!compatible_run_instruction(&run, &t));
8784        t.review_branch = Some("approved-head".into());
8785        t.review_instruction = None;
8786        assert!(
8787            review_branch_for(&t, Some(&run)).is_none(),
8788            "legacy retained candidate cannot replace a revised approved head"
8789        );
8790    }
8791
8792    #[test]
8793    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8794        let home = crate::run::test_home();
8795        crate::run::pin_test_home();
8796        let dir = tempfile::tempdir().unwrap();
8797        let queue = Queue::at(dir.path().join("queue"));
8798        for resume in [true, false] {
8799            let state = run_state(RunStatus::Blocked);
8800            let mut t = task();
8801            t.start(state.id.clone());
8802            let action = if resume {
8803                ask::ChoiceAction::Resume {
8804                    run: state.id.clone(),
8805                }
8806            } else {
8807                ask::ChoiceAction::Requeue
8808            };
8809            let mut q = action_question(&state.id, action);
8810            q.status = ask::QuestionStatus::Open;
8811            q.answer = None;
8812            q.answered_at = None;
8813            t.fail("run stopped with a question", 3);
8814            hold_if_runnable(&queue, &mut t);
8815            assert!(t.operator_decided_at.is_none());
8816            assert!(t.operator_held());
8817            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8818            let expected = if resume {
8819                ActionDecision::Resume(state.id.clone())
8820            } else {
8821                ActionDecision::Requeue
8822            };
8823            assert_eq!(
8824                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8825                expected
8826            );
8827            t.hold_manual(Some("later explicit hold".into()));
8828            assert_eq!(
8829                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8830                ActionDecision::Stale
8831            );
8832        }
8833    }
8834
8835    #[test]
8836    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8837        let mut t = task();
8838        t.answers.push(crate::queue::AnsweredQuestion {
8839            question: "Inspect the remote?".into(),
8840            answer: "Inspect then wait".into(),
8841        });
8842        let old = instruction_for(&t);
8843        assert!(compatible_instruction(&old, &t));
8844        t.instruction = "Reuse approved PR head and review".into();
8845        t.release_operator("cli", None);
8846        assert!(!compatible_instruction(&old, &t));
8847        let approved = instruction_for(&t);
8848        assert!(approved.contains("waiting premises are superseded"));
8849        assert!(compatible_instruction(&approved, &t));
8850        assert_eq!(resumed_instruction(&approved, &t), approved);
8851        t.release_operator("web", None);
8852        assert!(compatible_instruction(&approved, &t));
8853        assert_eq!(t.resumption_history.len(), 1);
8854        t.start("run".into());
8855        assert!(instruction_for(&t).contains("Explicit operator resumption"));
8856    }
8857
8858    /// A run that stopped on an infrastructure wait asked no agent anything:
8859    /// the task is held by the machine under a `[resource]` reason (resumable,
8860    /// re-checked by triage), and the attempt it started is given back.
8861    #[test]
8862    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
8863        let mut state = RunState::new(
8864            PathBuf::from("/repo"),
8865            "main".into(),
8866            "base".into(),
8867            "task".into(),
8868            Config::default(),
8869        );
8870        state.status = RunStatus::Landing;
8871        state.parked = true;
8872        state.pr_pushed_head = Some("head".into());
8873        state.land_unrelated = Some(
8874            serde_json::from_value(serde_json::json!({
8875                "head": "head", "question": "ci-question",
8876                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8877            }))
8878            .unwrap(),
8879        );
8880        let mut t = task();
8881        t.start(state.id.clone());
8882        let verdict = Verdict {
8883            status: RunStatus::Landing,
8884            left_pr: true,
8885            quota_hit: false,
8886            parked: true,
8887            no_viable_candidates: false,
8888        };
8889        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8890        assert_eq!(t.attempts, 0);
8891        assert_eq!(t.status, TaskStatus::Held);
8892        assert!(!t.operator_held());
8893        assert!(
8894            t.hold_reason
8895                .as_deref()
8896                .unwrap()
8897                .starts_with("[ci-unrelated]")
8898        );
8899        // A second settlement must not refund an earlier task attempt.
8900        t.attempts = 1;
8901        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8902        assert_eq!(t.attempts, 1);
8903        assert_eq!(t.passes.len(), 1);
8904        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8905        state.pr_pushed_head = Some("new-head".into());
8906        state.parked = false;
8907        state.status = RunStatus::Blocked;
8908        let stale = Verdict {
8909            status: RunStatus::Blocked,
8910            parked: false,
8911            ..verdict
8912        };
8913        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8914        assert_eq!(t.attempts, 1);
8915        // A new execution pass can refund its own newly charged attempt.
8916        state.begin_pass();
8917        state.begin_pass();
8918        state.status = RunStatus::Landing;
8919        state.parked = true;
8920        state.pr_pushed_head = Some("head".into());
8921        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8922        assert_eq!(t.attempts, 0);
8923        assert_eq!(t.passes.len(), 2);
8924    }
8925
8926    #[test]
8927    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8928        let mut state = run_state(RunStatus::Failed);
8929        state
8930            .quota
8931            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8932        state.begin_pass();
8933        let mut t = task();
8934        t.start(state.id.clone());
8935        reclaim(&mut t, Some(state), 2, "en");
8936        assert_eq!(t.attempts, 1);
8937    }
8938
8939    #[test]
8940    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8941        let mut state = run_state(RunStatus::Blocked);
8942        let losses: Vec<_> = ["alpha", "beta"]
8943            .into_iter()
8944            .enumerate()
8945            .map(|(i, agent)| {
8946                QuotaLoss::from_report(
8947                    format!("advisor-{i}"),
8948                    "advise",
8949                    Some(&crate::agent::Quota {
8950                        cause: crate::agent::QuotaCause::Authentication,
8951                        agent: agent.to_owned(),
8952                        reset: None,
8953                    }),
8954                )
8955            })
8956            .collect();
8957        crate::graph::block_machine_outage(&mut state, "advise", &losses);
8958        state.quota = losses;
8959        let mut t = task();
8960        t.start(state.id.clone());
8961        let verdict = Verdict {
8962            status: state.status,
8963            left_pr: false,
8964            quota_hit: true,
8965            parked: false,
8966            no_viable_candidates: true,
8967        };
8968        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8969        assert_eq!(t.attempts, 0);
8970        assert_eq!(t.status, TaskStatus::Held);
8971        assert!(!t.operator_held());
8972        let reason = t.hold_reason.as_deref().unwrap();
8973        assert!(reason.starts_with("[authentication]"));
8974        assert!(
8975            reason.contains("alpha")
8976                && reason.contains("beta")
8977                && reason.contains("re-authenticate")
8978        );
8979        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8980        // Orphan recovery uses the same settlement and cannot spend an attempt.
8981        let mut orphan = task();
8982        orphan.start(state.id.clone());
8983        reclaim(&mut orphan, Some(state), 2, "en");
8984        assert_eq!(orphan.attempts, 0);
8985        assert_eq!(orphan.status, TaskStatus::Held);
8986    }
8987
8988    #[test]
8989    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8990        let mut state = RunState::new(
8991            PathBuf::from("/repo"),
8992            "main".to_owned(),
8993            "abc1234".to_owned(),
8994            "task".to_owned(),
8995            Config::default(),
8996        );
8997        state.status = RunStatus::Blocked;
8998        state.resource_block = Some(crate::run::ResourceBlock {
8999            cause: crate::run::ResourceBlockCause::Other,
9000            node: "graft".to_owned(),
9001            kind: "shared build cache".to_owned(),
9002            detail: "timed out".to_owned(),
9003            at: jiff::Timestamp::now(),
9004        });
9005        let mut t = task();
9006        t.start("20260902-000000-aaaa".to_owned());
9007        assert_eq!(t.attempts, 1);
9008        let verdict = Verdict {
9009            status: RunStatus::Blocked,
9010            left_pr: false,
9011            quota_hit: false,
9012            parked: false,
9013            no_viable_candidates: false,
9014        };
9015        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9016        assert_eq!(t.status, TaskStatus::Held);
9017        assert_eq!(t.attempts, 0, "the attempt is refunded");
9018        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9019        assert!(
9020            !t.operator_held(),
9021            "a machine hold, released without a human"
9022        );
9023
9024        let mut selected = task();
9025        selected.start("20260902-000000-cccc".into());
9026        selected.replacement = Some(crate::merge_decision::Replacement {
9027            question: "fixture".into(),
9028            run: "earlier".into(),
9029            pr: "https://example.invalid/pr/1".into(),
9030            agent: "selected".into(),
9031            context: "fixture".into(),
9032        });
9033        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9034        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9035        assert_eq!(selected.attempts, 0);
9036        assert!(
9037            !selected.operator_held(),
9038            "a selected agent also retains a machine resource hold"
9039        );
9040        assert!(
9041            selected
9042                .hold_reason
9043                .as_deref()
9044                .unwrap()
9045                .starts_with("[resource] ")
9046        );
9047
9048        // A park request outranks it: still the operator's doing.
9049        let mut p = task();
9050        p.start("20260902-000000-bbbb".to_owned());
9051        settle_and_diagnose(
9052            &mut p,
9053            Verdict {
9054                parked: true,
9055                ..verdict
9056            },
9057            "parked",
9058            2,
9059            &state,
9060        );
9061        assert_eq!(p.status, TaskStatus::Parked);
9062        assert_eq!(
9063            p.attempts, 0,
9064            "parking refunds once rather than also settling the resource hold"
9065        );
9066    }
9067
9068    #[test]
9069    fn record_failure_notice_links_the_task() {
9070        let dir = tempfile::tempdir().unwrap();
9071        // A regular file where the queue directory should be makes every
9072        // `put` fail, on every platform and whoever runs the test.
9073        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9074        let queue = Queue::at(dir.path().join("queue"));
9075        let mut t = interrupt_task("rec-fail-1");
9076        record(&queue, &mut t);
9077
9078        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9079        assert_eq!(found.len(), 1);
9080        assert_eq!(found[0].key, "loop:record");
9081        assert_eq!(
9082            found[0].link,
9083            Some(Link::Task {
9084                id: "rec-fail-1".to_owned()
9085            })
9086        );
9087    }
9088
9089    /// A runnable task marked to interrupt, with an id fixed for assertions
9090    /// rather than the random one [`Task::new`] mints.
9091    fn interrupt_task(id: &str) -> Task {
9092        let mut t = task();
9093        t.id = id.to_owned();
9094        t.interrupt = true;
9095        t
9096    }
9097
9098    /// An ordinary runnable task with an id fixed for assertions.
9099    fn task_with_id(id: &str) -> Task {
9100        let mut t = task();
9101        t.id = id.to_owned();
9102        t
9103    }
9104
9105    /// A runnable task marked `--urgent`, with an id fixed for assertions.
9106    fn urgent_task(id: &str) -> Task {
9107        let mut t = task();
9108        t.id = id.to_owned();
9109        t.urgent = true;
9110        t
9111    }
9112
9113    #[test]
9114    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9115        let dir = tempfile::tempdir().unwrap();
9116        let queue = Queue::at(dir.path().join("queue"));
9117        let mut parked = task_with_id("parked");
9118        parked.start("run".into());
9119        parked.park("upgrade");
9120        parked.record_pass_at(
9121            "run",
9122            0,
9123            Some(Timestamp::now()),
9124            1,
9125            Some(crate::run::ParkCause::Upgrade {
9126                from: "old".into(),
9127                to: None,
9128            }),
9129        );
9130        let mut fresh = task_with_id("fresh");
9131        fresh.priority = 100;
9132        let mut urgent_task = urgent_task("urgent");
9133        for t in [&mut parked, &mut fresh, &mut urgent_task] {
9134            queue.put(t).unwrap();
9135        }
9136        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9137        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9138        let candidates = runnable(&queue);
9139        assert_eq!(candidates[0].id, parked.id);
9140        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9141        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9142        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9143        drop(first);
9144        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9145        let next = runnable(&queue)
9146            .into_iter()
9147            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9148            .unwrap();
9149        assert_eq!(next.task.id, fresh.id);
9150        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9151        drop(claimed_elsewhere);
9152        drop(next);
9153        assert!(matches!(
9154            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9155            Err(SkipReason::CoolingDown)
9156        ));
9157    }
9158
9159    #[test]
9160    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9161        let dir = tempfile::tempdir().unwrap();
9162        let queue = Queue::at(dir.path().join("queue"));
9163        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9164        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9165        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9166        let mut first = task();
9167        queue.put(&mut first).unwrap();
9168        let stale_plain = queue.get(&first.id).unwrap();
9169        first.set_urgent(true).unwrap();
9170        queue.put(&mut first).unwrap();
9171        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9172        let mut second = urgent_task("second");
9173        queue.put(&mut second).unwrap();
9174        assert!(matches!(
9175            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9176            Err(SkipReason::UrgentCapacity)
9177        ));
9178        drop(queue.claim(&second.id).unwrap());
9179        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9180        drop(dispatched);
9181        let stale_urgent = queue.get(&first.id).unwrap();
9182        first.set_urgent(false).unwrap();
9183        queue.put(&mut first).unwrap();
9184        assert!(matches!(
9185            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9186            Err(SkipReason::OrdinaryCapacity)
9187        ));
9188        assert_eq!(urgent.available_permits(), 1);
9189        drop(queue.claim(&first.id).unwrap());
9190        drop(occupied);
9191    }
9192
9193    #[test]
9194    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9195        let dir = tempfile::tempdir().unwrap();
9196        let queue = Queue::at(dir.path().join("queue"));
9197        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9198        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9199        let mut t = task();
9200        queue.put(&mut t).unwrap();
9201        for enabled in [true, false] {
9202            let stale = queue.get(&t.id).unwrap();
9203            t.set_urgent(enabled).unwrap();
9204            queue.put(&mut t).unwrap();
9205            assert_ne!(stale.urgent, enabled);
9206            let DispatchClaim {
9207                task: fresh,
9208                claim,
9209                lane,
9210                permit,
9211            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9212            assert_eq!(fresh.urgent, enabled);
9213            assert_eq!(
9214                lane,
9215                if enabled {
9216                    PermitKind::Urgent
9217                } else {
9218                    PermitKind::Ordinary
9219                }
9220            );
9221            assert_eq!(ordinary.available_permits(), usize::from(enabled));
9222            assert_eq!(urgent.available_permits(), usize::from(!enabled));
9223            assert!(queue.claim(&t.id).is_err());
9224            assert_eq!(fresh.attempts, stale.attempts);
9225            drop((claim, permit));
9226            assert_eq!(ordinary.available_permits(), 1);
9227            assert_eq!(urgent.available_permits(), 1);
9228        }
9229        t.set_urgent(true).unwrap();
9230        queue.put(&mut t).unwrap();
9231        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9232        assert!(matches!(
9233            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9234            Err(SkipReason::UrgentCapacity)
9235        ));
9236        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9237        drop(queue.claim(&t.id).unwrap());
9238        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9239        drop(occupied);
9240        assert!(matches!(
9241            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9242            Err(SkipReason::CoolingDown)
9243        ));
9244        drop(queue.claim(&t.id).unwrap());
9245        let held = queue.claim(&t.id).unwrap();
9246        assert!(matches!(
9247            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9248            Err(SkipReason::ClaimUnavailable)
9249        ));
9250        drop(held);
9251        t.status = TaskStatus::Held;
9252        queue.put(&mut t).unwrap();
9253        assert!(matches!(
9254            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9255            Err(SkipReason::NoLongerRunnable)
9256        ));
9257        drop(queue.claim(&t.id).unwrap());
9258        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9259        assert!(matches!(
9260            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9261            Err(SkipReason::RereadFailed)
9262        ));
9263        drop(queue.claim(&t.id).unwrap());
9264        assert_eq!(urgent.available_permits(), 1);
9265    }
9266
9267    /// The land-resume exemption wins outright, whether or not the candidate
9268    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
9269    /// queue behind anything" guarantee cannot be weaker just because the
9270    /// same task was also filed with `--urgent`.
9271    #[test]
9272    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9273        assert_eq!(permit_kind(true, false, false), PermitKind::None);
9274        assert_eq!(permit_kind(true, false, true), PermitKind::None);
9275        assert_eq!(permit_kind(true, true, false), PermitKind::None);
9276        assert_eq!(permit_kind(true, true, true), PermitKind::None);
9277    }
9278
9279    /// The one property this whole feature exists for: `--urgent` draws from
9280    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
9281    /// ordinary candidate draws from the ordinary pool exactly as before,
9282    /// untouched by the urgent slot's existence.
9283    #[test]
9284    fn permit_kind_separates_urgent_from_ordinary() {
9285        assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9286        assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9287        assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9288        assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9289    }
9290
9291    #[test]
9292    fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9293        let request = |task: &str, lane, standalone| TaskWorker {
9294            opts: Opts::default(),
9295            queue: PathBuf::from("/queue"),
9296            task: task.to_owned(),
9297            lane,
9298            standalone,
9299        };
9300        let jobs = vec![
9301            request("ordinary", PermitKind::Ordinary, false),
9302            request("urgent", PermitKind::Urgent, false),
9303            request("immediate-1", PermitKind::Immediate, false),
9304            request("immediate-2", PermitKind::Immediate, false),
9305            request("decision", PermitKind::None, false),
9306        ];
9307        assert_eq!(available_slots(&jobs, 1), (0, 0));
9308        assert_eq!(available_slots(&jobs, 2), (1, 0));
9309        let immediate_only = vec![
9310            request("immediate-1", PermitKind::Immediate, false),
9311            request("immediate-2", PermitKind::Immediate, false),
9312        ];
9313        assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9314    }
9315
9316    #[test]
9317    fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9318        let dir = tempfile::tempdir().unwrap();
9319        let queue = Queue::at(dir.path().join("queue"));
9320        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9321        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9322        let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9323        let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9324
9325        // Both ordinary and urgent lanes are saturated.
9326        let mut imm1 = task_with_id("imm-1");
9327        imm1.immediate = true;
9328        let mut imm2 = task_with_id("imm-2");
9329        imm2.immediate = true;
9330        imm2.urgent = true;
9331        queue.put(&mut imm1).unwrap();
9332        queue.put(&mut imm2).unwrap();
9333
9334        // Stale non-immediate listing still picks up saved immediate under claim.
9335        let mut stale = imm1.clone();
9336        stale.immediate = false;
9337        let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9338        assert_eq!(claim1.lane, PermitKind::Immediate);
9339        assert!(claim1.permit.is_none());
9340
9341        // Multiple immediate tasks can claim simultaneously without touching semaphores.
9342        let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9343        assert_eq!(claim2.lane, PermitKind::Immediate);
9344        assert!(claim2.permit.is_none());
9345        assert_eq!(ordinary.available_permits(), 0);
9346        assert_eq!(urgent.available_permits(), 0);
9347
9348        // Duplicate claim on an already-claimed immediate task is refused.
9349        assert_eq!(
9350            claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9351            Some(SkipReason::ClaimUnavailable)
9352        );
9353        drop((claim1, claim2));
9354
9355        // Cooldown still blocks immediate tasks.
9356        assert_eq!(
9357            claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9358            Some(SkipReason::CoolingDown)
9359        );
9360
9361        // Clearing immediate while urgent remains true reverts to urgent lane.
9362        imm2.set_immediate(false).unwrap();
9363        queue.put(&mut imm2).unwrap();
9364        assert_eq!(
9365            claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9366            Some(SkipReason::UrgentCapacity)
9367        );
9368
9369        // Interrupt gate still withholds immediate candidates.
9370        let interrupt = Interrupt::Parking {
9371            parked: vec!["in-flight".into()],
9372            interrupt_task: "other".into(),
9373        };
9374        assert!(
9375            interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9376            "an active interrupt sequence must withhold immediate tasks too"
9377        );
9378    }
9379
9380    #[test]
9381    fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9382        let dir = tempfile::tempdir().unwrap();
9383        let home = dir.path();
9384        let queue = Queue::at(home.join("queue"));
9385        let now = Timestamp::now();
9386
9387        let mut imm = task_with_id("imm-ready");
9388        imm.immediate = true;
9389        queue.put(&mut imm).unwrap();
9390
9391        // No scheduler running -> waiting, never "next poll".
9392        let snap = AdmissionSnapshot::capture(home, now);
9393        let adm = snap.evaluate(&imm, &queue, None, home);
9394        assert_eq!(adm.mode, "immediate");
9395        assert_eq!(adm.state, "waiting");
9396        assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9397
9398        // Live scheduler + saturated ordinary/urgent workers + stale capacity skip -> next poll!
9399        let mut status = Status::new();
9400        status.updated_at = now;
9401        status
9402            .dispatch_skips
9403            .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9404        write_status_to(&home.join("daemon.json"), &status).unwrap();
9405
9406        let mut ord = task_with_id("ord-running");
9407        ord.status = TaskStatus::Running;
9408        queue.put(&mut ord).unwrap();
9409        let ord_req = TaskWorker {
9410            opts: Opts::default(),
9411            queue: queue.root().to_path_buf(),
9412            task: ord.id.clone(),
9413            lane: PermitKind::Ordinary,
9414            standalone: false,
9415        };
9416        let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9417            home,
9418            &format!("task:{}", ord.id),
9419            serde_json::to_value(&ord_req).unwrap(),
9420        )
9421        .unwrap();
9422
9423        let mut urg = task_with_id("urg-running");
9424        urg.urgent = true;
9425        urg.status = TaskStatus::Running;
9426        queue.put(&mut urg).unwrap();
9427        let urg_req = TaskWorker {
9428            opts: Opts::default(),
9429            queue: queue.root().to_path_buf(),
9430            task: urg.id.clone(),
9431            lane: PermitKind::Urgent,
9432            standalone: false,
9433        };
9434        let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9435            home,
9436            &format!("task:{}", urg.id),
9437            serde_json::to_value(&urg_req).unwrap(),
9438        )
9439        .unwrap();
9440
9441        let snap = AdmissionSnapshot::capture(home, now);
9442        let adm = snap.evaluate(&imm, &queue, None, home);
9443        assert_eq!(adm.state, "next_poll");
9444        assert_eq!(adm.label, "Immediate: next poll");
9445        assert_eq!(adm.reservation_lane, None);
9446
9447        // Running worker reports its actual persisted reservation lane.
9448        let ord_adm = snap.evaluate(&ord, &queue, None, home);
9449        assert_eq!(ord_adm.state, "running");
9450        assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9451        assert_eq!(ord_adm.label, "Running (ordinary lane)");
9452
9453        // Held (manual + disk) and Blocked (dependency) report concrete blockers.
9454        let mut held = task_with_id("imm-held");
9455        held.immediate = true;
9456        held.hold_manual(Some("awaiting signoff".into()));
9457        queue.put(&mut held).unwrap();
9458        let held_adm = snap.evaluate(&held, &queue, None, home);
9459        assert_eq!(held_adm.state, "waiting");
9460        assert_eq!(
9461            held_adm.label,
9462            "Immediate: waiting — held (awaiting signoff)"
9463        );
9464
9465        let mut disk_held = task_with_id("imm-disk");
9466        disk_held.immediate = true;
9467        disk_held.hold_machine(Some("only 1 GiB free".into()));
9468        disk_held.mark_startup_disk_capacity();
9469        queue.put(&mut disk_held).unwrap();
9470        let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9471        assert_eq!(disk_adm.state, "waiting");
9472        assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9473
9474        let mut blocked = task_with_id("imm-blocked");
9475        blocked.immediate = true;
9476        blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9477        queue.put(&mut blocked).unwrap();
9478        let questions = Questions::at(home.join("questions"));
9479        let inv = crate::blockers::Inventory::load(&queue, &questions);
9480        let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9481        assert_eq!(blocked_adm.state, "waiting");
9482        assert!(
9483            blocked_adm
9484                .label
9485                .starts_with("Immediate: waiting — waiting on dependencies"),
9486            "{blocked_adm:?}"
9487        );
9488
9489        // Existing claim blocks immediate.
9490        let _claim = queue.claim(&imm.id).unwrap();
9491        let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9492        assert_eq!(claimed_adm.state, "waiting");
9493        assert_eq!(
9494            claimed_adm.label,
9495            "Immediate: waiting — claimed by another process"
9496        );
9497        drop(_claim);
9498
9499        // Quota cooldown blocks immediate.
9500        let until = now + jiff::SignedDuration::from_secs(120);
9501        std::fs::write(
9502            home.join("task-quota-cooldown.json"),
9503            serde_json::to_vec(&until).unwrap(),
9504        )
9505        .unwrap();
9506        let cool_snap = AdmissionSnapshot::capture(home, now);
9507        let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9508        assert_eq!(cool_adm.state, "waiting");
9509        assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9510        std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9511
9512        // Corrupt interrupt file is reported as unknown, never "next poll".
9513        std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9514        let bad_snap = AdmissionSnapshot::capture(home, now);
9515        let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9516        assert_eq!(bad_adm.state, "unknown");
9517        assert_ne!(bad_adm.label, "Immediate: next poll");
9518    }
9519
9520    /// The exact wiring `attempt` runs before minting anything: a config's
9521    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
9522    /// Free space is injected rather than asked of the real disk - the point
9523    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
9524    /// is deterministic on every machine this test runs on, never dependent
9525    /// on how full the CI runner's own disk happens to be.
9526    #[test]
9527    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9528        let cfg = Config::default();
9529        let repo = Path::new("/any/repo/path");
9530
9531        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9532            .expect("must hold below the threshold");
9533        assert!(reason.contains("1024"), "{reason}");
9534        assert!(
9535            reason.contains(&cfg.disk.min_free_bytes.to_string()),
9536            "{reason}"
9537        );
9538
9539        assert_eq!(
9540            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9541            None,
9542            "exactly at the floor is open"
9543        );
9544        assert_eq!(
9545            disk_gate_with(
9546                repo,
9547                &cfg,
9548                PathBuf::new,
9549                |_| Ok(cfg.disk.min_free_bytes + 1)
9550            ),
9551            None,
9552            "comfortably above the floor is open"
9553        );
9554    }
9555
9556    /// The collection threshold is not an admission floor: free space just
9557    /// above `min_free_bytes` but far below `reclaim_free_bytes` opens the gate
9558    /// with no hold, whatever the threshold is.
9559    #[test]
9560    fn disk_gate_ignores_the_collection_threshold() {
9561        let mut cfg = Config::default();
9562        cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9563        let repo = Path::new("/any/repo/path");
9564        assert_eq!(
9565            disk_gate_with(
9566                repo,
9567                &cfg,
9568                PathBuf::new,
9569                |_| Ok(cfg.disk.min_free_bytes + 1)
9570            ),
9571            None
9572        );
9573        assert!(
9574            disk_gate_with(
9575                repo,
9576                &cfg,
9577                PathBuf::new,
9578                |_| Ok(cfg.disk.min_free_bytes - 1)
9579            )
9580            .is_some(),
9581            "below the admission floor still holds"
9582        );
9583    }
9584
9585    #[test]
9586    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9587        let dir = tempfile::tempdir().unwrap();
9588        let repo = dir.path().join("repo");
9589        let cache = dir.path().join("cache");
9590        let worktrees = dir.path().join("worktrees");
9591        for path in [&repo, &cache, &worktrees] {
9592            std::fs::create_dir(path).unwrap();
9593        }
9594        let mut cfg = Config::default();
9595        cfg.graph.worktree_root = Some(worktrees.clone());
9596        cfg.verify.gate = vec![format!(
9597            "CARGO_TARGET_DIR='{}' cargo build",
9598            cache.display()
9599        )];
9600        for blocked in [&cache, &worktrees] {
9601            for unmeasured in [false, true] {
9602                assert!(
9603                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9604                        if path == blocked {
9605                            if unmeasured {
9606                                Err(anyhow::anyhow!("measurement failed"))
9607                            } else {
9608                                Ok(0)
9609                            }
9610                        } else {
9611                            Ok(u64::MAX)
9612                        }
9613                    })
9614                    .is_some(),
9615                    "a blocked secondary output volume must close admission"
9616                );
9617            }
9618        }
9619        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9620    }
9621
9622    #[test]
9623    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9624        let dir = tempfile::tempdir().unwrap();
9625        let repo = dir.path().join("repo");
9626        let cache = dir.path().join("cache");
9627        let home_parent = dir.path().join("run-volume");
9628        let home = home_parent.join("new-home");
9629        for path in [&repo, &cache, &home_parent] {
9630            std::fs::create_dir(path).unwrap();
9631        }
9632        let mut cfg = Config::default();
9633        cfg.graph.worktree_root = Some(repo.clone());
9634        cfg.verify.gate = vec![format!(
9635            "CARGO_TARGET_DIR='{}' cargo build",
9636            cache.display()
9637        )];
9638        cfg.verify.build_cache = BuildCache::Isolated;
9639        let denied = |blocked: &Path| {
9640            disk_gate_with(
9641                &repo,
9642                &cfg,
9643                || home.clone(),
9644                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9645            )
9646            .is_some()
9647        };
9648        assert!(!denied(&cache));
9649        assert!(denied(&home_parent));
9650    }
9651
9652    #[test]
9653    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9654        let mut cfg = Config::default();
9655        cfg.disk.min_free_bytes = 0;
9656        let repo = Path::new("/any/repo/path");
9657        assert_eq!(
9658            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9659            None,
9660            "a zero floor never measures at all"
9661        );
9662    }
9663
9664    #[test]
9665    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9666        let cfg = Config::default();
9667        let repo = Path::new("/any/repo/path");
9668        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9669            Err(anyhow::anyhow!("no df on this box"))
9670        })
9671        .expect("a measurement failure must close the gate, not open it");
9672        assert!(reason.contains("could not measure"), "{reason}");
9673    }
9674
9675    #[test]
9676    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9677        let ordinary = task();
9678        let next = advance_interrupt(
9679            Interrupt::Idle,
9680            std::slice::from_ref(&ordinary.id),
9681            std::slice::from_ref(&ordinary),
9682        );
9683        assert_eq!(next, Interrupt::Idle);
9684    }
9685
9686    #[test]
9687    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9688        // Nothing to interrupt - this is just an ordinary candidate, and the
9689        // loop's normal dispatch will pick it up like any other.
9690        let marked = interrupt_task("marked");
9691        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9692        assert_eq!(next, Interrupt::Idle);
9693    }
9694
9695    #[test]
9696    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9697        let marked = interrupt_task("marked");
9698        let next = advance_interrupt(
9699            Interrupt::Idle,
9700            &["running".to_owned()],
9701            std::slice::from_ref(&marked),
9702        );
9703        assert_eq!(
9704            next,
9705            Interrupt::Parking {
9706                parked: vec!["running".to_owned()],
9707                interrupt_task: "marked".to_owned(),
9708            }
9709        );
9710    }
9711
9712    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
9713    /// one run can be in flight when a task becomes runnable and marked.
9714    /// Parking all of them would mean `Resuming` later has more than one id
9715    /// to release back to ordinary dispatch, which cannot be made safe
9716    /// against that same setting's own extra concurrency slots letting two
9717    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
9718    /// The simplification the task's own constraints ask for: do not begin
9719    /// a sequence at all until the herd settles back to exactly one.
9720    #[test]
9721    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9722        let marked = interrupt_task("marked");
9723
9724        let two = advance_interrupt(
9725            Interrupt::Idle,
9726            &["a".to_owned(), "b".to_owned()],
9727            std::slice::from_ref(&marked),
9728        );
9729        assert_eq!(two, Interrupt::Idle);
9730
9731        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9732        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9733    }
9734
9735    #[test]
9736    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9737        let state = Interrupt::Parking {
9738            parked: vec!["running".to_owned()],
9739            interrupt_task: "marked".to_owned(),
9740        };
9741        // Still in flight: no change.
9742        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9743        assert_eq!(still_going, state);
9744
9745        // Left flight, but the interrupt task has not been dispatched yet on
9746        // this tick - stays `Parking` so `interrupt_gate` can let it through,
9747        // as long as it is still runnable.
9748        let stopped_but_not_yet_dispatched =
9749            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9750        assert_eq!(stopped_but_not_yet_dispatched, state);
9751
9752        // Left flight, and the interrupt task is now in flight itself.
9753        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9754        assert_eq!(
9755            dispatched,
9756            Interrupt::Running {
9757                parked: vec!["running".to_owned()],
9758                interrupt_task: "marked".to_owned(),
9759            }
9760        );
9761    }
9762
9763    #[test]
9764    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9765        let state = Interrupt::Running {
9766            parked: vec!["running".to_owned()],
9767            interrupt_task: "marked".to_owned(),
9768        };
9769        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9770        assert_eq!(still_running, state);
9771
9772        // Whatever it ended as - merged, failed, held - is not this
9773        // function's concern: leaving flight is the only trigger, driven
9774        // straight off the same in-flight list `poll` already reaps. It does
9775        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
9776        // why that would let an unrelated task start ahead of, or alongside,
9777        // the guaranteed resume.
9778        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9779        assert_eq!(
9780            ended,
9781            Interrupt::Resuming {
9782                parked: vec!["running".to_owned()]
9783            }
9784        );
9785    }
9786
9787    #[test]
9788    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9789        let state = Interrupt::Resuming {
9790            parked: vec!["running".to_owned()],
9791        };
9792        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9793        assert_eq!(still_waiting, state);
9794
9795        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9796        assert_eq!(dispatched, Interrupt::Idle);
9797    }
9798
9799    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
9800    /// or otherwise moved on by an operator with no claim standing in the
9801    /// way - must not wedge the sequence (and so the whole loop's dispatch,
9802    /// via `interrupt_gate`) waiting forever for a dispatch that can never
9803    /// come. The parked run still gets its resume.
9804    #[test]
9805    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9806    {
9807        let state = Interrupt::Parking {
9808            parked: vec!["running".to_owned()],
9809            interrupt_task: "marked".to_owned(),
9810        };
9811        // `marked` has been held/blocked/deleted since the sequence began:
9812        // it no longer appears in `runnable` at all.
9813        let next = advance_interrupt(state, &[], &[]);
9814        assert_eq!(
9815            next,
9816            Interrupt::Resuming {
9817                parked: vec!["running".to_owned()]
9818            },
9819            "abandoning the interrupt must not abandon the resume it owes"
9820        );
9821    }
9822
9823    /// The same abandonment, one step later: `Resuming` itself must not wait
9824    /// forever for a parked task that has since become unrunnable.
9825    #[test]
9826    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9827        let state = Interrupt::Resuming {
9828            parked: vec!["running".to_owned()],
9829        };
9830        let next = advance_interrupt(state, &[], &[]);
9831        assert_eq!(
9832            next,
9833            Interrupt::Idle,
9834            "nothing is left to wait for; the loop must not stay wedged"
9835        );
9836    }
9837
9838    #[test]
9839    fn disabled_by_config_the_sequence_can_never_leave_idle() {
9840        let marked = interrupt_task("marked");
9841        let next = advance_interrupt_tick(
9842            false,
9843            Interrupt::Idle,
9844            &["running".to_owned()],
9845            std::slice::from_ref(&marked),
9846        );
9847        assert_eq!(
9848            next,
9849            Interrupt::Idle,
9850            "an unmarked, unconfigured daemon must behave exactly as before"
9851        );
9852    }
9853
9854    #[test]
9855    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
9856        let state = Interrupt::Parking {
9857            parked: vec!["running".to_owned()],
9858            interrupt_task: "marked".to_owned(),
9859        };
9860        let candidates = vec![interrupt_task("marked"), task()];
9861        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9862        assert!(
9863            allowed.is_empty(),
9864            "nothing may dispatch - not even the interrupt task itself - \
9865             until the parked run has actually stopped"
9866        );
9867    }
9868
9869    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
9870    /// grow a special case for it: an urgent candidate that is not the
9871    /// interrupt task withholds exactly like an ordinary one for as long as
9872    /// the parked run it is racing has not actually left flight. A version
9873    /// of this feature once bypassed the gate for urgent candidates, on the
9874    /// theory that a genuinely separate concurrency lane could not collide
9875    /// with 75dd's own; it could, and did - the bypassed task dispatched
9876    /// alongside a run 75dd's own state machine had only *asked* to park,
9877    /// not yet confirmed gone, which is exactly the second run
9878    /// `Interrupt::Parking`'s own doc says must never happen. There is no
9879    /// tick during Parking/Running/Resuming where letting an extra
9880    /// candidate through is safe, urgent or not - the parked run may still
9881    /// be genuinely mid-call.
9882    #[test]
9883    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
9884        for state in [
9885            Interrupt::Parking {
9886                parked: vec!["running".to_owned()],
9887                interrupt_task: "marked".to_owned(),
9888            },
9889            Interrupt::Running {
9890                parked: vec!["running".to_owned()],
9891                interrupt_task: "marked".to_owned(),
9892            },
9893            Interrupt::Resuming {
9894                parked: vec!["running".to_owned()],
9895            },
9896        ] {
9897            let candidates = vec![
9898                interrupt_task("marked"),
9899                urgent_task("hot"),
9900                task_with_id("ordinary"),
9901            ];
9902            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9903            assert!(
9904                !allowed.iter().any(|t| t.id == "hot"),
9905                "an urgent candidate must wait out the same gate as anything \
9906                 else while the run it would run alongside has not actually \
9907                 left flight, for state {state:?}: {allowed:?}"
9908            );
9909        }
9910    }
9911
9912    /// The one case where marking a task `--urgent` and `interrupt` at once
9913    /// is not redundant: once the interrupt sequence's own guaranteed
9914    /// resume/dispatch actually admits the task, it is unaffected by also
9915    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
9916    /// never on the urgent flag.
9917    #[test]
9918    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
9919        let state = Interrupt::Resuming {
9920            parked: vec!["hot".to_owned()],
9921        };
9922        let candidates = vec![urgent_task("hot"), task()];
9923        let allowed = interrupt_gate(&state, &[], candidates);
9924        assert_eq!(
9925            allowed.iter().filter(|t| t.id == "hot").count(),
9926            1,
9927            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
9928        );
9929    }
9930
9931    #[test]
9932    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
9933        let state = Interrupt::Parking {
9934            parked: vec!["running".to_owned()],
9935            interrupt_task: "marked".to_owned(),
9936        };
9937        let other = task();
9938        let candidates = vec![interrupt_task("marked"), other.clone()];
9939        let allowed = interrupt_gate(&state, &[], candidates);
9940        assert_eq!(allowed.len(), 1);
9941        assert_eq!(allowed[0].id, "marked");
9942    }
9943
9944    #[test]
9945    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
9946        let state = Interrupt::Running {
9947            parked: vec!["running".to_owned()],
9948            interrupt_task: "marked".to_owned(),
9949        };
9950        let candidates = vec![task(), task()];
9951        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
9952        assert!(allowed.is_empty());
9953    }
9954
9955    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
9956    /// sequence began (only reachable above the default
9957    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
9958    /// never both in the same tick, which is what "exactly one resume, no
9959    /// simultaneous run" actually requires structurally rather than by
9960    /// coincidence of how many ordinary slots happen to be free.
9961    #[test]
9962    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
9963        let state = Interrupt::Resuming {
9964            parked: vec!["a".to_owned(), "c".to_owned()],
9965        };
9966        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
9967        let allowed = interrupt_gate(&state, &[], candidates);
9968        assert_eq!(
9969            allowed.len(),
9970            1,
9971            "at most one candidate may be offered while resuming: {allowed:?}"
9972        );
9973        assert_eq!(allowed[0].id, "a");
9974    }
9975
9976    #[test]
9977    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
9978        let state = Interrupt::Resuming {
9979            parked: vec!["a".to_owned()],
9980        };
9981        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
9982        assert!(allowed.is_empty());
9983    }
9984
9985    /// The invariant the completion criteria ask for by name: across a whole
9986    /// simulated sequence, there is never a tick where the gate would let
9987    /// through both the parked run's resume and the interrupt task, and
9988    /// exactly one candidate resumes the instant the interrupt task's run
9989    /// ends - never zero, never more than one.
9990    #[test]
9991    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
9992        let running = task(); // id: whatever `Task::new` minted
9993        let marked = interrupt_task("marked");
9994
9995        let mut state = Interrupt::Idle;
9996        // Tick 1: `running` is in flight, `marked` becomes runnable.
9997        let in_flight = vec![running.id.clone()];
9998        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
9999        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10000        assert!(gated.is_empty(), "still waiting on `running` to park");
10001
10002        // Tick 2: `running` parked and left flight; nothing dispatched yet.
10003        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10004        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10005        assert_eq!(
10006            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10007            vec!["marked"],
10008            "only the interrupt task may be offered to the dispatcher now"
10009        );
10010
10011        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
10012        state = advance_interrupt_tick(
10013            true,
10014            state,
10015            &["marked".to_owned()],
10016            std::slice::from_ref(&running),
10017        );
10018        let gated = interrupt_gate(
10019            &state,
10020            &["marked".to_owned()],
10021            vec![marked.clone(), running.clone()],
10022        );
10023        assert!(
10024            gated.is_empty(),
10025            "the parked run must not be offered back while the interrupt \
10026             task is still running"
10027        );
10028
10029        // Tick 4: `marked`'s run reached a terminal status and left flight.
10030        // A higher-priority ordinary task `other` is also runnable now - it
10031        // must not be let through instead of, or alongside, `running`.
10032        let other = task_with_id("other");
10033        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10034        assert_eq!(
10035            state,
10036            Interrupt::Resuming {
10037                parked: vec![running.id.clone()]
10038            }
10039        );
10040        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10041        assert_eq!(
10042            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10043            vec![running.id.as_str()],
10044            "exactly the parked run resumes - not the unrelated task, even \
10045             though it was offered first"
10046        );
10047
10048        // Tick 5: `running` is now in flight (dispatched from tick 4's
10049        // gate). Only now does the sequence end and ordinary dispatch fully
10050        // resume.
10051        state = advance_interrupt_tick(
10052            true,
10053            state,
10054            std::slice::from_ref(&running.id),
10055            std::slice::from_ref(&other),
10056        );
10057        assert_eq!(state, Interrupt::Idle);
10058        let gated = interrupt_gate(
10059            &state,
10060            std::slice::from_ref(&running.id),
10061            vec![other.clone()],
10062        );
10063        assert_eq!(
10064            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10065            vec![other.id.as_str()],
10066            "ordinary dispatch is unrestricted again"
10067        );
10068    }
10069
10070    #[test]
10071    fn every_run_status_settles_the_task_it_came_from() {
10072        // run status, resulting task status, attempts still standing after one
10073        let table = [
10074            (RunStatus::Merged, TaskStatus::Done, 1),
10075            (RunStatus::Ready, TaskStatus::Done, 1),
10076            (RunStatus::Stalled, TaskStatus::Failed, 0),
10077            (RunStatus::Blocked, TaskStatus::Failed, 1),
10078            (RunStatus::Failed, TaskStatus::Failed, 1),
10079            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10080            (RunStatus::Prep, TaskStatus::Failed, 1),
10081            (RunStatus::Implementing, TaskStatus::Failed, 1),
10082            (RunStatus::Judging, TaskStatus::Failed, 1),
10083            (RunStatus::Deliberating, TaskStatus::Failed, 1),
10084            (RunStatus::Voting, TaskStatus::Failed, 1),
10085            (RunStatus::Reviewing, TaskStatus::Failed, 1),
10086            (RunStatus::Gating, TaskStatus::Failed, 1),
10087        ];
10088        for (run, want, attempts) in table {
10089            let mut t = task();
10090            t.start("20260902-000000-aaaa".to_owned());
10091            settle(
10092                &mut t,
10093                Verdict {
10094                    status: run,
10095                    left_pr: false,
10096                    parked: false,
10097                    quota_hit: matches!(run, RunStatus::Stalled),
10098                    no_viable_candidates: false,
10099                },
10100                "why",
10101                2,
10102            );
10103            assert_eq!(t.status, want, "task status after {}", label(run));
10104            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10105        }
10106    }
10107
10108    #[test]
10109    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10110        let mut stalled = task();
10111        stalled.start("20260902-000000-aaaa".to_owned());
10112        settle(
10113            &mut stalled,
10114            Verdict {
10115                status: RunStatus::Stalled,
10116                left_pr: false,
10117                parked: false,
10118                quota_hit: true,
10119                no_viable_candidates: false,
10120            },
10121            "quota",
10122            1,
10123        );
10124        assert_eq!(stalled.attempts, 0);
10125        assert!(
10126            stalled.status.runnable(),
10127            "a machine problem must leave the task in line"
10128        );
10129
10130        let mut blocked = task();
10131        blocked.start("20260902-000000-aaaa".to_owned());
10132        settle(
10133            &mut blocked,
10134            Verdict {
10135                status: RunStatus::Blocked,
10136                left_pr: false,
10137                parked: false,
10138                quota_hit: false,
10139                no_viable_candidates: false,
10140            },
10141            "findings open",
10142            1,
10143        );
10144        assert_eq!(blocked.attempts, 1);
10145        assert_eq!(
10146            blocked.status,
10147            TaskStatus::Held,
10148            "the last attempt hands the task to a human"
10149        );
10150    }
10151
10152    #[test]
10153    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10154        // Attempts to spare: without the pull request this task would go
10155        // straight back in line and run the whole competition again.
10156        let mut delivered = task();
10157        delivered.start("20260903-080619-01c2".to_owned());
10158        settle(
10159            &mut delivered,
10160            Verdict {
10161                status: RunStatus::Blocked,
10162                left_pr: true,
10163                parked: false,
10164                quota_hit: false,
10165                no_viable_candidates: false,
10166            },
10167            "no check status",
10168            4,
10169        );
10170        assert_eq!(
10171            delivered.status,
10172            TaskStatus::Held,
10173            "a pull request waiting on CI or a person is not a retryable failure"
10174        );
10175        assert!(
10176            !delivered.status.runnable(),
10177            "the loop must not pick this task up again"
10178        );
10179        assert_eq!(
10180            delivered.last_error.as_deref(),
10181            Some("no check status"),
10182            "the operator needs to be told what the gate was waiting for"
10183        );
10184
10185        // The same status without a pull request is a plain failure, and with
10186        // attempts left it is retried.
10187        let mut empty_handed = task();
10188        empty_handed.start("20260903-080619-01c2".to_owned());
10189        settle(
10190            &mut empty_handed,
10191            Verdict {
10192                status: RunStatus::Blocked,
10193                left_pr: false,
10194                parked: false,
10195                quota_hit: false,
10196                no_viable_candidates: false,
10197            },
10198            "findings open",
10199            4,
10200        );
10201        assert_eq!(empty_handed.status, TaskStatus::Failed);
10202        assert!(empty_handed.status.runnable());
10203    }
10204
10205    #[test]
10206    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10207        // Every candidate agreed, with evidence, that nothing belonged in the
10208        // worktree. That is not a confirmed success to close automatically -
10209        // a human still has to check the claim - and it is not an ordinary
10210        // failure either, so this settles exactly like a pull request nobody
10211        // merged yet: `Held`, same as `Blocked` with a PR.
10212        let mut noop = task();
10213        noop.start("20260912-131304-391f".to_owned());
10214        settle(
10215            &mut noop,
10216            Verdict {
10217                status: RunStatus::VerifiedNoop,
10218                left_pr: false,
10219                parked: false,
10220                quota_hit: false,
10221                no_viable_candidates: true,
10222            },
10223            "candidate A: already fixed by b32cfc4, on main",
10224            4,
10225        );
10226        assert_eq!(
10227            noop.status,
10228            TaskStatus::Held,
10229            "an unverified claim is a request for a human, not a failure"
10230        );
10231        assert!(
10232            !noop.status.runnable(),
10233            "the loop must not requeue this on the same unverified claim"
10234        );
10235        // `Task::release` resets attempts to zero the moment a human looks at
10236        // the evidence and lets it run again, so it does not matter here
10237        // whether the one attempt already spent stays spent - what matters is
10238        // that nothing retries this task unattended in the meantime.
10239        assert_eq!(noop.attempts, 1);
10240    }
10241
10242    #[test]
10243    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10244        // Parking is the operator asking for the process back - to replace the
10245        // binary, most of all. The run's work is intact on disk, so this is
10246        // not a failed attempt, and charging for it would mean a few upgrades
10247        // could exhaust a budget meant for agents that misbehaved.
10248        let mut parked = task();
10249        parked.start("20260903-183634-2d98".to_owned());
10250        settle(
10251            &mut parked,
10252            Verdict {
10253                status: RunStatus::Implementing,
10254                left_pr: false,
10255                quota_hit: false,
10256                parked: true,
10257                no_viable_candidates: false,
10258            },
10259            "parked after `implementing`",
10260            2,
10261        );
10262        assert_eq!(parked.attempts, 0, "a park is refunded");
10263        assert!(
10264            parked.status.runnable(),
10265            "and the task stays in line so the next loop resumes its run"
10266        );
10267        assert_eq!(parked.status, TaskStatus::Parked);
10268        assert_eq!(
10269            parked.park_reason.as_deref(),
10270            Some("parked after `implementing`"),
10271            "the card says where it stopped"
10272        );
10273        assert_eq!(parked.last_error, None, "nothing failed");
10274
10275        // Without the park flag the same non-terminal status is what it always
10276        // was: `execute` returning mid-flight, which is a bug and spends an
10277        // attempt so a task cannot loop on it forever.
10278        let mut broken = task();
10279        broken.start("20260903-183634-2d98".to_owned());
10280        settle(
10281            &mut broken,
10282            Verdict {
10283                status: RunStatus::Implementing,
10284                left_pr: false,
10285                quota_hit: false,
10286                parked: false,
10287                no_viable_candidates: false,
10288            },
10289            "returned mid-flight",
10290            2,
10291        );
10292        assert_eq!(broken.attempts, 1);
10293    }
10294
10295    #[test]
10296    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10297        // Run e633: quorum lost because two judges answered with the wrong
10298        // JSON shape, `quota: []`. Refunding that takes the bound off the
10299        // retry loop, and each retry pays for a fresh hour-long implement
10300        // wave before it can fail the same way.
10301        let mut flaky = task();
10302        flaky.start("20260903-123023-e633".to_owned());
10303        settle(
10304            &mut flaky,
10305            Verdict {
10306                status: RunStatus::Stalled,
10307                left_pr: false,
10308                parked: false,
10309                quota_hit: false,
10310                no_viable_candidates: false,
10311            },
10312            "verdict rests on 1 of 3 judges",
10313            2,
10314        );
10315        assert_eq!(
10316            flaky.attempts, 1,
10317            "flakiness spends an attempt, so `max_attempts` still bounds it"
10318        );
10319        assert!(flaky.status.runnable(), "and it is still worth retrying");
10320
10321        // The same status, lost to a rate limit, is the machine's fault.
10322        let mut limited = task();
10323        limited.start("20260903-123023-e633".to_owned());
10324        settle(
10325            &mut limited,
10326            Verdict {
10327                status: RunStatus::Stalled,
10328                left_pr: false,
10329                parked: false,
10330                quota_hit: true,
10331                no_viable_candidates: false,
10332            },
10333            "judge-2, judge-3 out of quota",
10334            2,
10335        );
10336        assert_eq!(limited.attempts, 0, "a quota window is refunded");
10337        assert!(limited.status.runnable());
10338
10339        // And the bound really binds: a task that keeps stalling on flakiness
10340        // reaches a human instead of running the roster forever.
10341        let mut worn = task();
10342        for _ in 0..2 {
10343            worn.release();
10344        }
10345        worn.start("20260903-123023-e633".to_owned());
10346        worn.attempts = 2;
10347        settle(
10348            &mut worn,
10349            Verdict {
10350                status: RunStatus::Stalled,
10351                left_pr: false,
10352                parked: false,
10353                quota_hit: false,
10354                no_viable_candidates: false,
10355            },
10356            "no quorum again",
10357            2,
10358        );
10359        assert_eq!(worn.status, TaskStatus::Held);
10360        assert!(!worn.status.runnable());
10361    }
10362
10363    #[test]
10364    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10365        // The implement wave loses every seat to the same rate limit and
10366        // `after_implement` bails with nothing viable, which surfaces as
10367        // `Failed` rather than `Stalled`. That is the same machine fact the
10368        // `Stalled`-quota row already refunds, and must be refunded the same
10369        // way, or a quota outage quietly holds every task it touches instead
10370        // of leaving them in line for the reset.
10371        let mut wiped_out = task();
10372        wiped_out.start("20260907-025000-a1b2".to_owned());
10373        settle(
10374            &mut wiped_out,
10375            Verdict {
10376                status: RunStatus::Failed,
10377                left_pr: false,
10378                parked: false,
10379                quota_hit: true,
10380                no_viable_candidates: true,
10381            },
10382            "no candidate produced a change; nothing to judge",
10383            2,
10384        );
10385        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10386        assert!(
10387            wiped_out.status.runnable(),
10388            "a machine problem must leave the task in line"
10389        );
10390
10391        // This is the exemption that must stay narrow: a candidate that did
10392        // produce a change, and then failed for some other reason, still
10393        // spends the attempt even though a seat elsewhere hit its quota.
10394        // Otherwise every ordinary failure that happens to share a run with
10395        // an unrelated rate limit would be refunded for free.
10396        let mut partial_progress = task();
10397        partial_progress.start("20260907-025500-c3d4".to_owned());
10398        settle(
10399            &mut partial_progress,
10400            Verdict {
10401                status: RunStatus::Failed,
10402                left_pr: false,
10403                parked: false,
10404                quota_hit: true,
10405                no_viable_candidates: false,
10406            },
10407            "gate failed on the winning candidate",
10408            2,
10409        );
10410        assert_eq!(
10411            partial_progress.attempts, 1,
10412            "a candidate that actually produced a change spends the attempt \
10413             even though some other seat hit its quota"
10414        );
10415        assert!(partial_progress.status.runnable());
10416    }
10417
10418    #[test]
10419    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10420        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
10421        // disk, and that construction must reach the same conclusion as the
10422        // one `attempt` builds from a live run, or a crash at exactly the
10423        // wrong moment gives a recovered task a different policy than one a
10424        // daemon finished settling itself.
10425        let mut t = task();
10426        t.start("20260907-025000-a1b2".to_owned());
10427        let mut state = run_state(RunStatus::Failed);
10428        state.quota.push(QuotaLoss {
10429            cause: crate::agent::QuotaCause::UsageLimit,
10430            agent: String::new(),
10431            seat: "cand-a".to_owned(),
10432            node: "implement".to_owned(),
10433            at: Timestamp::now(),
10434            reset: None,
10435        });
10436        assert!(
10437            state.viable().is_empty(),
10438            "no candidate was added, so nothing is viable"
10439        );
10440        reclaim(&mut t, Some(state), 2, "en");
10441        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10442        assert!(t.status.runnable());
10443    }
10444
10445    #[test]
10446    fn a_held_task_is_never_offered_to_the_loop() {
10447        let dir = tempfile::tempdir().unwrap();
10448        let queue = Queue::at(dir.path().to_path_buf());
10449        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10450            let mut t = task();
10451            t.id = format!("2026090{n}-000000-000{n}");
10452            t.priority = priority;
10453            queue.put(&mut t).unwrap();
10454        }
10455        let mut held = task();
10456        held.id = "20260909-000000-9999".to_owned();
10457        held.priority = 99;
10458        held.hold_machine(None);
10459        queue.put(&mut held).unwrap();
10460
10461        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10462        assert_eq!(order.len(), 3);
10463        assert!(!order.contains(&held.id));
10464        assert_eq!(
10465            order.first().cloned(),
10466            queue.next_runnable().map(|t| t.id),
10467            "the loop's first candidate is exactly what the queue offers"
10468        );
10469        assert_eq!(
10470            order,
10471            vec![
10472                "20260902-000000-0002".to_owned(),
10473                "20260903-000000-0003".to_owned(),
10474                "20260901-000000-0001".to_owned(),
10475            ],
10476            "priority first, then oldest, so nothing starves"
10477        );
10478    }
10479
10480    #[test]
10481    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10482        let dir = tempfile::tempdir().unwrap();
10483        let queue = Queue::at(dir.path().to_path_buf());
10484        let mut old = task();
10485        old.id = "20260101-000000-old0".to_owned();
10486        queue.put(&mut old).unwrap();
10487        let mut fresh = task();
10488        fresh.id = "20260101-000000-new0".to_owned();
10489        queue.put(&mut fresh).unwrap();
10490
10491        // No parseable pid at all, so age is the only signal there is to
10492        // check - unlike a real `Queue::claim`, which always names a real,
10493        // and therefore alive, pid this test cannot fake as dead.
10494        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10495        std::thread::sleep(Duration::from_millis(60));
10496        let live = queue.claim(&fresh.id).unwrap();
10497
10498        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10499        assert_eq!(swept, vec![old.id.clone()]);
10500        assert!(
10501            queue.claim(&old.id).is_ok(),
10502            "an unparseable lock older than the threshold is swept"
10503        );
10504        assert!(
10505            queue.claim(&fresh.id).is_err(),
10506            "a live pid protects its lock regardless of age"
10507        );
10508        drop(live);
10509    }
10510
10511    #[test]
10512    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10513        // A live worker's claim remains authoritative even beyond the sweep's
10514        // age limit. Sweeping it would permit a second competing attempt.
10515        let dir = tempfile::tempdir().unwrap();
10516        let queue = Queue::at(dir.path().to_path_buf());
10517        let mut t = task();
10518        t.id = "20260101-000000-live".to_owned();
10519        queue.put(&mut t).unwrap();
10520
10521        let claim = queue.claim(&t.id).unwrap();
10522        std::thread::sleep(Duration::from_millis(60));
10523
10524        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10525        assert!(
10526            swept.is_empty(),
10527            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10528        );
10529        assert!(
10530            queue.claim(&t.id).is_err(),
10531            "the lock still protects its task"
10532        );
10533        drop(claim);
10534    }
10535
10536    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
10537    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
10538    fn injected_dead_pid() -> u32 {
10539        std::process::id().checked_add(1).unwrap_or(1)
10540    }
10541
10542    #[test]
10543    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
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-dead".to_owned();
10548        queue.put(&mut t).unwrap();
10549        let dead_pid = injected_dead_pid();
10550
10551        // Written directly rather than through `Queue::claim`, which would
10552        // stamp this test process's own very much alive pid and defeat the
10553        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
10554        // like moments after it died, not six hours later.
10555        std::fs::write(
10556            dir.path().join(format!("{}.lock", t.id)),
10557            dead_pid.to_string(),
10558        )
10559        .unwrap();
10560
10561        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10562            pid != dead_pid
10563        });
10564        assert_eq!(
10565            swept,
10566            vec![t.id.clone()],
10567            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10568        );
10569        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10570    }
10571
10572    #[test]
10573    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10574        let dir = tempfile::tempdir().unwrap();
10575        let queue = Queue::at(dir.path().to_path_buf());
10576        let mut t = task();
10577        t.id = "20260101-000000-late".to_owned();
10578        queue.put(&mut t).unwrap();
10579        let dead_pid = injected_dead_pid();
10580
10581        // Tick one, standing in for the sweep `poll` already runs at
10582        // startup: nothing to find yet.
10583        assert!(
10584            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10585            "nothing has claimed the task yet"
10586        );
10587
10588        // A second daemon claims the task and dies before it ever writes
10589        // `running`, well after this loop's own startup sweep already ran.
10590        std::fs::write(
10591            dir.path().join(format!("{}.lock", t.id)),
10592            dead_pid.to_string(),
10593        )
10594        .unwrap();
10595
10596        // Tick two, standing in for a poll long into this daemon's uptime:
10597        // the same function, called again, notices what only just appeared -
10598        // proving the sweep is not a one-shot startup check.
10599        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10600            pid != dead_pid
10601        });
10602        assert_eq!(swept, vec![t.id.clone()]);
10603    }
10604
10605    #[test]
10606    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10607        // `reclaim_orphaned_running` looks up the task's last run, which
10608        // touches `run::home()`; the first call anywhere in this binary wins,
10609        // so this is a no-op if another test already pinned one, and either
10610        // way the run id below is never written under it.
10611        crate::run::pin_test_home();
10612        let dir = tempfile::tempdir().unwrap();
10613        let queue = Queue::at(dir.path().to_path_buf());
10614        let mut t = task();
10615        t.id = "20260101-000000-crsh".to_owned();
10616        t.status = TaskStatus::Running;
10617        t.attempts = 1;
10618        // No `run.json` behind this id: standing in for a run this test does
10619        // not need to make readable, since the point is the lock, not the
10620        // recovery table `reclaim` already has its own tests for.
10621        t.runs.push("20260904-000000-4043".to_owned());
10622        queue.put(&mut t).unwrap();
10623        let dead_pid = injected_dead_pid();
10624
10625        // The crashed daemon's own claim, naming a pid nothing on the
10626        // machine holds anymore.
10627        std::fs::write(
10628            dir.path().join(format!("{}.lock", t.id)),
10629            dead_pid.to_string(),
10630        )
10631        .unwrap();
10632
10633        // Before the lock is swept the task looks claimed, and
10634        // `reclaim_orphaned_running` must leave it alone - this is exactly
10635        // the bug: a `running` task stranded behind a dead daemon's lock,
10636        // invisible to the claim-as-proof check because the lock outlived
10637        // the process that wrote it.
10638        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10639        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10640
10641        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10642            pid != dead_pid
10643        });
10644        assert_eq!(swept, vec![t.id.clone()]);
10645
10646        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10647        assert_eq!(reclaimed, vec![t.id.clone()]);
10648        let after = queue.get(&t.id).unwrap();
10649        assert_eq!(
10650            after.status,
10651            TaskStatus::Held,
10652            "no run.json to recover from, so a human is asked"
10653        );
10654        assert_eq!(
10655            after.runs,
10656            vec!["20260904-000000-4043".to_owned()],
10657            "the crashed run's id is kept as evidence, not discarded"
10658        );
10659    }
10660
10661    #[test]
10662    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10663        let dir = tempfile::tempdir().unwrap();
10664        let queue = Queue::at(dir.path().to_path_buf());
10665        let mut t = task();
10666        t.id = "20260101-000000-unknown".to_owned();
10667        queue.put(&mut t).unwrap();
10668        let dead_pid = injected_dead_pid();
10669        std::fs::write(
10670            dir.path().join(format!("{}.lock", t.id)),
10671            dead_pid.to_string(),
10672        )
10673        .unwrap();
10674
10675        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10676        assert!(swept.is_empty(), "an unknown pid must keep its lock");
10677        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10678    }
10679
10680    fn run_state_in(status: RunStatus, language: &str) -> RunState {
10681        let mut s = run_state(status);
10682        s.config.graph.language = language.to_owned();
10683        s
10684    }
10685
10686    fn unstarted_verdict(status: RunStatus) -> Verdict {
10687        Verdict {
10688            status,
10689            left_pr: false,
10690            quota_hit: false,
10691            parked: false,
10692            no_viable_candidates: false,
10693        }
10694    }
10695
10696    #[test]
10697    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10698        let mut t = task();
10699        t.attempts = 1;
10700        settle_in(
10701            &mut t,
10702            unstarted_verdict(RunStatus::AlreadyInBase),
10703            "already in main",
10704            1,
10705            phrases("en"),
10706            None,
10707        );
10708        assert_eq!(t.status, TaskStatus::Done);
10709        assert_eq!(t.attempts, 0);
10710    }
10711
10712    #[test]
10713    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10714        let reason = |language: &str| {
10715            let mut t = task();
10716            settle_in(
10717                &mut t,
10718                unstarted_verdict(RunStatus::Judging),
10719                "boom",
10720                1,
10721                phrases(language),
10722                None,
10723            );
10724            t.last_error.or(t.hold_reason).unwrap_or_default()
10725        };
10726        assert!(
10727            reason("en").starts_with("the graph stopped at `"),
10728            "{}",
10729            reason("en")
10730        );
10731        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10732        assert!(reason("日本語").contains("boom"));
10733        assert_eq!(reason("fr"), reason("en"));
10734    }
10735
10736    #[test]
10737    fn describe_follows_the_run_language_and_keeps_the_run_id() {
10738        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10739        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10740        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10741        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10742        assert!(ja.contains("[run "), "{ja}");
10743        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10744        assert!(ended.starts_with("run 終了: "), "{ended}");
10745        let mut de = run_state_in(RunStatus::Failed, "de");
10746        let mut en = run_state_in(RunStatus::Failed, "en");
10747        de.id = "same".to_owned();
10748        en.id = "same".to_owned();
10749        assert_eq!(describe(&de), describe(&en));
10750    }
10751
10752    #[test]
10753    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10754        use crate::handover::Refused;
10755        let cases = [
10756            Refused::Foreign {
10757                branch: "b".into(),
10758                path: "/w/x".into(),
10759                why: "made by hand".into(),
10760            },
10761            Refused::Unsafe {
10762                branch: "b".into(),
10763                path: "/w/x".into(),
10764                why: "its worktree has uncommitted changes (a.rs)".into(),
10765            },
10766            Refused::ReleaseFailed {
10767                branch: "b".into(),
10768                path: "/w/x".into(),
10769                run: "ab12".into(),
10770            },
10771        ];
10772        for r in &cases {
10773            let en = (phrases("en").handover_refused)(r);
10774            assert_eq!(en, r.to_string());
10775            let ja = (phrases("ja").handover_refused)(r);
10776            assert!(
10777                !ja.contains("is checked out") && !ja.contains("try again"),
10778                "{ja}"
10779            );
10780            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10781            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10782                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10783            }
10784        }
10785        assert!(phrases("en").handover_hint.contains("release the task"));
10786        assert!(phrases("ja").handover_hint.contains("解放"));
10787    }
10788
10789    #[test]
10790    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10791        let build = |lang: &str| {
10792            let mut s = run_state_in(RunStatus::Blocked, lang);
10793            s.id = "same".to_owned();
10794            s.config.graph.review_rounds = 3;
10795            let mut r = review_round(3);
10796            r.expected = 3;
10797            r.answered = 1;
10798            s.reviews.push(r);
10799            s.event(
10800                "review",
10801                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10802            );
10803            s
10804        };
10805        let en = describe(&build("en"));
10806        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10807        let ja = describe(&build("ja"));
10808        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10809        assert!(!ja.contains("never answered"), "{ja}");
10810        assert!(ja.contains("[run "), "{ja}");
10811
10812        // An incomplete panel whose verification failed is a different stop:
10813        // the real event must survive in ja too.
10814        let mut failed = build("ja");
10815        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10816            command: "cargo test".to_owned(),
10817            code: Some(1),
10818            output_tail: String::new(),
10819            duration_ms: 0,
10820            resource_blocked: false,
10821            ..Default::default()
10822        });
10823        failed.event("review", "stopped; e2e failed: cargo test");
10824        let ja = describe(&failed);
10825        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10826        assert!(!ja.contains("席のレビュアー"), "{ja}");
10827    }
10828
10829    #[test]
10830    fn refusals_and_recovery_prose_follow_the_language() {
10831        let home = crate::run::test_home();
10832        let t = held_task_with("r1");
10833        let q = action_question(
10834            "r1",
10835            ask::ChoiceAction::Resume {
10836                run: "r1".to_owned(),
10837            },
10838        );
10839        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10840            ActionDecision::Refuse(s) => s,
10841            other => panic!("{other:?}"),
10842        };
10843        assert!(refuse(phrases("en")).contains("could not be read: gone"));
10844        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10845        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10846
10847        let mut held = task();
10848        reclaim(&mut held, None, 2, "ja");
10849        assert!(held.hold_reason.unwrap().contains("保留にしました"));
10850        let mut held = task();
10851        reclaim(&mut held, None, 2, "xx");
10852        assert!(held.hold_reason.unwrap().contains("held for a human"));
10853    }
10854
10855    fn run_state(status: RunStatus) -> RunState {
10856        let mut state = RunState::new(
10857            PathBuf::from("/repo"),
10858            "main".to_owned(),
10859            "abc1234def".to_owned(),
10860            "add retries".to_owned(),
10861            Config::default(),
10862        );
10863        state.status = status;
10864        state
10865    }
10866
10867    #[test]
10868    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
10869        crate::run::pin_test_home();
10870        let dir = tempfile::tempdir().unwrap();
10871        let mut state = run_state(RunStatus::Blocked);
10872        state.id = "20260101-000000-audit".into();
10873        state.save_under(dir.path()).unwrap();
10874        let mut t = task();
10875        t.start(state.id.clone());
10876        // The final state is newer than disk, as when a worker settles its
10877        // in-memory outcome or recovery is passed an already loaded run.
10878        state.status = RunStatus::Ready;
10879        settle_and_diagnose(
10880            &mut t,
10881            unstarted_verdict(RunStatus::Ready),
10882            "Verified local delivery",
10883            2,
10884            &state,
10885        );
10886        let completion = t.completion_history.last().unwrap();
10887        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
10888        assert_eq!(completion.prior_status, TaskStatus::Running);
10889        assert_eq!(
10890            completion.reason.as_deref(),
10891            Some("Verified local delivery")
10892        );
10893        let snapshot = completion.run.as_ref().unwrap();
10894        assert_eq!(snapshot.id, state.id);
10895        assert_eq!(snapshot.status, Some(RunStatus::Ready));
10896        assert_eq!(
10897            RunState::load_under(&state.id, dir.path()).unwrap().status,
10898            RunStatus::Blocked,
10899            "settlement records the actual outcome without rewriting run history"
10900        );
10901    }
10902
10903    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
10904        Candidate {
10905            index: 0,
10906            label,
10907            agent: "claude".to_owned(),
10908            branch: format!("magi/x/{label}"),
10909            worktree: PathBuf::from("/repo"),
10910            summary: summary.to_owned(),
10911            stat: String::new(),
10912            files: 0,
10913            commits: usize::from(!empty),
10914            empty,
10915            failed: failed.map(str::to_owned),
10916            verified_noop: None,
10917            duration_ms: 0,
10918            folded: false,
10919        }
10920    }
10921
10922    #[test]
10923    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
10924        let mut state = run_state(RunStatus::Blocked);
10925        state.gate = vec![
10926            CommandOutcome {
10927                command: "cargo make check".to_owned(),
10928                code: Some(0),
10929                output_tail: "ok".to_owned(),
10930                duration_ms: 0,
10931                resource_blocked: false,
10932                ..Default::default()
10933            },
10934            CommandOutcome {
10935                command: "cargo test".to_owned(),
10936                code: Some(101),
10937                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
10938                duration_ms: 0,
10939                resource_blocked: false,
10940                ..Default::default()
10941            },
10942        ];
10943        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
10944        assert!(d.contains("cargo test"), "{d}");
10945        assert!(
10946            !d.contains("cargo make check"),
10947            "a passing check is not a diagnostic: {d}"
10948        );
10949        assert!(d.contains("assertion failed"), "{d}");
10950    }
10951
10952    #[test]
10953    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
10954        let mut state = run_state(RunStatus::Blocked);
10955        state.event(
10956            "land",
10957            "stopped: the fixer produced no commit while 2 check(s) were failing \
10958             (build, lint); stopping instead of looping on an unchanged tree",
10959        );
10960        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
10961        assert!(d.contains("build"), "{d}");
10962        assert!(d.contains("lint"), "{d}");
10963        assert!(d.contains("fixer produced no commit"), "{d}");
10964    }
10965
10966    #[test]
10967    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
10968        // `describe`'s output becomes `Task::last_error` verbatim, and the
10969        // phone renders that in the same alarm-styled box an ordinary
10970        // failure gets. A bare `verified_noop` there would read exactly like
10971        // the failure this status exists to be told apart from.
10972        let state = run_state(RunStatus::VerifiedNoop);
10973        let d = describe(&state);
10974        assert!(
10975            d.contains("agent-verified no-op"),
10976            "expected the display label, not the wire spelling: {d}"
10977        );
10978        assert!(!d.contains("verified_noop"), "{d}");
10979    }
10980
10981    #[test]
10982    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
10983        let mut state = run_state(RunStatus::Failed);
10984        state.gate.push(crate::run::CommandOutcome {
10985            command: "cargo test".into(),
10986            code: Some(101),
10987            output_tail: format!(
10988                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
10989                "  41: 0x1234 - backtrace frame\n".repeat(10000)
10990            ),
10991            duration_ms: 1,
10992            resource_blocked: false,
10993            ..Default::default()
10994        });
10995        let d = diagnostic(&state).unwrap();
10996        assert!(d.contains("panicked at widget.rs:12"), "{d}");
10997        assert!(d.contains("assertion failed: widget missing"));
10998        assert!(d.contains("widget log"));
10999    }
11000
11001    #[test]
11002    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11003        // The whole point of the feature: a run held as "no candidate produced
11004        // a change" can mean the implementer actually finished the task and
11005        // only left a clean local tree behind - see AGENTS.md on this exact
11006        // failure mode. The diagnostic has to carry what the agent actually
11007        // said, not just the fact that nothing was there to judge.
11008        let mut state = run_state(RunStatus::Failed);
11009        state.candidates = vec![candidate(
11010            'A',
11011            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11012            true,
11013            None,
11014        )];
11015        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11016        assert!(d.contains("candidate A"), "{d}");
11017        assert!(d.contains("tagged v1.2.3"), "{d}");
11018    }
11019
11020    #[test]
11021    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11022        let mut state = run_state(RunStatus::Failed);
11023        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11024        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11025        assert!(d.contains("candidate A"), "{d}");
11026        assert!(d.contains("agent timed out"), "{d}");
11027    }
11028
11029    #[test]
11030    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11031        // A viable candidate existed, the gate never ran, and nothing land
11032        // said matches - `Task::last_error` is left to explain this one alone.
11033        let mut state = run_state(RunStatus::Failed);
11034        state.candidates = vec![candidate('A', "did the work", false, None)];
11035        assert!(diagnostic(&state).is_none());
11036    }
11037
11038    #[test]
11039    fn diagnostic_is_bounded_however_much_a_run_printed() {
11040        let mut state = run_state(RunStatus::Blocked);
11041        state.gate = vec![
11042            CommandOutcome {
11043                command: "cargo test".to_owned(),
11044                code: Some(101),
11045                output_tail: "x".repeat(50_000),
11046                duration_ms: 0,
11047                resource_blocked: false,
11048                ..Default::default()
11049            },
11050            CommandOutcome {
11051                command: "cargo clippy".to_owned(),
11052                code: Some(1),
11053                output_tail: "y".repeat(50_000),
11054                duration_ms: 0,
11055                resource_blocked: false,
11056                ..Default::default()
11057            },
11058        ];
11059        state.candidates = vec![
11060            candidate('A', &"z".repeat(50_000), true, None),
11061            candidate('B', &"w".repeat(50_000), true, None),
11062        ];
11063        let d = diagnostic(&state).expect("plenty here to diagnose");
11064        assert!(
11065            d.len() <= DIAGNOSTIC_MAX,
11066            "diagnostic grew to {} bytes, unbounded",
11067            d.len()
11068        );
11069    }
11070
11071    #[test]
11072    fn selected_delivery_guards_survive_recovery_failure_accounting() {
11073        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11074            let mut t = task();
11075            let mut state = run_state(status);
11076            t.pr_recovery = Some(crate::pr_recovery::Selection {
11077                url: "url".into(),
11078                branch: format!("magi/task-{}", t.id),
11079                head: "a".repeat(40),
11080                source_head: None,
11081                source_run: None,
11082                source_proof: None,
11083                disposition: Some(crate::pr_recovery::Disposition::Land),
11084                instruction: t.instruction.clone(),
11085                approved_at: Timestamp::now(),
11086            });
11087            state.pr_recovery = t.pr_recovery.clone();
11088            t.start(state.id.clone());
11089            settle_and_diagnose(
11090                &mut t,
11091                Verdict {
11092                    status,
11093                    left_pr: false,
11094                    quota_hit: false,
11095                    parked: false,
11096                    no_viable_candidates: false,
11097                },
11098                "delivery stopped",
11099                5,
11100                &state,
11101            );
11102            assert_eq!(t.status, TaskStatus::Held);
11103            let reason = t.hold_reason.as_deref().unwrap();
11104            if status == RunStatus::Ready {
11105                assert!(reason.contains("Selected PR delivery is incomplete"));
11106                assert!(t.recovery_budget.is_none());
11107            } else {
11108                assert!(reason.contains("Selected recovery stopped"));
11109                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11110            }
11111            assert!(t.pr_recovery.is_some());
11112        }
11113    }
11114
11115    #[test]
11116    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11117        let mut state = run_state(RunStatus::Voting);
11118        state.base_sync = Some(crate::run::BaseSync {
11119            tip: "base-tip".into(),
11120            behind: 3,
11121            attempts: 4,
11122            conflict: Some("base stopped".into()),
11123            already_in: None,
11124        });
11125        state.record_base_sync_stop("candidate-head");
11126        let mut t = task();
11127        t.start(state.id.clone());
11128        let verdict = Verdict {
11129            status: RunStatus::Blocked,
11130            left_pr: false,
11131            quota_hit: false,
11132            parked: false,
11133            no_viable_candidates: false,
11134        };
11135        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11136        assert_eq!(
11137            t.status,
11138            TaskStatus::Held,
11139            "unspent task attempts cannot start another competition"
11140        );
11141        let at = t.held_at;
11142        let cause = t.hold_notice_cause.clone();
11143        state.begin_pass();
11144        t.release_operator("test-resume", None);
11145        t.start(state.id.clone());
11146        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11147        assert_eq!(t.status, TaskStatus::Held);
11148        assert_eq!(t.held_at, at);
11149        assert_eq!(t.hold_notice_cause, cause);
11150    }
11151
11152    #[test]
11153    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11154        let mut state = run_state(RunStatus::Blocked);
11155        state.gate = vec![CommandOutcome {
11156            command: "cargo test".to_owned(),
11157            code: Some(101),
11158            output_tail: "assertion failed".to_owned(),
11159            duration_ms: 0,
11160            resource_blocked: false,
11161            ..Default::default()
11162        }];
11163        let verdict = Verdict {
11164            status: RunStatus::Blocked,
11165            left_pr: false,
11166            quota_hit: false,
11167            parked: false,
11168            no_viable_candidates: false,
11169        };
11170
11171        // Attempt one of two still has a retry coming: no diagnostic yet, the
11172        // task is going to run again and this run's evidence would go stale.
11173        let mut t = task();
11174        t.start("run-1".to_owned());
11175        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11176        assert_eq!(t.status, TaskStatus::Failed);
11177        assert!(t.diagnostic.is_none());
11178
11179        // Attempt two exhausts the budget: now it is held, and the
11180        // diagnostic is what `magi task show` has to say more than one line.
11181        t.start("run-2".to_owned());
11182        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11183        assert_eq!(t.status, TaskStatus::Held);
11184        let d = t.diagnostic.expect("a held task must carry its diagnostic");
11185        assert!(d.contains("cargo test"), "{d}");
11186    }
11187
11188    fn verified_noop_run_state() -> RunState {
11189        let mut state = run_state(RunStatus::VerifiedNoop);
11190        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":[]}"#;
11191        let mut c = candidate('A', summary, true, None);
11192        c.verified_noop = Some(summary.to_owned());
11193        state.candidates = vec![c];
11194        state
11195    }
11196
11197    #[test]
11198    fn a_held_task_names_the_open_question_it_is_waiting_on() {
11199        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
11200        // `magi ask` question settled Held with `hold_reason: null`, so the
11201        // notification said nothing actionable. `note_open_question` should
11202        // append the question id to whatever `handed_off` already wrote.
11203        crate::run::pin_test_home();
11204        let home = crate::run::home();
11205        let state = verified_noop_run_state();
11206        let mut q = ask::Question::new(
11207            state.id.clone(),
11208            "implement".to_owned(),
11209            "impl-A".to_owned(),
11210            "is this really a no-op?".to_owned(),
11211            String::new(),
11212            Vec::new(),
11213        );
11214        Questions::at(home.join("questions")).put(&mut q).unwrap();
11215
11216        let verdict = Verdict {
11217            status: RunStatus::VerifiedNoop,
11218            left_pr: false,
11219            quota_hit: false,
11220            parked: false,
11221            no_viable_candidates: true,
11222        };
11223        let mut t = task();
11224        t.start(state.id.clone());
11225        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11226
11227        assert_eq!(t.status, TaskStatus::Held);
11228        let reason = t.hold_reason.expect("a held task must record why");
11229        assert!(
11230            reason.starts_with("run ended agent-verified no-op"),
11231            "the original settle reason must survive unchanged: {reason}"
11232        );
11233        assert!(
11234            reason.contains(q.short()),
11235            "the open question's id must be named so the notice is actionable: {reason}"
11236        );
11237    }
11238
11239    #[test]
11240    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11241        crate::run::pin_test_home();
11242        let state = verified_noop_run_state();
11243
11244        let verdict = Verdict {
11245            status: RunStatus::VerifiedNoop,
11246            left_pr: false,
11247            quota_hit: false,
11248            parked: false,
11249            no_viable_candidates: true,
11250        };
11251        let mut t = task();
11252        t.start(state.id.clone());
11253        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11254
11255        assert_eq!(t.status, TaskStatus::Held);
11256        assert_eq!(
11257            t.hold_reason.as_deref(),
11258            Some("run ended agent-verified no-op"),
11259            "nothing to append when the question was already answered or never asked"
11260        );
11261    }
11262
11263    #[test]
11264    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11265        crate::run::pin_test_home();
11266
11267        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
11268        // regression prose instead of valid structured evidence.
11269        let mut bad = run_state(RunStatus::VerifiedNoop);
11270        let mut c = candidate(
11271            'A',
11272            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11273            true,
11274            None,
11275        );
11276        c.verified_noop = Some("Not established.".to_owned());
11277        bad.candidates = vec![c];
11278
11279        let mut t = task();
11280        t.start(bad.id.clone());
11281        let verdict = Verdict {
11282            status: RunStatus::VerifiedNoop,
11283            left_pr: false,
11284            quota_hit: true,
11285            parked: false,
11286            no_viable_candidates: true,
11287        };
11288        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11289        assert_eq!(
11290            t.status,
11291            TaskStatus::Failed,
11292            "inconsistent verified_noop must retry as Failed when attempts remain"
11293        );
11294        assert_eq!(t.attempts, 1);
11295        assert_eq!(
11296            t.last_error.as_deref(),
11297            Some("no-change result lacks verified evidence")
11298        );
11299        assert!(t.hold_reason.is_none());
11300
11301        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
11302        // attempts exhausted holds as `failed`, never `verified_noop`, and
11303        // never auto-closes to `Done`.
11304        let mut t_exhausted = task();
11305        t_exhausted.start(bad.id.clone());
11306        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11307        assert_eq!(t_exhausted.status, TaskStatus::Held);
11308        assert_eq!(t_exhausted.attempts, 1);
11309        assert_eq!(
11310            t_exhausted
11311                .hold_notice_cause
11312                .as_ref()
11313                .map(|c| c.stage.as_str()),
11314            Some("failed"),
11315            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11316        );
11317        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11318        assert!(
11319            !diag.contains("agent-verified no-op"),
11320            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11321        );
11322        assert!(diag.contains("Not established"), "{diag}");
11323    }
11324
11325    #[test]
11326    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11327        let mut state = verified_noop_run_state();
11328        let summary = state.candidates[0].summary.clone();
11329        state.candidates[0].summary = "Already satisfied.".to_owned();
11330        assert!(state.all_candidates_verified_noop());
11331
11332        state.candidates[0].summary = summary;
11333        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11334        assert!(!state.all_candidates_verified_noop());
11335    }
11336
11337    #[test]
11338    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11339        crate::run::pin_test_home();
11340        let mut first = run_state(RunStatus::Blocked);
11341        first.id = "20260101-000000-sup1".to_owned();
11342        first.save().unwrap();
11343        let mut second = run_state(RunStatus::Merged);
11344        second.id = "20260101-000000-sup2".to_owned();
11345        second.save().unwrap();
11346
11347        let mut t = task();
11348        t.runs = vec![first.id.clone(), second.id.clone()];
11349        t.status = TaskStatus::Done;
11350
11351        supersede_prior_runs(&t, &crate::run::home());
11352
11353        assert_eq!(
11354            RunState::load(&first.id).unwrap().status,
11355            RunStatus::Superseded,
11356            "the first attempt's Blocked no longer needs anyone's attention"
11357        );
11358        assert_eq!(
11359            RunState::load(&second.id).unwrap().status,
11360            RunStatus::Merged,
11361            "the run that actually succeeded is left exactly as it was"
11362        );
11363    }
11364
11365    #[test]
11366    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11367        // `is_working_on` alone only proves a *daemon* claim; a `magi run
11368        // --resume` invoked by hand outside the daemon never touches
11369        // `daemon.json` at all, so it would look identical to a genuinely
11370        // idle run without also consulting `RunState::liveness`, which reads
11371        // this run's own recorded `driver_pid` instead.
11372        crate::run::pin_test_home();
11373        let mut first = run_state(RunStatus::Blocked);
11374        first.id = "20260101-000000-sup9".to_owned();
11375        // This test process's own pid: guaranteed alive without needing a
11376        // real second process or daemon.
11377        first.driver_pid = Some(std::process::id());
11378        first.driver_started_at = Some(
11379            crate::proc::process_started_at(std::process::id())
11380                .expect("this test process's own start time must be queryable"),
11381        );
11382        first.save().unwrap();
11383        let mut second = run_state(RunStatus::Merged);
11384        second.id = "20260101-000000-supa".to_owned();
11385        second.save().unwrap();
11386
11387        let mut t = task();
11388        t.runs = vec![first.id.clone(), second.id.clone()];
11389        t.status = TaskStatus::Done;
11390
11391        supersede_prior_runs(&t, &crate::run::home());
11392
11393        assert_eq!(
11394            RunState::load(&first.id).unwrap().status,
11395            RunStatus::Blocked,
11396            "a live driver_pid means something is still actually working this run, \
11397             even though no daemon claims it - rewriting under it would just be \
11398             undone the next time that process saves"
11399        );
11400    }
11401
11402    #[test]
11403    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11404        // The first resweep must skip a still-live attempt exactly like
11405        // `supersede_prior_runs` itself does; a later resweep, once that
11406        // process is no longer actually driving it, is what closes the gap
11407        // `supersede_prior_runs` alone leaves - a task only ever reaches
11408        // `Done` once, so nothing else would ever look at this run again.
11409        let dir = tempfile::tempdir().unwrap();
11410        let home = dir.path().to_path_buf();
11411        let queue = Queue::at(dir.path().join("queue"));
11412
11413        let mut first = run_state(RunStatus::Blocked);
11414        first.id = "20260101-000000-supd".to_owned();
11415        first.driver_pid = Some(std::process::id());
11416        first.driver_started_at = Some(
11417            crate::proc::process_started_at(std::process::id())
11418                .expect("this test process's own start time must be queryable"),
11419        );
11420        first.save_under(&home).unwrap();
11421        let mut second = run_state(RunStatus::Merged);
11422        second.id = "20260101-000000-supe".to_owned();
11423        second.save_under(&home).unwrap();
11424
11425        let mut t = task();
11426        t.runs = vec![first.id.clone(), second.id.clone()];
11427        t.status = TaskStatus::Done;
11428        queue.put(&mut t).unwrap();
11429
11430        resweep_superseded_attempts(&queue, &home);
11431        assert_eq!(
11432            RunState::load_under(&first.id, &home).unwrap().status,
11433            RunStatus::Blocked,
11434            "still live on the first pass, so still untouched"
11435        );
11436
11437        // Stand in for the manual process no longer being the one driving
11438        // this run: same pid (this test process really is still alive), but
11439        // an identity marker that no longer matches it - see
11440        // `RunState::liveness`'s own doc for why a mismatched
11441        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
11442        let mut stale = RunState::load_under(&first.id, &home).unwrap();
11443        stale.driver_started_at = Some("1".to_owned());
11444        stale.save_under(&home).unwrap();
11445
11446        resweep_superseded_attempts(&queue, &home);
11447        assert_eq!(
11448            RunState::load_under(&first.id, &home).unwrap().status,
11449            RunStatus::Superseded,
11450            "the second pass catches up what the first one correctly skipped"
11451        );
11452    }
11453
11454    #[test]
11455    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11456        crate::run::pin_test_home();
11457        let mut first = run_state(RunStatus::Blocked);
11458        first.id = "20260101-000000-sup3".to_owned();
11459        first.save().unwrap();
11460        let mut second = run_state(RunStatus::Blocked);
11461        second.id = "20260101-000000-sup4".to_owned();
11462        second.save().unwrap();
11463
11464        let mut t = task();
11465        t.runs = vec![first.id.clone(), second.id.clone()];
11466        // Still retrying: nothing about this task's story is settled yet, so
11467        // neither Blocked run may be relabelled, even though a later attempt
11468        // already exists.
11469        t.status = TaskStatus::Failed;
11470
11471        supersede_prior_runs(&t, &crate::run::home());
11472
11473        assert_eq!(
11474            RunState::load(&first.id).unwrap().status,
11475            RunStatus::Blocked
11476        );
11477        assert_eq!(
11478            RunState::load(&second.id).unwrap().status,
11479            RunStatus::Blocked
11480        );
11481    }
11482
11483    #[test]
11484    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11485        // `magi task done` (or the API's equivalent) can close a task with no
11486        // run of its own ever having succeeded - there is nothing here that
11487        // counts as "the attempt that finished it", so nothing is rewritten.
11488        crate::run::pin_test_home();
11489        let mut first = run_state(RunStatus::Blocked);
11490        first.id = "20260101-000000-sup5".to_owned();
11491        first.save().unwrap();
11492
11493        let mut t = task();
11494        t.runs = vec![first.id.clone()];
11495        t.status = TaskStatus::Done;
11496
11497        supersede_prior_runs(&t, &crate::run::home());
11498
11499        assert_eq!(
11500            RunState::load(&first.id).unwrap().status,
11501            RunStatus::Blocked,
11502            "a single-attempt task has no earlier run to supersede"
11503        );
11504    }
11505
11506    #[test]
11507    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11508        for status in [
11509            RunStatus::Blocked,
11510            RunStatus::Stalled,
11511            RunStatus::Failed,
11512            RunStatus::Ready,
11513            RunStatus::Merged,
11514        ] {
11515            let dir = tempfile::tempdir().unwrap();
11516            let home = dir.path();
11517            let mut first = run_state(RunStatus::Blocked);
11518            first.id = "20260101-000000-supb".to_owned();
11519            first.save_under(home).unwrap();
11520            let mut second = run_state(status);
11521            second.id = "20260101-000000-supc".to_owned();
11522            second.save_under(home).unwrap();
11523
11524            let mut t = task();
11525            t.runs = vec![first.id.clone(), second.id.clone()];
11526            t.hold_manual(Some("Unmerged work remains".into()));
11527            let mut context = CompletionContext::new(
11528                CompletionActor::Cli,
11529                Some("Discard the unmerged attempts".into()),
11530                home,
11531                &t,
11532            );
11533            context.discard = true;
11534            t.succeed(context);
11535            assert_eq!(t.completion_history.len(), 1);
11536
11537            supersede_prior_runs(&t, home);
11538
11539            assert_eq!(
11540                RunState::load_under(&first.id, home).unwrap().status,
11541                RunStatus::Blocked,
11542                "an audited manual close is not proof the earlier work landed"
11543            );
11544            assert_eq!(
11545                RunState::load_under(&second.id, home).unwrap().status,
11546                status,
11547                "the latest attempt retains its actual outcome"
11548            );
11549        }
11550    }
11551
11552    #[test]
11553    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11554        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
11555        // to look" - `Failed` and `VerifiedNoop` are already their own
11556        // terminal answers and must not be relabelled into a third one.
11557        crate::run::pin_test_home();
11558        let mut failed = run_state(RunStatus::Failed);
11559        failed.id = "20260101-000000-sup6".to_owned();
11560        failed.save().unwrap();
11561        let mut noop = run_state(RunStatus::VerifiedNoop);
11562        noop.id = "20260101-000000-sup7".to_owned();
11563        noop.save().unwrap();
11564        let mut winner = run_state(RunStatus::Ready);
11565        winner.id = "20260101-000000-sup8".to_owned();
11566        winner.save().unwrap();
11567
11568        let mut t = task();
11569        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11570        t.status = TaskStatus::Done;
11571
11572        supersede_prior_runs(&t, &crate::run::home());
11573
11574        assert_eq!(
11575            RunState::load(&failed.id).unwrap().status,
11576            RunStatus::Failed
11577        );
11578        assert_eq!(
11579            RunState::load(&noop.id).unwrap().status,
11580            RunStatus::VerifiedNoop
11581        );
11582    }
11583
11584    fn approval_question(run: &str) -> ask::Question {
11585        ask::Question::new(
11586            run.to_owned(),
11587            land::APPROVAL_NODE.to_owned(),
11588            "land".to_owned(),
11589            "merge?".to_owned(),
11590            String::new(),
11591            vec!["merge".to_owned(), "hold".to_owned()],
11592        )
11593    }
11594
11595    #[test]
11596    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11597        crate::run::pin_test_home();
11598        let mut state = run_state(RunStatus::Landing);
11599        state.id = "20260101-000000-fre1".to_owned();
11600        state.parked = true;
11601        state.save().unwrap();
11602        ask::Questions::open()
11603            .put(&mut approval_question(&state.id))
11604            .unwrap();
11605
11606        let mut t = task();
11607        t.runs.push(state.id.clone());
11608        assert_eq!(
11609            land_resume_state(&t),
11610            LandResume::StillWaiting,
11611            "nobody has answered and the timeout has not passed"
11612        );
11613    }
11614
11615    #[test]
11616    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11617        crate::run::pin_test_home();
11618        let mut state = run_state(RunStatus::Gating);
11619        state.id = "20260101-000000-gt01".to_owned();
11620        state.parked = true;
11621        state.config.graph.answer_timeout = 60;
11622        state.github_text = Some(crate::run::GithubTextAsk {
11623            rewrite: None,
11624            fingerprint: "f".into(),
11625            title: true,
11626            body: false,
11627            categories: vec!["title-language".into()],
11628            question: None,
11629            asks: 1,
11630            resolved: false,
11631            chosen_title: None,
11632            choice: None,
11633            publication: None,
11634        });
11635        state.save().unwrap();
11636        let store = ask::Questions::open();
11637        let mut q = ask::Question::new(
11638            state.id.clone(),
11639            crate::github_text::ASK_NODE.to_owned(),
11640            crate::github_text::ASK_SEAT.to_owned(),
11641            "s".into(),
11642            String::new(),
11643            vec!["use fallback".into()],
11644        );
11645        store.put(&mut q).unwrap();
11646        let mut t = task();
11647        t.runs.push(state.id.clone());
11648        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11649        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11650        store.put(&mut q).unwrap();
11651        assert_eq!(land_resume_state(&t), LandResume::Ready);
11652        assert!(!store.get(&q.id).unwrap().status.open());
11653        // Once decided, a parked run is an ordinary candidate again.
11654        state.github_text.as_mut().unwrap().resolved = true;
11655        state.save().unwrap();
11656        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11657    }
11658
11659    #[test]
11660    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11661        // `ask::ask_and_wait`'s own deadline used to retire a question
11662        // nobody answered; land's approval bypasses that wait (see
11663        // `land::approval_gate`), so this is now the only place
11664        // `graph.answer_timeout` is enforced for a land approval at all.
11665        crate::run::pin_test_home();
11666        let mut state = run_state(RunStatus::Landing);
11667        state.id = "20260101-000000-exp1".to_owned();
11668        state.parked = true;
11669        state.config.graph.answer_timeout = 60;
11670        state.save().unwrap();
11671
11672        let store = ask::Questions::open();
11673        let mut q = approval_question(&state.id);
11674        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11675        store.put(&mut q).unwrap();
11676
11677        let mut t = task();
11678        t.runs.push(state.id.clone());
11679        assert_eq!(
11680            land_resume_state(&t),
11681            LandResume::Ready,
11682            "an expired question must not be waited on forever"
11683        );
11684
11685        let after = store.get(&q.id).unwrap();
11686        assert!(
11687            !after.status.open(),
11688            "the question is abandoned, not silently ignored"
11689        );
11690        assert!(
11691            after.resolution().is_none(),
11692            "an abandoned question is not read as a decision"
11693        );
11694    }
11695
11696    #[test]
11697    fn reclaim_settles_a_running_task_against_its_last_run() {
11698        let mut t = task();
11699        t.start("20260904-000000-4043".to_owned());
11700        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11701        assert_eq!(
11702            t.status,
11703            TaskStatus::Done,
11704            "a run that actually finished must not stay `running` forever"
11705        );
11706    }
11707
11708    #[test]
11709    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11710        let dir = tempfile::tempdir().unwrap();
11711        let queue = Queue::at(dir.path().join("queue"));
11712        let mut task = task();
11713        let mut run = run_state(RunStatus::Blocked);
11714        run.reserve_under(dir.path()).unwrap();
11715        run.driver_exited = true;
11716        run.save_under(dir.path()).unwrap();
11717        queue.put(&mut task).unwrap();
11718        let stale = task.clone();
11719        task.resume_override = Some(crate::queue::OperatorResume {
11720            question_id: "pending-resume".into(),
11721            at: Timestamp::now(),
11722            conductor_rehold: None,
11723            forced: true,
11724            pinned_run: Some(run.id.clone()),
11725        });
11726        task.start(run.id.clone());
11727        queue.put(&mut task).unwrap();
11728        // Discard every in-memory handoff, as a worker death before execute does.
11729        let mut recovered = queue.get(&task.id).unwrap();
11730        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11731        reclaim(&mut recovered, Some(disk), 2, "en");
11732        queue.put(&mut recovered).unwrap();
11733        assert!(recovered.resume_override.is_none());
11734        assert_eq!(
11735            recovered.dispatched_resumes.get("pending-resume"),
11736            Some(&run.id)
11737        );
11738        let mut stale = stale;
11739        queue.put(&mut stale).unwrap();
11740        assert_eq!(
11741            stale.dispatched_resumes, recovered.dispatched_resumes,
11742            "a stale task writer cannot erase dispatch ownership"
11743        );
11744        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11745        assert!(resumed.decision_starts.is_empty());
11746        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11747        assert!(
11748            resumed.decision_starts.is_empty(),
11749            "handoff is not execution proof"
11750        );
11751        resumed.begin_pass();
11752        resumed.save_under(dir.path()).unwrap();
11753        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11754        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11755        disk.carry_dispatched_resumes(&recovered);
11756        disk.begin_pass();
11757        assert_eq!(
11758            disk.decision_starts.get("pending-resume"),
11759            Some(&0),
11760            "later execution must preserve the original pass receipt"
11761        );
11762    }
11763
11764    #[test]
11765    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11766        let mut t = task();
11767        t.start("20260904-000000-4043".to_owned());
11768        t.last_error = Some("earlier trouble".to_owned());
11769        let mut state = run_state(RunStatus::Judging);
11770        state.parked = true;
11771        reclaim(&mut t, Some(state), 1, "en");
11772        assert_eq!(t.status, TaskStatus::Parked);
11773        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11774        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11775        assert!(t.park_reason.is_some());
11776        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11777        assert!(!t.fresh_start);
11778        assert!(t.status.runnable());
11779    }
11780
11781    #[test]
11782    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11783        let mut t = task();
11784        t.start("20260904-000000-4043".to_owned());
11785        t.last_error = Some("earlier trouble".to_owned());
11786        settle(
11787            &mut t,
11788            Verdict {
11789                status: RunStatus::Judging,
11790                left_pr: false,
11791                quota_hit: false,
11792                parked: true,
11793                no_viable_candidates: false,
11794            },
11795            "parked after `judging`",
11796            1,
11797        );
11798        assert_eq!(t.status, TaskStatus::Parked);
11799        assert_eq!(t.attempts, 0);
11800        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11801        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11802        assert_eq!(t.schema, crate::queue::SCHEMA);
11803        assert!(
11804            crate::notices::task_held(&t).is_none(),
11805            "a park is not news"
11806        );
11807        t.start("20260904-000000-4043".to_owned());
11808        assert_eq!(t.park_reason, None);
11809    }
11810
11811    #[test]
11812    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11813        // A blocked run with attempts left goes back to `Failed`, exactly as
11814        // it would from `attempt` itself - `reclaim` must not invent a second
11815        // policy for a task a daemon merely stopped without reporting.
11816        let mut t = task();
11817        t.start("20260904-000000-4043".to_owned());
11818        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11819        assert_eq!(t.status, TaskStatus::Failed);
11820        assert!(t.status.runnable());
11821    }
11822
11823    #[test]
11824    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11825        let mut t = task();
11826        t.start("20260904-000000-4043".to_owned());
11827        assert_eq!(t.attempts, 1);
11828        let mut run = run_state(RunStatus::Implementing);
11829        run.id = "20260904-000000-4043".to_owned();
11830        run.begin_pass();
11831        let cause = crate::run::ParkCause::Upgrade {
11832            from: "0.121.0".to_owned(),
11833            to: Some("0.121.1".to_owned()),
11834        };
11835        run.end_pass_parked(cause.clone());
11836        run.parked = true;
11837        let verdict = Verdict {
11838            status: run.status,
11839            left_pr: false,
11840            quota_hit: false,
11841            parked: true,
11842            no_viable_candidates: false,
11843        };
11844        // A crash after the checkpoint but before queue settlement must
11845        // recover exactly the same scheduling evidence and refund.
11846        let mut orphan = t.clone();
11847        reclaim(&mut orphan, Some(run.clone()), 2, "en");
11848        assert_eq!(orphan.status, TaskStatus::Parked);
11849        assert_eq!(orphan.attempts, 0);
11850        assert_eq!(
11851            orphan.upgrade_resume_key(),
11852            Some((run.passes[0].started_at, orphan.id.as_str()))
11853        );
11854        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
11855        assert_eq!(t.attempts, 0);
11856        assert_eq!(t.passes.len(), 1);
11857        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11858        assert_eq!(t.passes[0].parked, Some(cause));
11859        assert_eq!(t.passes[0].pass_index, 0);
11860        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
11861        assert!(t.upgrade_resume_key().is_some());
11862
11863        // A resumed pass that then fails spends its attempt, and the earlier
11864        // pass's entry is untouched.
11865        t.start("20260904-000000-4043".to_owned());
11866        run.begin_pass();
11867        run.status = RunStatus::Failed;
11868        let verdict = Verdict {
11869            status: RunStatus::Failed,
11870            left_pr: false,
11871            quota_hit: false,
11872            parked: false,
11873            no_viable_candidates: false,
11874        };
11875        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
11876        assert_eq!(t.passes.len(), 2);
11877        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11878        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
11879        assert_eq!(t.passes[1].pass_index, 1);
11880        assert_eq!(t.attempts, 1);
11881    }
11882
11883    #[test]
11884    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
11885        let mut t = task();
11886        t.start("20260904-000000-4043".to_owned());
11887        reclaim(&mut t, None, 2, "en");
11888        assert_eq!(t.status, TaskStatus::Held);
11889        assert!(
11890            t.last_error
11891                .as_deref()
11892                .is_some_and(|e| e.contains("running")),
11893            "the operator needs to know why this task was held"
11894        );
11895    }
11896
11897    #[test]
11898    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
11899        let dir = tempfile::tempdir().unwrap();
11900        let queue = Queue::at(dir.path().to_path_buf());
11901        let mut task = task();
11902        let run = "20261124-000000-dead";
11903        task.link_run(run);
11904        task.attempts = 2;
11905        task.status = TaskStatus::Running;
11906        task.sync_only = Some(crate::base_sync_only::Request {
11907            run: run.into(),
11908            at: Timestamp::now(),
11909        });
11910        queue.put(&mut task).unwrap();
11911        assert_eq!(
11912            reclaim_orphaned_running(&queue, 3, &Default::default()),
11913            vec![task.id.clone()]
11914        );
11915        let saved = queue.get(&task.id).unwrap();
11916        assert_eq!(saved.status, TaskStatus::Held);
11917        assert_eq!(saved.attempts, 2);
11918        assert_eq!(saved.execution_runs(), [run]);
11919        assert!(
11920            saved
11921                .last_error
11922                .unwrap()
11923                .contains("verification was not allowed")
11924        );
11925        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
11926    }
11927
11928    #[test]
11929    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
11930        use crate::base_sync_only::{Outcome, Pass, Request};
11931
11932        let mut state = run_state(RunStatus::Blocked);
11933        let mut task = task();
11934        let request = Request {
11935            run: state.id.clone(),
11936            at: Timestamp::now(),
11937        };
11938        task.start(state.id.clone());
11939        task.sync_only = Some(request.clone());
11940        // Dedicated dispatch saves Running with the pre-pass attempt count.
11941        task.attempts = 2;
11942        let mut pass = Pass::new(request, &state);
11943        pass.result = Outcome::AlreadyCurrent;
11944        state.sync_only_passes.push(pass);
11945        state.begin_pass();
11946
11947        reclaim(&mut task, Some(state), 3, "en");
11948
11949        assert_eq!(task.status, TaskStatus::Held);
11950        assert_eq!(task.attempts, 2);
11951        assert!(task.sync_only.is_none());
11952        let detail = task.hold_reason.unwrap();
11953        assert!(detail.contains("HEAD already contains the base"));
11954        assert!(detail.contains("verification was not allowed"));
11955    }
11956
11957    #[test]
11958    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
11959        let dir = tempfile::tempdir().unwrap();
11960        let queue = Queue::at(dir.path().to_path_buf());
11961
11962        // No run recorded, so this never has to touch `RunState::load`.
11963        let mut orphaned = task();
11964        orphaned.id = "20260904-000000-orph".to_owned();
11965        orphaned.status = TaskStatus::Running;
11966        orphaned.attempts = 1;
11967        queue.put(&mut orphaned).unwrap();
11968
11969        let mut alive = task();
11970        alive.id = "20260904-000000-live".to_owned();
11971        alive.status = TaskStatus::Running;
11972        alive.attempts = 1;
11973        queue.put(&mut alive).unwrap();
11974        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
11975
11976        let mut queued = task();
11977        queued.id = "20260904-000000-wait".to_owned();
11978        queue.put(&mut queued).unwrap();
11979
11980        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
11981        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
11982
11983        assert_eq!(
11984            queue.get(&orphaned.id).unwrap().status,
11985            TaskStatus::Held,
11986            "nothing was driving it and there was no run to recover"
11987        );
11988        assert_eq!(
11989            queue.get(&alive.id).unwrap().status,
11990            TaskStatus::Running,
11991            "a live claim must protect the task it belongs to"
11992        );
11993        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
11994    }
11995
11996    /// Read a run.json back from an explicit `home`, the same way
11997    /// `reclaim_abandoned_runs` itself does - never through the
11998    /// process-global `RunState::load`, which this test's own `home` (an
11999    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
12000    /// use at all.
12001    fn read_run_under(home: &Path, id: &str) -> RunState {
12002        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12003        serde_json::from_str(&body).unwrap()
12004    }
12005
12006    #[test]
12007    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12008        let dir = tempfile::tempdir().unwrap();
12009        let home = dir.path().to_path_buf();
12010        let now = Timestamp::now();
12011        let overrun_seat = || crate::run::ActiveSeat {
12012            node: "implement".to_owned(),
12013            started_at: now - jiff::SignedDuration::new(21_000, 0),
12014            timeout_secs: 3_600,
12015            attempt: 0,
12016            task: None,
12017            command: None,
12018            index: None,
12019            total: None,
12020        };
12021
12022        let mut dead = run_state(RunStatus::Implementing);
12023        dead.id = "20260101-000000-dead".to_owned();
12024        dead.active.insert("impl-A".to_owned(), overrun_seat());
12025        // A `driver_pid` the injected query below confirms gone outright —
12026        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
12027        dead.driver_pid = Some(4242);
12028        dead.save_under(&home).unwrap();
12029
12030        // Same shape, but a live daemon's heartbeat names it: must be left
12031        // exactly alone, however far past its own timeout the seat sits.
12032        let mut alive = run_state(RunStatus::Implementing);
12033        alive.id = "20260101-000000-aliv".to_owned();
12034        alive.active.insert("impl-A".to_owned(), overrun_seat());
12035        alive.save_under(&home).unwrap();
12036        let mut status = Status::new();
12037        status.current = vec![Current {
12038            worker: None,
12039            task: "20260101-000000-task".to_owned(),
12040            run: alive.id.clone(),
12041        }];
12042        write_status_to(&home.join("daemon.json"), &status).unwrap();
12043
12044        // The abandoned seat left an open question behind: nobody is left to
12045        // read an answer once the run is failed, and this must not wait for
12046        // some later daemon startup's own sweep to notice that.
12047        let questions = Questions::at(home.join("questions"));
12048        let mut q = ask::Question::new(
12049            dead.id.clone(),
12050            "implement".to_owned(),
12051            "impl-A".to_owned(),
12052            "Which storage backend?".to_owned(),
12053            String::new(),
12054            vec!["SQLite".to_owned(), "Redis".to_owned()],
12055        );
12056        questions.put(&mut q).unwrap();
12057
12058        let abandoned = reclaim_abandoned_runs_with(
12059            &home,
12060            now,
12061            |pid| if pid == 4242 { Some(false) } else { None },
12062            |_| panic!("a query answering Dead outright needs no identity corroboration"),
12063        );
12064        assert_eq!(abandoned, vec![dead.id.clone()]);
12065
12066        let reloaded = read_run_under(&home, &dead.id);
12067        assert_eq!(reloaded.status, RunStatus::Failed);
12068        assert!(reloaded.active.is_empty());
12069        assert!(
12070            !questions.get(&q.id).unwrap().status.open(),
12071            "the failed run's own open question must be settled in the same pass"
12072        );
12073
12074        let still_alive = read_run_under(&home, &alive.id);
12075        assert_eq!(
12076            still_alive.status,
12077            RunStatus::Implementing,
12078            "a live daemon's claim protects it"
12079        );
12080        assert!(!still_alive.active.is_empty());
12081    }
12082
12083    /// The exact shape a review round flagged as broken: `magi serve` running
12084    /// in this same `home` scans *every* run on disk, including a manual
12085    /// `magi review` / `magi run` this daemon never started and that
12086    /// therefore claims no heartbeat of its own. Before this scan asked
12087    /// `liveness` rather than just `is_working_on`, a manual run whose active
12088    /// seat merely ran a little past its own timeout — the CLI finishing up,
12089    /// its result still being collected — got wiped and failed by a daemon
12090    /// that had nothing to do with it, out from under a process that was
12091    /// still very much running.
12092    #[test]
12093    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12094        let dir = tempfile::tempdir().unwrap();
12095        let home = dir.path().to_path_buf();
12096        let now = Timestamp::now();
12097
12098        let mut manual = run_state(RunStatus::Reviewing);
12099        manual.id = "20260101-000000-manl".to_owned();
12100        manual.active.insert(
12101            "review-1".to_owned(),
12102            crate::run::ActiveSeat {
12103                node: "review".to_owned(),
12104                started_at: now - jiff::SignedDuration::new(21_000, 0),
12105                timeout_secs: 3_600,
12106                attempt: 0,
12107                task: None,
12108                command: None,
12109                index: None,
12110                total: None,
12111            },
12112        );
12113        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
12114        // but a real, still-running process: `liveness` must corroborate this
12115        // as `Live`, not read the missing daemon claim as death.
12116        manual.driver_pid = Some(4242);
12117        manual.driver_started_at = Some("1790000000".to_owned());
12118        manual.save_under(&home).unwrap();
12119
12120        let abandoned = reclaim_abandoned_runs_with(
12121            &home,
12122            now,
12123            |pid| if pid == 4242 { Some(true) } else { None },
12124            |pid| {
12125                if pid == 4242 {
12126                    Some("1790000000".to_owned())
12127                } else {
12128                    None
12129                }
12130            },
12131        );
12132        assert!(
12133            abandoned.is_empty(),
12134            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12135        );
12136
12137        let reloaded = read_run_under(&home, &manual.id);
12138        assert_eq!(reloaded.status, RunStatus::Reviewing);
12139        assert!(!reloaded.active.is_empty());
12140    }
12141
12142    #[test]
12143    fn an_already_claimed_task_is_skipped_rather_than_failed() {
12144        let dir = tempfile::tempdir().unwrap();
12145        let queue = Queue::at(dir.path().to_path_buf());
12146        let mut only = task();
12147        queue.put(&mut only).unwrap();
12148
12149        let _elsewhere = queue.claim(&only.id).unwrap();
12150        let candidates = runnable(&queue);
12151        assert_eq!(candidates.len(), 1, "the task is still runnable");
12152        assert!(
12153            queue.claim(&candidates[0].id).is_err(),
12154            "the loop cannot take a claim somebody else holds"
12155        );
12156
12157        let after = queue.get(&only.id).unwrap();
12158        assert_eq!(after.status, TaskStatus::Queued);
12159        assert_eq!(
12160            after.attempts, 0,
12161            "losing the race is not an attempt at the task"
12162        );
12163        assert_eq!(after.last_error, None);
12164    }
12165
12166    #[test]
12167    fn the_status_file_round_trips_and_its_heartbeat_advances() {
12168        let dir = tempfile::tempdir().unwrap();
12169        let path = dir.path().join("daemon.json");
12170
12171        let mut status = Status::new();
12172        status.idle = false;
12173        status.completed = 7;
12174        status.current = vec![Current {
12175            worker: None,
12176            task: "20260902-000000-t111".to_owned(),
12177            run: "20260902-000001-r111".to_owned(),
12178        }];
12179        write_status_to(&path, &status).unwrap();
12180        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12181        assert_eq!(first.schema, SCHEMA);
12182        assert_eq!(first.pid, std::process::id());
12183        assert!(!first.idle);
12184        assert_eq!(first.completed, 7);
12185        assert_eq!(first.current, status.current);
12186        assert!(
12187            !path.with_extension("json.tmp").exists(),
12188            "the temp file is renamed, not left behind"
12189        );
12190
12191        std::thread::sleep(Duration::from_millis(5));
12192        status.updated_at = Timestamp::now();
12193        status.polls = 3;
12194        write_status_to(&path, &status).unwrap();
12195        let second: Status =
12196            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12197        assert!(
12198            second.updated_at > first.updated_at,
12199            "a reader can only detect staleness if the heartbeat moves"
12200        );
12201        assert_eq!(
12202            second.started_at, first.started_at,
12203            "the start time is not a heartbeat"
12204        );
12205        assert_eq!(second.polls, 3);
12206    }
12207
12208    #[test]
12209    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12210        let dir = tempfile::tempdir().unwrap();
12211
12212        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12213
12214        let mut status = Status::new();
12215        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12216        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12217        let stale = read_status(dir.path()).unwrap();
12218        assert!(
12219            !stale.running(Timestamp::now()),
12220            "a minute without a heartbeat is a dead daemon, not a busy one"
12221        );
12222        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12223
12224        status.updated_at = Timestamp::now();
12225        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12226        let fresh = read_status(dir.path()).unwrap();
12227        assert!(fresh.running(Timestamp::now()));
12228    }
12229
12230    #[test]
12231    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12232        let dir = tempfile::tempdir().unwrap();
12233        let now = Timestamp::now();
12234        let mine = "20260903-080619-01c2";
12235
12236        assert!(
12237            !is_working_on(dir.path(), mine, now),
12238            "no status file means nobody is working on anything"
12239        );
12240
12241        let mut status = Status::new();
12242        status.current = vec![Current {
12243            worker: None,
12244            task: "20260903-080340-0167".to_owned(),
12245            run: mine.to_owned(),
12246        }];
12247        status.updated_at = now;
12248        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12249        assert!(is_working_on(dir.path(), mine, now));
12250        assert!(
12251            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12252            "a daemon busy with one run is not working on another"
12253        );
12254
12255        // A killed daemon stops writing heartbeats but leaves the file behind
12256        // naming the run it died in. That run must not be undeletable forever.
12257        status.updated_at = now - jiff::SignedDuration::from_secs(600);
12258        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12259        assert!(
12260            !is_working_on(dir.path(), mine, now),
12261            "a stale heartbeat is a dead daemon, so its run is a leftover"
12262        );
12263    }
12264
12265    #[test]
12266    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12267        let dir = tempfile::tempdir().unwrap();
12268        let now = Timestamp::now();
12269
12270        assert!(
12271            !is_working_on_short(dir.path(), "01c2", now),
12272            "no status file means nobody is working on anything"
12273        );
12274
12275        let mut status = Status::new();
12276        status.current = vec![Current {
12277            worker: None,
12278            task: "20260903-080340-0167".to_owned(),
12279            run: "20260903-080619-01c2".to_owned(),
12280        }];
12281        status.updated_at = now;
12282        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12283        assert!(
12284            is_working_on_short(dir.path(), "01c2", now),
12285            "the run's short id is the last block of its full id"
12286        );
12287        assert!(
12288            !is_working_on_short(dir.path(), "3cbf", now),
12289            "a daemon busy with one worktree bay is not working on another"
12290        );
12291    }
12292
12293    #[test]
12294    fn a_newer_status_file_still_yields_a_reading() {
12295        let dir = tempfile::tempdir().unwrap();
12296        // A field this build has never heard of must not turn the reading into
12297        // nothing at all; that is the whole reason the reader is permissive.
12298        std::fs::write(
12299            dir.path().join("daemon.json"),
12300            serde_json::json!({
12301                "schema": 2,
12302                "updated_at": Timestamp::now().to_string(),
12303                "idle": true,
12304                "surprise": { "nested": [1, 2, 3] },
12305            })
12306            .to_string(),
12307        )
12308        .unwrap();
12309
12310        let reading = read_status(dir.path()).expect("a forward-compatible read");
12311        assert!(reading.running(Timestamp::now()));
12312        assert!(reading.idle);
12313        assert!(reading.current.is_empty());
12314    }
12315
12316    #[test]
12317    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12318        // A daemon started before `current` became a list keeps writing this
12319        // shape on every heartbeat until it is restarted. A rolling upgrade
12320        // - a newer `magi web` or `magi doctor` reading an older `magi
12321        // serve`'s heartbeat - must still see the run it is on, not "no
12322        // daemon" from a type mismatch failing the whole struct.
12323        let dir = tempfile::tempdir().unwrap();
12324        std::fs::write(
12325            dir.path().join("daemon.json"),
12326            serde_json::json!({
12327                "schema": 1,
12328                "pid": 4242,
12329                "updated_at": Timestamp::now().to_string(),
12330                "idle": false,
12331                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12332                "completed": 3,
12333                "polls": 9,
12334            })
12335            .to_string(),
12336        )
12337        .unwrap();
12338
12339        let reading = read_status(dir.path()).expect("an older shape must still parse");
12340        assert!(reading.running(Timestamp::now()));
12341        assert_eq!(
12342            reading.current,
12343            vec![Current {
12344                worker: None,
12345                task: "20260902-140501-aaaa".to_owned(),
12346                run: "20260902-140502-bbbb".to_owned(),
12347            }]
12348        );
12349    }
12350
12351    #[test]
12352    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12353        let dir = tempfile::tempdir().unwrap();
12354        std::fs::write(
12355            dir.path().join("daemon.json"),
12356            serde_json::json!({
12357                "schema": 1,
12358                "updated_at": Timestamp::now().to_string(),
12359                "idle": true,
12360                "current": null,
12361            })
12362            .to_string(),
12363        )
12364        .unwrap();
12365        let with_null = read_status(dir.path()).expect("null must still parse");
12366        assert!(with_null.current.is_empty());
12367
12368        std::fs::write(
12369            dir.path().join("daemon.json"),
12370            serde_json::json!({
12371                "schema": 1,
12372                "updated_at": Timestamp::now().to_string(),
12373                "idle": true,
12374            })
12375            .to_string(),
12376        )
12377        .unwrap();
12378        let absent = read_status(dir.path()).expect("a missing field must still parse");
12379        assert!(absent.current.is_empty());
12380    }
12381
12382    #[test]
12383    fn a_task_without_a_repository_runs_in_the_daemons_default() {
12384        let fallback = Path::new("/default");
12385        let mut blank = task();
12386        blank.repo = PathBuf::new();
12387        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12388        let mut dot = task();
12389        dot.repo = PathBuf::from(".");
12390        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12391        assert_eq!(
12392            repo_for(&task(), fallback),
12393            PathBuf::from("/repo"),
12394            "a task that names a repository keeps it"
12395        );
12396    }
12397
12398    #[test]
12399    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12400        let dir = tempfile::tempdir().unwrap();
12401        let repo = dir.path();
12402        let path = repo.join("explicit.toml");
12403        std::fs::write(
12404            &path,
12405            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12406        )
12407        .unwrap();
12408        let opts = Opts {
12409            config: Some(path),
12410            ..Opts::default()
12411        };
12412        let queue = Queue::at(repo.join("queue"));
12413        let mut new = task();
12414        queue.put(&mut new).unwrap();
12415        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12416        assert_eq!(
12417            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12418            BuildCache::Isolated
12419        );
12420
12421        let mut old = task();
12422        old.schema = 22;
12423        queue.put(&mut old).unwrap();
12424        let mut old = queue.get(&old.id).unwrap();
12425        let config = resolved(&old);
12426        assert_eq!(config.verify.build_cache, BuildCache::Shared);
12427        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12428        old.hold_manual(Some("wait".into()));
12429        queue.put(&mut old).unwrap();
12430
12431        let mut saved = queue.get(&old.id).unwrap();
12432        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12433        saved
12434            .overrides
12435            .as_mut()
12436            .unwrap()
12437            .merge_over(&crate::queue::RunOverrides {
12438                build_cache: Some(BuildCache::Isolated),
12439                ..Default::default()
12440            });
12441        queue.put(&mut saved).unwrap();
12442        assert_eq!(
12443            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12444            BuildCache::Isolated
12445        );
12446    }
12447
12448    #[test]
12449    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12450        let dir = tempfile::tempdir().unwrap();
12451        let path = dir.path().join("explicit.toml");
12452        let write = |verify: &str| {
12453            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12454        };
12455        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12456        let opts = Opts {
12457            config: Some(path.clone()),
12458            ..Opts::default()
12459        };
12460        let mut task = task();
12461        task.set_urgent(true).unwrap();
12462        let resolved = |task: &Task| {
12463            prepare_for(dir.path(), &opts, task)
12464                .unwrap()
12465                .verify
12466                .build_cache
12467        };
12468        assert_eq!(resolved(&task), BuildCache::Isolated);
12469        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12470        assert_eq!(resolved(&task), BuildCache::Shared);
12471        task.change_build_cache(None).unwrap();
12472        assert_eq!(resolved(&task), BuildCache::Isolated);
12473        task.set_urgent(false).unwrap();
12474        assert_eq!(resolved(&task), BuildCache::Shared);
12475
12476        // Urgent work must never be the one stopped by isolation: with no
12477        // shared cache to wait behind, or with a verification command isolated
12478        // mode cannot run, an urgent task keeps the configured mode.
12479        task.set_urgent(true).unwrap();
12480        write("e2e = [\"npm test\"]\n");
12481        assert_eq!(resolved(&task), BuildCache::Shared);
12482        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12483        assert_eq!(resolved(&task), BuildCache::Shared);
12484        // An explicit choice stays strict and is applied as asked.
12485        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12486        assert_eq!(resolved(&task), BuildCache::Isolated);
12487    }
12488
12489    #[test]
12490    fn task_implementers_edit_inherits_daemon_config_and_merge() {
12491        let dir = tempfile::tempdir().unwrap();
12492        let path = dir.path().join("explicit.toml");
12493        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12494        let opts = Opts {
12495            config: Some(path),
12496            merge: Some("none".into()),
12497            ..Default::default()
12498        };
12499        let mut t = task();
12500        t.set_implementers(
12501            2,
12502            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12503                .unwrap(),
12504        )
12505        .unwrap();
12506        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12507        assert_eq!(cfg.graph.implementers, 2);
12508        assert_eq!(cfg.graph.judges, 1);
12509        assert_eq!(cfg.merge.mode, MergeMode::None);
12510        t.set_implementers(1, &cfg).unwrap();
12511        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12512        apply_task_implementers(&mut cfg, &t);
12513        assert_eq!(cfg.graph.implementers, 1);
12514        assert_eq!(cfg.graph.judges, 1);
12515        assert_eq!(cfg.merge.mode, MergeMode::None);
12516    }
12517
12518    #[test]
12519    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12520        let dir = tempfile::tempdir().unwrap();
12521        let repo = dir.path().join("repo");
12522        std::fs::create_dir(&repo).unwrap();
12523        std::fs::write(
12524            repo.join("magi.toml"),
12525            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12526        )
12527        .unwrap();
12528        let daemon_config = dir.path().join("daemon.toml");
12529        std::fs::write(
12530            &daemon_config,
12531            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12532        )
12533        .unwrap();
12534        let opts = Opts {
12535            config: Some(daemon_config),
12536            merge: Some("pr".into()),
12537            ..Default::default()
12538        };
12539        let q = Queue::at(dir.path().join("queue"));
12540        let validation: Config =
12541            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12542                .unwrap();
12543        // No provenance field on legacy direct tasks: both shapes stay isolated.
12544        for record in ["{}", r#"{"candidates":2}"#] {
12545            let overrides = serde_json::from_str(record).unwrap();
12546            let filing = crate::direct::Filing {
12547                instruction: "work".into(),
12548                title: "direct".into(),
12549                repo: repo.clone(),
12550                source: crate::queue::Source::Human,
12551                solo: false,
12552                overrides,
12553                review_of: None,
12554                sources: Default::default(),
12555            };
12556            let filed =
12557                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12558            let crate::direct::Filed::Standalone {
12559                mut task,
12560                claim: _claim,
12561            } = filed
12562            else {
12563                panic!("local filing")
12564            };
12565            let before = prepare_for(&repo, &opts, &task).unwrap();
12566            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12567            assert_eq!(
12568                before.merge.mode,
12569                MergeMode::None,
12570                "daemon --merge must not leak"
12571            );
12572            for n in [2, 1, 2] {
12573                task.set_implementers(n, &validation).unwrap();
12574                q.put(&mut task).unwrap();
12575                task = q.get(&task.id).unwrap();
12576                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12577                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12578                apply_task_implementers(&mut cfg, &task);
12579                assert_eq!(cfg.graph.implementers, usize::from(n));
12580                assert_eq!(cfg.graph.judges, 2);
12581                assert_eq!(cfg.merge.mode, MergeMode::None);
12582            }
12583        }
12584    }
12585
12586    #[test]
12587    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12588        let cfg: Config =
12589            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12590                .unwrap();
12591        let mut t = task();
12592        t.review_of = Some("review-target".into());
12593        t.hold_manual(Some("retry".into()));
12594        let mut previous = RunState::new(
12595            PathBuf::from("/repo"),
12596            "main".into(),
12597            "abc1234".into(),
12598            "review".into(),
12599            cfg.clone(),
12600        );
12601        previous.config.graph.implementers = 2;
12602        for count in [1, 3] {
12603            t.set_implementers(count, &cfg).unwrap();
12604            t.release();
12605            assert_eq!(t.review_of.as_deref(), Some("review-target"));
12606            for proposed in [
12607                Starter::Resume(previous.id.clone()),
12608                Starter::Review("recovery-target".into()),
12609            ] {
12610                assert_eq!(
12611                    starter_with_implementers(&t, Some(&previous), proposed),
12612                    Starter::Review("review-target".into())
12613                );
12614            }
12615            let mut configured = cfg.clone();
12616            apply_task_implementers(&mut configured, &t);
12617            assert_eq!(configured.graph.implementers, usize::from(count));
12618            assert_eq!(previous.config.graph.implementers, 2);
12619        }
12620    }
12621
12622    #[test]
12623    fn task_implementers_dispatch_and_resume_agree() {
12624        let mut t = task();
12625        let cfg: crate::config::Config =
12626            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12627                .unwrap();
12628        let mut run = RunState::new(
12629            PathBuf::from("/repo"),
12630            "main".into(),
12631            "abc1234".into(),
12632            "work".into(),
12633            cfg.clone(),
12634        );
12635        run.config.graph.implementers = 2;
12636        for n in [2, 1, 3, 2] {
12637            t.set_implementers(n, &cfg).unwrap();
12638            let mut dispatched = cfg.clone();
12639            apply_task_implementers(&mut dispatched, &t);
12640            assert_eq!(dispatched.graph.implementers, usize::from(n));
12641            assert_eq!(implementers_match(&t, &run), n == 2);
12642            for proposed in [
12643                Starter::Resume(run.id.clone()),
12644                Starter::Review("old-branch".into()),
12645            ] {
12646                let expected = if n == 2 {
12647                    proposed.clone()
12648                } else {
12649                    Starter::Start
12650                };
12651                assert_eq!(
12652                    starter_with_implementers(&t, Some(&run), proposed),
12653                    expected
12654                );
12655            }
12656            assert_eq!(
12657                run.config.graph.implementers, 2,
12658                "history must not be rewritten"
12659            );
12660        }
12661        t.solo = false;
12662        t.overrides = None;
12663        assert!(implementers_match(&t, &run));
12664    }
12665
12666    #[test]
12667    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12668        // Three seats said out loud. What `solo` promises is one candidate
12669        // *whatever the config asks for*, so the contrast has to be a number
12670        // this test owns - it used to be `Config::default()`'s, which became
12671        // 1 when one implementation became the default and left the two
12672        // halves of this test asserting the same thing.
12673        let mut solo_cfg = Config::default();
12674        solo_cfg.graph.implementers = 3;
12675        let mut solo_task = task();
12676        solo_task.solo = true;
12677        apply_task_implementers(&mut solo_cfg, &solo_task);
12678        assert_eq!(solo_cfg.graph.implementers, 1);
12679
12680        let mut plain_cfg = Config::default();
12681        plain_cfg.graph.implementers = 3;
12682        let plain_task = task();
12683        assert!(!plain_task.solo);
12684        apply_task_implementers(&mut plain_cfg, &plain_task);
12685        assert_eq!(
12686            plain_cfg.graph.implementers, 3,
12687            "a task that did not ask to run alone keeps the config's candidates"
12688        );
12689    }
12690
12691    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12692        QuotaLoss {
12693            cause: crate::agent::QuotaCause::UsageLimit,
12694            agent: String::new(),
12695            seat: seat.into(),
12696            node: "judge".into(),
12697            at: at.parse().unwrap(),
12698            reset: reset.map(str::to_string),
12699        }
12700    }
12701
12702    #[test]
12703    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12704        let now = Timestamp::now();
12705        for reset in [None, Some("in 1h")] {
12706            let auth = crate::agent::Quota {
12707                cause: crate::agent::QuotaCause::Authentication,
12708                agent: "alpha".into(),
12709                reset: reset.map(str::to_owned),
12710            };
12711            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12712            assert_eq!(cooldown_until(&[loss], now), None);
12713        }
12714    }
12715
12716    #[test]
12717    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12718        let old: Vec<QuotaLoss> = (1..=4)
12719            .map(|i| {
12720                loss(
12721                    &format!("judge-{i}"),
12722                    "2026-09-23T05:23:00Z",
12723                    Some("2:40pm (Asia/Tokyo)"),
12724                )
12725            })
12726            .collect();
12727        let fresh = losses_this_attempt(&old, &old);
12728        assert!(fresh.is_empty());
12729        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12730        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
12731    }
12732
12733    #[test]
12734    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12735        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12736        let now = Timestamp::now();
12737        let mut after = old.clone();
12738        after.push(loss("judge-2", &now.to_string(), None));
12739        let fresh = losses_this_attempt(&old, &after);
12740        assert_eq!(fresh, vec![after[1].clone()]);
12741        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12742        assert_eq!(
12743            until,
12744            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12745        );
12746    }
12747
12748    #[test]
12749    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12750        // `recover_stall` removes judge-1's loss and the retry then hits quota
12751        // again: the vector is the same length, so an index diff sees nothing.
12752        let before = vec![
12753            loss("judge-1", "2026-09-23T05:23:00Z", None),
12754            loss("judge-2", "2026-09-23T05:24:00Z", None),
12755        ];
12756        let after = vec![
12757            loss("judge-2", "2026-09-23T05:24:00Z", None),
12758            loss("judge-1", "2026-09-24T01:00:00Z", None),
12759        ];
12760        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12761    }
12762
12763    #[test]
12764    fn merge_overrides_are_parsed_or_refused() {
12765        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12766        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12767        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12768        assert!(merge_mode("squash").is_err());
12769    }
12770
12771    #[test]
12772    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12773        let now = Timestamp::now();
12774        let fallback = Duration::from_secs(300);
12775        let cap = Duration::from_secs(1800);
12776
12777        // No reset hint at all: the fallback.
12778        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12779
12780        // A reset ten minutes out, well inside the cap: waited for exactly.
12781        let soon = now + jiff::SignedDuration::from_secs(600);
12782        assert_eq!(
12783            quota_wait(Some(soon), now, fallback, cap),
12784            Duration::from_secs(600)
12785        );
12786
12787        // A reset already in the past is not trusted: the fallback, not a
12788        // zero or negative wait that would spin the loop right back around.
12789        let past = now - jiff::SignedDuration::from_secs(60);
12790        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12791
12792        // A reset further out than the cap is trusted for direction but not
12793        // for magnitude: a parsing slip must not sleep the loop for a day.
12794        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12795        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12796    }
12797
12798    #[test]
12799    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12800        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12801
12802        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12803        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12804
12805        // Same clock reading, but it has already gone by today: read as
12806        // tomorrow's, since the CLI would not still be reporting a limit past
12807        // its own stated reset.
12808        let already_past =
12809            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12810        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12811
12812        assert!(
12813            parse_reset_hint("session limit reached", now, now).is_none(),
12814            "free text with no recognised shape is not guessed at"
12815        );
12816        assert!(
12817            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12818            "an unresolvable zone name is not guessed at either"
12819        );
12820    }
12821
12822    #[test]
12823    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12824        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12825
12826        let at = parse_reset_hint(
12827            "You've hit your usage limit. Visit \
12828             https://chatgpt.com/codex/settings/usage to purchase more \
12829             credits or try again at Sep 19th, 2026 5:10 PM.",
12830            now,
12831            now,
12832        )
12833        .expect("the codex reset wording is a recognised shape");
12834        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12835
12836        // The month is explicit, so a date already earlier in the same
12837        // sentence-implied year than `now` is trusted as written rather than
12838        // rolled forward a year the way the bracketed shape rolls a
12839        // same-day clock reading to tomorrow.
12840        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12841            .expect("an explicit year needs no rollover");
12842        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12843
12844        assert!(
12845            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
12846            "a two-digit year is not the documented shape and is not guessed at"
12847        );
12848        assert!(
12849            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
12850            "a four-letter month name is not the documented three-letter abbreviation"
12851        );
12852        assert!(
12853            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
12854            "an explicit zone on the dated shape is a format nobody has \
12855             documented, and is refused rather than guessed at as UTC"
12856        );
12857    }
12858
12859    #[test]
12860    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
12861        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
12862        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
12863
12864        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
12865        assert_eq!(at.as_second() - recorded.as_second(), 3769);
12866
12867        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
12868        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
12869
12870        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
12871            assert!(
12872                parse_reset_hint(bad, now, recorded).is_none(),
12873                "{bad:?} must not be guessed at"
12874            );
12875        }
12876    }
12877
12878    /// A loop whose queue lives in a temp tree and whose poll interval is far
12879    /// longer than the test's patience, so anything that waits out a poll
12880    /// instead of noticing the stop fails rather than merely being slow.
12881    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
12882        let config = dir.join("magi.toml");
12883        std::fs::write(
12884            &config,
12885            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
12886        )
12887        .unwrap();
12888        let opts = Opts {
12889            poll: Duration::from_secs(30),
12890            config: Some(config),
12891            // The explicit fixture config keeps startup cleanup from reading
12892            // machine configuration. This fictional repository likewise
12893            // keeps any best-effort git cleanup away from this checkout.
12894            repo: dir.join("repo"),
12895            ..Opts::default()
12896        };
12897        // The status file goes in a directory that does not exist yet, so its
12898        // creation is itself evidence the loop published one. `worktrees`
12899        // must be just as fictional: the janitor reclaims worktrees under it
12900        // for real, and a test that let it fall through to
12901        // `crate::run::default_worktree_root()` would have it reclaim
12902        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
12903        // which is exactly what happened before this function took the
12904        // parameter at all.
12905        let home = dir.join("home");
12906        // These control-only fixtures do not launch native workers. Give the
12907        // independently tested maintenance services a fresh cadence receipt.
12908        let stamps = home.join("service-ticks");
12909        std::fs::create_dir_all(&stamps).unwrap();
12910        for service in ["waiter", "deputies", "release-watch"] {
12911            std::fs::write(
12912                stamps.join(service),
12913                Timestamp::now().as_second().to_string(),
12914            )
12915            .unwrap();
12916        }
12917        for operation in [
12918            "conductor",
12919            "maintenance",
12920            "housekeeping",
12921            "disk-pressure",
12922            "fold",
12923            "cache",
12924            "fetch",
12925            "chat-goals",
12926        ] {
12927            std::fs::write(
12928                stamps.join(format!("daemon-{operation}")),
12929                serde_json::to_vec(&Timestamp::now()).unwrap(),
12930            )
12931            .unwrap();
12932        }
12933        let worktrees = dir.join("wt");
12934        (
12935            opts,
12936            Queue::at(dir.join("queue")),
12937            home.join("daemon.json"),
12938            home,
12939            worktrees,
12940        )
12941    }
12942
12943    #[tokio::test]
12944    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
12945        let dir = tempfile::tempdir().unwrap();
12946        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12947        let mut waiting = task();
12948        waiting.repo = opts.repo.clone();
12949        waiting.hold_machine(crate::disk::gate(1, 100));
12950        waiting.mark_disk_capacity();
12951        waiting.attempts = 2;
12952        queue.put(&mut waiting).unwrap();
12953        let mut busy = task();
12954        busy.status = TaskStatus::Running;
12955        queue.put(&mut busy).unwrap();
12956        let payload = serde_json::to_value(ServiceWorker {
12957            opts,
12958            queue: queue.root().to_owned(),
12959            worktrees_root: worktrees,
12960            operation: "maintenance".into(),
12961        })
12962        .unwrap();
12963        run_service_worker(&home, payload.clone()).await.unwrap();
12964        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
12965        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12966        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
12967        run_service_worker(&home, payload).await.unwrap();
12968        assert!(
12969            crate::worker::active(&home).unwrap().is_empty(),
12970            "monitoring only queues; normal dispatch owns launches"
12971        );
12972        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12973    }
12974
12975    #[tokio::test]
12976    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
12977        let dir = tempfile::tempdir().unwrap();
12978        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12979        let cfg = Config::default();
12980        start_service(
12981            &home,
12982            &opts,
12983            &queue,
12984            &worktrees,
12985            "housekeeping",
12986            Some(&cfg),
12987            true,
12988        )
12989        .await
12990        .unwrap();
12991        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
12992        let read = |path: &Path| -> serde_json::Value {
12993            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
12994        };
12995        assert_eq!(read(&receipt)["detail"], "cadence not due");
12996        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
12997        start_service(
12998            &home,
12999            &opts,
13000            &queue,
13001            &worktrees,
13002            "housekeeping",
13003            Some(&cfg),
13004            true,
13005        )
13006        .await
13007        .unwrap();
13008        assert_eq!(
13009            read(&receipt)["detail"],
13010            "active work or runnable task queue"
13011        );
13012        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13013        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13014        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13015        start_service(
13016            &home,
13017            &opts,
13018            &queue,
13019            &worktrees,
13020            "disk-pressure",
13021            Some(&cfg),
13022            false,
13023        )
13024        .await
13025        .unwrap();
13026        assert_eq!(
13027            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13028            "no active work; idle housekeeping owns scan"
13029        );
13030        assert!(crate::worker::active(&home).unwrap().is_empty());
13031    }
13032
13033    /// The folding turn exists exactly where idle housekeeping does not: with
13034    /// work busy or runnable. On `origin/main` the only caller of
13035    /// `clean::fold_due` was housekeeping, so a queue that was never empty
13036    /// admitted no finished-run folding at all.
13037    #[test]
13038    fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13039        let on = Config::default();
13040        for busy in [false, true] {
13041            for runnable in [false, true] {
13042                assert_ne!(
13043                    housekeeping_eligible(busy, runnable),
13044                    fold_turn_eligible(busy, runnable, Some(&on)),
13045                    "busy={busy} runnable={runnable}"
13046                );
13047            }
13048        }
13049        assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13050        assert!(!fold_turn_eligible(true, true, None));
13051        let mut off = Config::default();
13052        off.disk.auto_fold = false;
13053        assert!(!fold_turn_eligible(true, true, Some(&off)));
13054        assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13055    }
13056
13057    #[tokio::test]
13058    async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13059        let dir = tempfile::tempdir().unwrap();
13060        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13061        let read = || -> serde_json::Value {
13062            serde_json::from_slice(
13063                &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13064            )
13065            .unwrap()
13066        };
13067        let tick = home.join("service-ticks/daemon-fold");
13068        let cfg = Config::default();
13069        let dispatch = |busy: bool, cfg: Config| {
13070            let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13071            async move {
13072                start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13073                    .await
13074                    .unwrap();
13075            }
13076        };
13077        dispatch(true, cfg.clone()).await;
13078        assert_eq!(read()["detail"], "cadence not due");
13079
13080        std::fs::remove_file(&tick).unwrap();
13081        dispatch(false, cfg.clone()).await;
13082        assert_eq!(
13083            read()["detail"],
13084            "idle machine; housekeeping owns finished-run folding"
13085        );
13086        let mut off = cfg.clone();
13087        off.disk.auto_fold = false;
13088        dispatch(true, off).await;
13089        assert_eq!(read()["detail"], "auto_fold disabled");
13090        // An unreadable startup configuration is its own reason, not "idle".
13091        start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13092            .await
13093            .unwrap();
13094        assert_eq!(read()["detail"], "startup configuration unavailable");
13095
13096        // A housekeeping worker already folding: one folding service at a time.
13097        let directory = home.join("workers/jobs/abcdef");
13098        std::fs::create_dir_all(&directory).unwrap();
13099        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13100        crate::pr_head::try_lock_file(&lease).unwrap();
13101        let mut job = crate::worker::Job {
13102            id: "abcdef".into(),
13103            sequence: 1,
13104            kind: "daemon-service".into(),
13105            key: "service:daemon-housekeeping".into(),
13106            payload: serde_json::Value::Null,
13107            generation: "fixture".into(),
13108            version: None,
13109            status: crate::worker::Status::Running,
13110            result: None,
13111            pid: Some(std::process::id()),
13112            created_at: Timestamp::now().as_second() as u64,
13113            finished_at: None,
13114        };
13115        let record = directory.join("job.json");
13116        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13117        dispatch(true, cfg).await;
13118        assert_eq!(
13119            read()["detail"],
13120            "another finished-run folding service is active"
13121        );
13122        assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13123        job.status = crate::worker::Status::Finished;
13124        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13125        drop(lease);
13126    }
13127
13128    /// Issue 1275 through the scheduler's own admission: a leased task worker is
13129    /// busy, another task is runnable, and a confirmed merged run of the same
13130    /// repository is long past its grace. `poll` admits the fold service (the
13131    /// worker runs inline here: a unit test has no `magi` executable to exec),
13132    /// the historical worktree goes, the repository's active checkout stays and
13133    /// the merged run's evidence is kept. Removing `"fold"` from the operation
13134    /// list in `poll` leaves the worktree standing and fails this test.
13135    #[tokio::test]
13136    async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13137        let dir = tempfile::tempdir().unwrap();
13138        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13139        let repo = dir.path().join("checkout");
13140        std::fs::create_dir_all(&repo).unwrap();
13141        crate::clean::tests::init_repo(&repo);
13142        std::fs::write(
13143            opts.config.as_ref().unwrap(),
13144            "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13145        )
13146        .unwrap();
13147        let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13148            &home,
13149            &repo,
13150            &worktrees,
13151            "20260801-000000-s001",
13152        )
13153        .await;
13154        let active = dir.path().join("active");
13155        crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13156            .await
13157            .unwrap();
13158        // The busy worker belongs to the scheduler's own queue and owns a
13159        // recorded run of the same repository that is eligible on paper
13160        // (finished, past its grace). Its execution lease is held, as a
13161        // driving worker holds it.
13162        let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13163            &home.join("runs"),
13164            &worktrees,
13165            &repo,
13166            "20260801-000000-s002",
13167            RunStatus::Superseded,
13168        )
13169        .await;
13170        let owned_run = home.join("runs").join(&owned_id);
13171        let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13172        let mut busy = task();
13173        busy.repo = repo.clone();
13174        busy.status = TaskStatus::Running;
13175        busy.link_run(&owned_id);
13176        queue.put(&mut busy).unwrap();
13177        let worker_lease = crate::worker::running_fixture(
13178            &home,
13179            &format!("task:{}", busy.id),
13180            serde_json::to_value(TaskWorker {
13181                opts: Opts::default(),
13182                queue: queue.root().to_owned(),
13183                task: busy.id.clone(),
13184                lane: PermitKind::default(),
13185                standalone: true,
13186            })
13187            .unwrap(),
13188        )
13189        .unwrap();
13190        let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13191        let mut waiting = task();
13192        waiting.repo = repo.clone();
13193        queue.put(&mut waiting).unwrap();
13194        std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13195
13196        let mut cfg = Config::default();
13197        cfg.disk.auto_fold = true;
13198        INLINE_SERVICES.with(|inline| inline.set(true));
13199        let status = Arc::new(Mutex::new(Status::new()));
13200        let stop = Stop::new();
13201        let mut dispatch = Box::pin(poll(
13202            &opts,
13203            &queue,
13204            &status,
13205            &home,
13206            &worktrees,
13207            &stop,
13208            DispatchLimits {
13209                max_concurrent: 0,
13210                pause_for_interrupts: false,
13211                recovery_cfg: Some(cfg),
13212            },
13213        ));
13214        let receipt = home.join("source-eviction-fold-worker.json");
13215        let completed = async {
13216            loop {
13217                let done = std::fs::read(&receipt)
13218                    .ok()
13219                    .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13220                    .is_some_and(|receipt| receipt["outcome"] == "completed");
13221                if done {
13222                    break;
13223                }
13224                tokio::time::sleep(Duration::from_millis(25)).await;
13225            }
13226        };
13227        tokio::select! {
13228            result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13229            result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13230                result.expect("the scheduler never admitted the fold service");
13231            }
13232        }
13233        stop.stop();
13234        dispatch.await.unwrap();
13235        INLINE_SERVICES.with(|inline| inline.set(false));
13236
13237        assert!(!historical.exists(), "the merged run's worktree is folded");
13238        assert!(
13239            active.join("README.md").is_file(),
13240            "the repository's active checkout is untouched"
13241        );
13242        let run = home.join("runs").join(&id);
13243        assert!(run.join("run.json").is_file());
13244        assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13245        let read = |name: &str| -> serde_json::Value {
13246            serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13247        };
13248        assert_eq!(
13249            read("source-eviction-fold-dispatch.json")["detail"],
13250            "eligible and cadence due"
13251        );
13252        let worker = read("source-eviction-fold-worker.json");
13253        assert_eq!(worker["fold"]["records"], 2);
13254        assert_eq!(worker["fold"]["folded"], 1);
13255        assert_eq!(worker["fold"]["invoked"], 1);
13256        assert_eq!(
13257            worker["fold"]["live"], 1,
13258            "the busy worker's own run is left alone: {worker}"
13259        );
13260        // The run the busy worker owns - eligible on paper (finished, past its
13261        // grace) - keeps its checkout, its candidate and its record, byte for byte.
13262        assert!(owned_worktree.exists());
13263        assert_eq!(
13264            std::fs::read(owned_run.join("run.json")).unwrap(),
13265            owned_record
13266        );
13267        assert!(
13268            !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13269            "the owned run's candidate is not folded"
13270        );
13271        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13272        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13273        drop(execution);
13274        drop(worker_lease);
13275    }
13276
13277    /// On a platform without process containment the disk-pressure service
13278    /// refuses to reclaim, and says so in both places an operator looks: the
13279    /// persisted retention report and the worker receipt. Driven through the
13280    /// service handler itself, so removing either publication fails this test.
13281    #[tokio::test]
13282    async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13283        let dir = tempfile::tempdir().unwrap();
13284        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13285        let payload = serde_json::to_value(ServiceWorker {
13286            opts,
13287            queue: queue.root().to_owned(),
13288            worktrees_root: worktrees,
13289            operation: "disk-pressure".into(),
13290        })
13291        .unwrap();
13292        let _platform = crate::retention::WithoutContainment::new();
13293        run_service_worker(&home, payload).await.unwrap();
13294
13295        let refusal = "Automatic output reclamation requires Unix process containment";
13296        let report: serde_json::Value =
13297            serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13298        assert_eq!(report["failures"], serde_json::json!([refusal]));
13299        let receipt: serde_json::Value = serde_json::from_slice(
13300            &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13301        )
13302        .unwrap();
13303        assert_eq!(receipt["outcome"], "retention swept");
13304        assert_eq!(receipt["retention"]["failure_count"], 1);
13305        assert_eq!(
13306            receipt["retention"]["failures"],
13307            serde_json::json!([refusal])
13308        );
13309    }
13310
13311    #[tokio::test]
13312    async fn goal_observation_service_does_not_block_scheduler_decisions() {
13313        let dir = tempfile::tempdir().unwrap();
13314        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13315        let queue = Queue::at(home.join("queue"));
13316        let mut task = task();
13317        task.repo = opts.repo.clone();
13318        task.chat = Some("decision-chat".into());
13319        task.hold_machine(Some("waiting for a decision".into()));
13320        queue.put(&mut task).unwrap();
13321        let questions = Questions::at(home.join("questions"));
13322        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13323        question.node = crate::conduct::NODE.into();
13324        question.status = ask::QuestionStatus::Open;
13325        question.answer = None;
13326        question.answered_at = None;
13327        questions.put(&mut question).unwrap();
13328        questions
13329            .update(&question.id, |q| {
13330                q.answer(ask::Answer::Choice("resume で続行する".into()))
13331            })
13332            .unwrap();
13333
13334        let talks = crate::talk::Talks::at(home.join("talks"));
13335        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13336        decision_chat.pending = "Keep this unsent status question".into();
13337        talks.put(&mut decision_chat).unwrap();
13338        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13339        talk.goals.push(serde_json::from_value(serde_json::json!({
13340            "id":"goal","purpose":"follow the retained job","scope":"one task",
13341            "condition":{"description":"land the result","kind":"runs_merged"},
13342            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13343            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13344            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13345        })).unwrap());
13346        talks.put(&mut talk).unwrap();
13347
13348        // A retained service lease models an observation still waiting on its
13349        // external dependency. Admission must neither await nor repeat it.
13350        let directory = home.join("workers/jobs/abcdef");
13351        std::fs::create_dir_all(&directory).unwrap();
13352        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13353        crate::pr_head::try_lock_file(&lease).unwrap();
13354        let mut job = crate::worker::Job {
13355            id: "abcdef".into(),
13356            sequence: 1,
13357            kind: "daemon-service".into(),
13358            key: "service:daemon-chat-goals".into(),
13359            payload: serde_json::Value::Null,
13360            generation: "fixture".into(),
13361            version: None,
13362            status: crate::worker::Status::Running,
13363            result: None,
13364            pid: Some(std::process::id()),
13365            created_at: Timestamp::now().as_second() as u64,
13366            finished_at: None,
13367        };
13368        let record = directory.join("job.json");
13369        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13370        let status = Arc::new(Mutex::new(Status::new()));
13371        let stop = Stop::new();
13372        let mut dispatch = Box::pin(poll(
13373            &opts,
13374            &queue,
13375            &status,
13376            &home,
13377            &worktrees,
13378            &stop,
13379            DispatchLimits {
13380                max_concurrent: 1,
13381                pause_for_interrupts: false,
13382                recovery_cfg: None,
13383            },
13384        ));
13385        std::future::poll_fn(|cx| {
13386            assert!(dispatch.as_mut().poll(cx).is_pending());
13387            std::task::Poll::Ready(())
13388        })
13389        .await;
13390        assert!(lock(&status).polls > 0);
13391        let saved = queue.get(&task.id).unwrap();
13392        assert_eq!(saved.status, TaskStatus::Done);
13393        assert!(saved.action_applied(&question.id));
13394        assert!(
13395            talks
13396                .get("decision-chat")
13397                .unwrap()
13398                .pending
13399                .contains("Keep this unsent status question")
13400        );
13401        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13402        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13403        assert_eq!(
13404            goal.started,
13405            Some(1),
13406            "only the observation worker may reconcile its goal"
13407        );
13408        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13409
13410        stop.stop();
13411        dispatch.await.unwrap();
13412        job.status = crate::worker::Status::Finished;
13413        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13414        drop(lease);
13415    }
13416
13417    #[test]
13418    fn a_stop_is_idempotent_and_once_set_stays_set() {
13419        let stop = Stop::new();
13420        assert!(!stop.stopped());
13421
13422        stop.stop();
13423        assert!(stop.stopped());
13424        stop.stop();
13425        assert!(stop.stopped(), "a second stop is not a toggle");
13426
13427        let shared = stop.clone();
13428        assert!(
13429            shared.stopped(),
13430            "a clone is the same stop; that is how the loop and its caller share one"
13431        );
13432    }
13433
13434    #[tokio::test]
13435    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13436        for operation in ["conductor", "maintenance", "housekeeping"] {
13437            let dir = tempfile::tempdir().unwrap();
13438            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13439            opts.once = true;
13440            opts.poll = Duration::from_millis(1);
13441            // This test exercises answer scheduling, not explicit discard:
13442            // ordinary Done requires a completed retained execution.
13443            let mut state = run_state(RunStatus::Ready);
13444            state.reserve_under(&home).unwrap();
13445            state.save_under(&home).unwrap();
13446            let mut task = task();
13447            task.runs.push(state.id.clone());
13448            queue.put(&mut task).unwrap();
13449            let claim = queue.claim(&task.id).unwrap();
13450
13451            // Model a live service holding the task's claim across the
13452            // scheduler's dispatch scan. No real subprocess or timed race.
13453            let directory = home.join("workers/jobs/abcdef");
13454            std::fs::create_dir_all(&directory).unwrap();
13455            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13456            crate::pr_head::try_lock_file(&lease).unwrap();
13457            let mut job = crate::worker::Job {
13458                id: "abcdef".into(),
13459                sequence: 1,
13460                kind: "daemon-service".into(),
13461                key: format!("service:daemon-{operation}"),
13462                payload: serde_json::Value::Null,
13463                generation: "fixture".into(),
13464                version: None,
13465                status: crate::worker::Status::Running,
13466                result: None,
13467                pid: Some(std::process::id()),
13468                created_at: Timestamp::now().as_second() as u64,
13469                finished_at: None,
13470            };
13471            let record = directory.join("job.json");
13472            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13473
13474            let status = Arc::new(Mutex::new(Status::new()));
13475            let stop = Stop::new();
13476            let mut drain = Box::pin(poll(
13477                &opts,
13478                &queue,
13479                &status,
13480                &home,
13481                &worktrees,
13482                &stop,
13483                DispatchLimits {
13484                    max_concurrent: 1,
13485                    pause_for_interrupts: false,
13486                    recovery_cfg: None,
13487                },
13488            ));
13489            std::future::poll_fn(|cx| {
13490                use std::future::Future;
13491                assert!(
13492                    drain.as_mut().poll(cx).is_pending(),
13493                    "--once must wait for {operation} to release its queue claim"
13494                );
13495                std::task::Poll::Ready(())
13496            })
13497            .await;
13498            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13499
13500            // An answer arrives while the service still owns the claim. A
13501            // fresh scheduling pass must apply it before declaring idle.
13502            let questions = Questions::at(home.join("questions"));
13503            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13504            questions.put(&mut q).unwrap();
13505            drop(claim);
13506            // Model services that took longer than their cadence, without a
13507            // wall-clock sleep. The final scans must not respawn them even
13508            // though their receipts now permit another periodic invocation.
13509            let expired =
13510                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13511            for service in [operation, "housekeeping"] {
13512                std::fs::write(
13513                    home.join("service-ticks").join(format!("daemon-{service}")),
13514                    &expired,
13515                )
13516                .unwrap();
13517            }
13518            job.status = crate::worker::Status::Finished;
13519            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13520            drop(lease);
13521            tokio::time::timeout(Duration::from_secs(2), drain)
13522                .await
13523                .expect("the settled service must allow the drain to finish")
13524                .unwrap();
13525            let after = queue.get(&task.id).unwrap();
13526            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13527            assert!(after.action_applied(&q.id));
13528            for service in [operation, "housekeeping"] {
13529                assert_eq!(
13530                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13531                        .unwrap(),
13532                    expired,
13533                    "the final once rescan must not restart {service}"
13534                );
13535            }
13536        }
13537    }
13538
13539    #[test]
13540    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13541        let stop = Stop::new();
13542        stop.busy.store(1, Ordering::SeqCst);
13543        assert!(
13544            !stop.finishing(),
13545            "a busy loop nobody has asked to stop is just running"
13546        );
13547
13548        stop.stop();
13549        assert!(
13550            stop.finishing(),
13551            "a stop asked for mid-run has not landed until the run is settled"
13552        );
13553
13554        stop.busy.store(0, Ordering::SeqCst);
13555        assert!(
13556            !stop.finishing(),
13557            "once the run is settled the stop has landed and there is nothing to finish"
13558        );
13559    }
13560
13561    #[test]
13562    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13563        let stop = Stop::new();
13564        stop.busy.store(2, Ordering::SeqCst);
13565        stop.stop();
13566        assert!(stop.finishing(), "two runs still in flight");
13567
13568        stop.busy.store(1, Ordering::SeqCst);
13569        assert!(
13570            stop.finishing(),
13571            "one run finished, but a sibling is still working"
13572        );
13573
13574        stop.busy.store(0, Ordering::SeqCst);
13575        assert!(
13576            !stop.finishing(),
13577            "the last run out is what actually lands the stop"
13578        );
13579    }
13580
13581    #[tokio::test]
13582    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13583        let dir = tempfile::tempdir().unwrap();
13584        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13585        let stop = Stop::new();
13586        stop.stop();
13587
13588        let began = std::time::Instant::now();
13589        tokio::time::timeout(
13590            Duration::from_secs(2),
13591            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13592        )
13593        .await
13594        .expect("a stopped loop must return, not sit out its poll interval")
13595        .expect("the loop's own setup and teardown must not fail");
13596        assert!(
13597            began.elapsed() < opts.poll,
13598            "returned only after {:?}, which is a poll interval, not a stop",
13599            began.elapsed()
13600        );
13601    }
13602
13603    #[tokio::test]
13604    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13605        let dir = tempfile::tempdir().unwrap();
13606        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13607        let stop = Stop::new();
13608
13609        // Asked for after the loop is already parked on its empty queue, which
13610        // is the case an operator tapping stop on a phone actually hits.
13611        let asker = {
13612            let stop = stop.clone();
13613            tokio::spawn(async move {
13614                tokio::time::sleep(Duration::from_millis(20)).await;
13615                stop.stop();
13616            })
13617        };
13618
13619        let began = std::time::Instant::now();
13620        tokio::time::timeout(
13621            Duration::from_secs(2),
13622            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13623        )
13624        .await
13625        .expect("a stop asked for while idle must wake the wait")
13626        .expect("the loop's own setup and teardown must not fail");
13627        asker.await.unwrap();
13628        assert!(
13629            began.elapsed() < opts.poll,
13630            "returned only after {:?}, so the stop waited on the sleep",
13631            began.elapsed()
13632        );
13633    }
13634
13635    #[tokio::test]
13636    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13637        let dir = tempfile::tempdir().unwrap();
13638        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13639        let stop = Stop::new();
13640        stop.stop();
13641
13642        tokio::time::timeout(
13643            Duration::from_secs(2),
13644            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13645        )
13646        .await
13647        .expect("a stopped loop must return")
13648        .expect("the loop's own setup and teardown must not fail");
13649
13650        assert!(
13651            home.is_dir(),
13652            "the loop did publish a status file, so its removal is the teardown and not an absence"
13653        );
13654        assert!(
13655            !status_file.exists(),
13656            "a stopped loop clears its status file"
13657        );
13658        assert!(
13659            read_status(&home).is_none(),
13660            "a reader must see no daemon at all, not a heartbeat that merely stopped"
13661        );
13662    }
13663
13664    #[tokio::test]
13665    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13666        let dir = tempfile::tempdir().unwrap();
13667        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13668
13669        let mut settled = RunState::new(
13670            dir.path().join("repo"),
13671            "main".to_owned(),
13672            "abc1234".to_owned(),
13673            "fixture".to_owned(),
13674            Config::default(),
13675        );
13676        settled.status = RunStatus::Ready;
13677        let run_dir = home.join("runs").join(&settled.id);
13678        std::fs::create_dir_all(&run_dir).unwrap();
13679        std::fs::write(
13680            run_dir.join("run.json"),
13681            serde_json::to_string_pretty(&settled).unwrap(),
13682        )
13683        .unwrap();
13684        let questions = Questions::at(home.join("questions"));
13685        let mut question = ask::Question::new(
13686            settled.id.clone(),
13687            "review".to_owned(),
13688            "reviewer-1".to_owned(),
13689            "Continue?".to_owned(),
13690            String::new(),
13691            Vec::new(),
13692        );
13693        questions.put(&mut question).unwrap();
13694
13695        run_service_worker(
13696            &home,
13697            serde_json::to_value(ServiceWorker {
13698                opts,
13699                queue: queue.root().to_path_buf(),
13700                worktrees_root: worktrees,
13701                operation: "housekeeping".to_owned(),
13702            })
13703            .unwrap(),
13704        )
13705        .await
13706        .unwrap();
13707
13708        assert_eq!(
13709            questions.get(&question.id).unwrap().status,
13710            ask::QuestionStatus::Abandoned,
13711            "the independent housekeeping worker settles ended-run questions"
13712        );
13713    }
13714
13715    #[test]
13716    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13717        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13718
13719        assert!(
13720            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13721            "never checked before: due at once"
13722        );
13723
13724        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13725        assert!(
13726            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13727            "well inside the interval: not due yet"
13728        );
13729
13730        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13731        assert!(
13732            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13733            "exactly at the edge: not yet due, same convention as `clean::due`"
13734        );
13735
13736        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13737        assert!(
13738            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13739            "past the interval: due again"
13740        );
13741    }
13742
13743    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
13744    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
13745    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
13746    /// and the congestion test below both need, and must not drift apart.
13747    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13748        let config = dir.join("magi.toml");
13749        // A literal (single-quoted) TOML string, not a basic one: the cache
13750        // path is a Windows path full of backslashes, and a basic string
13751        // would have TOML try to interpret `\U` (from `\Users\...`) as a
13752        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
13753        // `{{ vars.cache }}` rendering documents.
13754        std::fs::write(
13755            &config,
13756            format!(
13757                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13758                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13759                cache_dir.display()
13760            ),
13761        )
13762        .unwrap();
13763        Opts {
13764            config: Some(config),
13765            repo: dir.join("repo"),
13766            ..Opts::default()
13767        }
13768    }
13769
13770    #[tokio::test]
13771    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13772        let dir = tempfile::tempdir().unwrap();
13773        let home = dir.path().join("home");
13774        let cache_dir = dir.path().join("cache");
13775        std::fs::create_dir_all(&cache_dir).unwrap();
13776        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13777        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13778
13779        // Nobody has asked this daemon to stop, which is the ordinary case;
13780        // the skip that a stop buys is asserted by its own test below.
13781        let running = Stop::new();
13782        let mut last_checked = None;
13783        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13784        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13785            .await;
13786        assert_eq!(
13787            crate::disk::dir_size(&cache_dir),
13788            0,
13789            "over the cap on the first check ever: pruned at once, no idle queue required"
13790        );
13791        assert_eq!(last_checked, Some(t0));
13792
13793        // A fresh oversized file lands, but the next check is not due yet.
13794        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13795        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13796        maybe_prune_cache_between_runs(
13797            &opts.repo,
13798            &opts,
13799            &home,
13800            &running,
13801            &mut last_checked,
13802            too_soon,
13803        )
13804        .await;
13805        assert_eq!(
13806            crate::disk::dir_size(&cache_dir),
13807            10,
13808            "too soon since the last check: left alone rather than rescanned every call"
13809        );
13810        assert_eq!(
13811            last_checked,
13812            Some(t0),
13813            "an idle check does not reset the clock"
13814        );
13815
13816        // Once the interval elapses, the same oversized cache is caught again.
13817        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13818        maybe_prune_cache_between_runs(
13819            &opts.repo,
13820            &opts,
13821            &home,
13822            &running,
13823            &mut last_checked,
13824            due_again,
13825        )
13826        .await;
13827        assert_eq!(
13828            crate::disk::dir_size(&cache_dir),
13829            0,
13830            "due again: pruned back under the cap"
13831        );
13832    }
13833
13834    /// A stop must not queue behind housekeeping. The prune below is a
13835    /// synchronous walk of the whole cache with no await point in it, so a
13836    /// loop that entered it could not get back to its own `stopped()` test
13837    /// until the walk finished - and because no run is in flight at this
13838    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
13839    /// the stop had already landed. The idle branch has always made this same
13840    /// check before reaching `janitor`; the between-runs path makes it too.
13841    #[tokio::test]
13842    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
13843        let dir = tempfile::tempdir().unwrap();
13844        let home = dir.path().join("home");
13845        let cache_dir = dir.path().join("cache");
13846        std::fs::create_dir_all(&cache_dir).unwrap();
13847        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13848        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13849
13850        let stop = Stop::new();
13851        stop.stop();
13852        assert!(
13853            !stop.finishing(),
13854            "no run is in flight at a between-runs boundary, so nothing else \
13855             would tell the operator this stop had not taken effect yet"
13856        );
13857
13858        let mut last_checked = None;
13859        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13860        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
13861            .await;
13862        assert_eq!(
13863            crate::disk::dir_size(&cache_dir),
13864            10,
13865            "over its cap, and due for the first check ever, but a stop outranks \
13866             it: the cap is a standing policy the next start measures again"
13867        );
13868        assert_eq!(
13869            last_checked, None,
13870            "a check that never happened must not claim the interval"
13871        );
13872    }
13873
13874    /// A backlog must not starve cache pruning. The finite cache worker runs
13875    /// independently of queue drain and must not consume any task attempts.
13876    #[tokio::test]
13877    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
13878        let dir = tempfile::tempdir().unwrap();
13879        let cache_dir = dir.path().join("cache");
13880        std::fs::create_dir_all(&cache_dir).unwrap();
13881        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
13882
13883        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
13884        opts.poll = Duration::from_millis(20);
13885        opts.max_attempts = 1_000;
13886
13887        let queue = Queue::at(dir.path().join("queue"));
13888        for i in 0..128 {
13889            let mut task = Task::new(
13890                format!("queued work {i}"),
13891                format!("queued work {i}"),
13892                opts.repo.clone(),
13893                Source::Human,
13894            );
13895            queue.put(&mut task).unwrap();
13896        }
13897
13898        let home = dir.path().join("home");
13899        let worktrees = dir.path().join("wt");
13900        run_service_worker(
13901            &home,
13902            serde_json::to_value(ServiceWorker {
13903                opts,
13904                queue: queue.root().to_path_buf(),
13905                worktrees_root: worktrees,
13906                operation: "cache".to_owned(),
13907            })
13908            .unwrap(),
13909        )
13910        .await
13911        .unwrap();
13912        let after = queue.list();
13913        assert_eq!(after.len(), 128);
13914        assert!(
13915            after
13916                .iter()
13917                .all(|task| task.status.runnable() && task.attempts == 0)
13918        );
13919
13920        assert_eq!(
13921            crate::disk::dir_size(&cache_dir),
13922            0,
13923            "an oversized cache must not be left to grow unboundedly just because the \
13924             queue kept the loop busy the whole time"
13925        );
13926    }
13927
13928    #[test]
13929    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
13930        let dir = tempfile::tempdir().unwrap();
13931        let queue = Queue::at(dir.path().join("queue"));
13932        let questions = Questions::at(dir.path().join("questions"));
13933        let mut task = task();
13934        queue.put(&mut task).unwrap();
13935
13936        let mut task_question = ask::Question::new(
13937            task.id.clone(),
13938            crate::conduct::NODE.to_owned(),
13939            "conduct".to_owned(),
13940            "Which backend?".to_owned(),
13941            String::new(),
13942            Vec::new(),
13943        );
13944        questions.put(&mut task_question).unwrap();
13945        task.block(vec![task_question.id.clone()], None);
13946        queue.put(&mut task).unwrap();
13947
13948        let mut run_question = ask::Question::new(
13949            "20260101-000000-run1".to_owned(),
13950            "review".to_owned(),
13951            "reviewer-1".to_owned(),
13952            "Run question".to_owned(),
13953            String::new(),
13954            Vec::new(),
13955        );
13956        questions.put(&mut run_question).unwrap();
13957
13958        // A question from another node whose `run` happens to equal this
13959        // task's id — the same field, filled in for an unrelated reason. Only
13960        // `crate::conduct::NODE` questions use `run` as a task id; this one
13961        // must never be touched by this reconciliation, even after release.
13962        let mut coincidental = ask::Question::new(
13963            task.id.clone(),
13964            "review".to_owned(),
13965            "reviewer-1".to_owned(),
13966            "Unrelated review question".to_owned(),
13967            String::new(),
13968            Vec::new(),
13969        );
13970        questions.put(&mut coincidental).unwrap();
13971
13972        reconcile_task_questions(&queue, &questions);
13973        assert!(questions.get(&task_question.id).unwrap().status.open());
13974        assert!(questions.get(&run_question.id).unwrap().status.open());
13975        assert!(questions.get(&coincidental.id).unwrap().status.open());
13976
13977        task.release();
13978        queue.put(&mut task).unwrap();
13979        reconcile_task_questions(&queue, &questions);
13980        assert_eq!(
13981            questions.get(&task_question.id).unwrap().status,
13982            ask::QuestionStatus::Abandoned
13983        );
13984        assert!(
13985            questions.get(&run_question.id).unwrap().status.open(),
13986            "run questions remain the run janitor's responsibility"
13987        );
13988        assert!(
13989            questions.get(&coincidental.id).unwrap().status.open(),
13990            "a non-conductor question must not be abandoned just because its \
13991             run id coincides with a task id"
13992        );
13993    }
13994
13995    #[test]
13996    fn a_freshly_started_running_task_is_never_stalled() {
13997        let dir = tempfile::tempdir().unwrap();
13998        let mut t = task();
13999        t.start("run-1".to_owned());
14000        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
14001        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
14002        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14003    }
14004
14005    #[test]
14006    fn a_long_running_task_with_no_live_daemon_is_stalled() {
14007        let dir = tempfile::tempdir().unwrap();
14008        let mut t = task();
14009        t.start("run-1".to_owned());
14010        t.updated_at = Timestamp::now()
14011            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14012        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14013        assert_eq!(
14014            stalled_tasks(
14015                &Queue::at(dir.path().join("q")),
14016                dir.path(),
14017                Timestamp::now()
14018            )
14019            .len(),
14020            0,
14021            "the task was never written to this queue"
14022        );
14023    }
14024
14025    #[test]
14026    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14027        let dir = tempfile::tempdir().unwrap();
14028        let mut t = task();
14029        t.id = "20260903-080340-0167".to_owned();
14030        t.start("20260903-080619-01c2".to_owned());
14031        t.updated_at = Timestamp::now()
14032            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14033
14034        let mut status = Status::new();
14035        status.current = vec![Current {
14036            worker: None,
14037            task: t.id.clone(),
14038            run: "20260903-080619-01c2".to_owned(),
14039        }];
14040        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14041
14042        assert!(
14043            !is_stalled(&t, dir.path(), Timestamp::now()),
14044            "a live daemon's own heartbeat rules out stalled, however long the task has run"
14045        );
14046    }
14047
14048    /// Rewrite a task's `updated_at` on disk directly, bypassing
14049    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
14050    /// a fixture look like it has genuinely been `running` for a while.
14051    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14052        let path = queue.path_of(id);
14053        let body = std::fs::read_to_string(&path).unwrap();
14054        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14055        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14056        v["updated_at"] = serde_json::Value::String(old.to_string());
14057        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14058    }
14059
14060    #[test]
14061    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14062        // The realistic `poll()` ordering, not `is_stalled` in isolation:
14063        // `reclaim_orphaned_running` runs first, on every poll, and settles
14064        // any `running` task whose claim it can actually take. For most
14065        // crashes that is immediate - a dead pid is proof enough for
14066        // `sweep_stale_claims` to drop the lock the same tick, and the very
14067        // next claim attempt succeeds. But a lock whose pid cannot be parsed
14068        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
14069        // `sweep_stale_claims`'s own doc), so the lock - and the claim
14070        // failure behind it - can legitimately outlive many polls. This is
14071        // exactly the gap `stalled_tasks` exists to surface well before that
14072        // six-hour sweep would: reclaim leaves the task `running`, and it
14073        // must still reach the conductor as stalled.
14074        let dir = tempfile::tempdir().unwrap();
14075        let queue = Queue::at(dir.path().join("queue"));
14076        let home = dir.path().join("home");
14077
14078        let mut t = task();
14079        t.id = "20260101-000001-lock".to_owned();
14080        t.start("run-1".to_owned());
14081        queue.put(&mut t).unwrap();
14082        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14083        std::fs::write(
14084            dir.path().join("queue").join(format!("{}.lock", t.id)),
14085            "not a pid",
14086        )
14087        .unwrap();
14088
14089        let now = Timestamp::now();
14090        assert!(
14091            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14092            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14093             and reclaim must leave the task alone"
14094        );
14095        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14096
14097        let stalled = stalled_tasks(&queue, &home, now);
14098        assert_eq!(
14099            stalled.len(),
14100            1,
14101            "reclaim's inability to claim it yet must not hide it from the conductor"
14102        );
14103        assert_eq!(stalled[0].id, t.id);
14104    }
14105
14106    #[test]
14107    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14108        let dir = tempfile::tempdir().unwrap();
14109        crate::run::set_home(dir.path().join("run-home"));
14110        let queue = Queue::at(dir.path().join("queue"));
14111        let home = dir.path().join("home");
14112        let questions = Questions::at(dir.path().join("questions"));
14113
14114        let mut t = task();
14115        t.id = "20260101-000003-dead".to_owned();
14116        t.start("missing-run".to_owned());
14117        queue.put(&mut t).unwrap();
14118        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14119
14120        // This is the real poll ordering: retain the deterministic stalled
14121        // input before a claim proves the owner is gone and reclaims it.
14122        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14123        assert_eq!(
14124            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14125            [&t.id]
14126        );
14127        assert_eq!(
14128            reclaim_orphaned_running(&queue, 2, &Default::default()),
14129            [t.id.clone()]
14130        );
14131        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14132
14133        // Reclaim drops its guard before conductor decisions are applied, so
14134        // the decision for the captured stalled input has a real write path.
14135        crate::conduct::apply(
14136            &queue,
14137            &questions,
14138            &crate::conduct::Verdict {
14139                decisions: vec![crate::conduct::Decision {
14140                    id: t.id.clone(),
14141                    recovery: Some(crate::conduct::Recovery::Requeue),
14142                    ..crate::conduct::Decision::default()
14143                }],
14144            },
14145        )
14146        .unwrap();
14147        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14148    }
14149
14150    #[test]
14151    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14152        let dir = tempfile::tempdir().unwrap();
14153        let queue = Queue::at(dir.path().join("queue"));
14154        let home = dir.path().join("home");
14155
14156        let mut fresh = task();
14157        fresh.id = "20260101-000001-aaaa".to_owned();
14158        fresh.start("run-1".to_owned());
14159        queue.put(&mut fresh).unwrap();
14160
14161        let mut old = task();
14162        old.id = "20260101-000002-bbbb".to_owned();
14163        old.start("run-2".to_owned());
14164        queue.put(&mut old).unwrap();
14165        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14166
14167        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14168        assert_eq!(stalled.len(), 1);
14169        assert_eq!(stalled[0].id, old.id);
14170    }
14171
14172    #[test]
14173    fn queued_and_finished_task_views_partition_by_status() {
14174        let dir = tempfile::tempdir().unwrap();
14175        let queue = Queue::at(dir.path().join("queue"));
14176
14177        let mut queued = task();
14178        queued.id = "20260101-000001-aaaa".to_owned();
14179        queue.put(&mut queued).unwrap();
14180
14181        let mut failed = task();
14182        failed.id = "20260101-000002-bbbb".to_owned();
14183        failed.start("run-1".to_owned());
14184        failed.fail("gate red", 5);
14185        queue.put(&mut failed).unwrap();
14186
14187        let mut held = task();
14188        held.id = "20260101-000003-cccc".to_owned();
14189        held.hold_machine(None);
14190        queue.put(&mut held).unwrap();
14191
14192        let mut running = task();
14193        running.id = "20260101-000004-dddd".to_owned();
14194        running.start("run-2".to_owned());
14195        queue.put(&mut running).unwrap();
14196
14197        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14198        assert_eq!(queued_ids, [queued.id.clone()]);
14199
14200        let mut finished_ids: Vec<String> =
14201            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14202        finished_ids.sort_unstable();
14203        let mut want = vec![failed.id.clone(), held.id.clone()];
14204        want.sort_unstable();
14205        assert_eq!(finished_ids, want);
14206    }
14207
14208    #[test]
14209    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14210        for short in [false, true] {
14211            let dir = tempfile::tempdir().unwrap();
14212            let queue = Queue::at(dir.path().join("queue"));
14213            let questions = ask::Questions::at(dir.path().join("questions"));
14214            let mut running = task();
14215            running.id = "20261013-192213-feb2".into();
14216            running.start("existing-run".into());
14217            queue.put(&mut running).unwrap();
14218            let mut middle = task();
14219            middle.id = "20261013-193611-ca5b".into();
14220            middle.block(
14221                vec![if short {
14222                    "feb2".into()
14223                } else {
14224                    running.id.clone()
14225                }],
14226                None,
14227            );
14228            queue.put(&mut middle).unwrap();
14229            let mut waiting = task();
14230            waiting.id = "20261013-202849-ee37".into();
14231            waiting.block(
14232                vec![if short {
14233                    "ca5b".into()
14234                } else {
14235                    middle.id.clone()
14236                }],
14237                Some("wait for implementation".into()),
14238            );
14239            queue.put(&mut waiting).unwrap();
14240            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14241            let inv = crate::blockers::Inventory::load(&queue, &questions);
14242            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14243            assert!(inv.stuck().is_empty());
14244            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14245            assert!(report.quarantined.is_empty());
14246            assert!(report.asked.is_empty());
14247            resolve_blockers(&queue, &questions);
14248            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14249            assert!(questions.list().is_empty());
14250            // Finishing the transitive prerequisite alone does not satisfy
14251            // the task's direct dependency.
14252            running.succeed(CompletionContext::new(
14253                CompletionActor::DaemonSettle,
14254                None,
14255                dir.path(),
14256                &running,
14257            ));
14258            queue.put(&mut running).unwrap();
14259            resolve_blockers(&queue, &questions);
14260            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14261            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14262            middle = queue.get(&middle.id).unwrap();
14263            middle.succeed(CompletionContext::new(
14264                CompletionActor::DaemonSettle,
14265                None,
14266                dir.path(),
14267                &middle,
14268            ));
14269            queue.put(&mut middle).unwrap();
14270            resolve_blockers(&queue, &questions);
14271            let after = queue.get(&waiting.id).unwrap();
14272            assert_eq!(after.status, TaskStatus::Queued);
14273            assert!(after.blocked_by.is_empty());
14274            assert_eq!(after.instruction, waiting.instruction);
14275        }
14276    }
14277
14278    #[test]
14279    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14280        for future_schema in [false, true] {
14281            let name = "20261013-193611-ca5b";
14282            let mut future = task();
14283            future.id = name.into();
14284            future.schema = crate::queue::SCHEMA + 1;
14285            let contents = if future_schema {
14286                serde_json::to_string(&future).unwrap()
14287            } else {
14288                "corrupt".into()
14289            };
14290            let dir = tempfile::tempdir().unwrap();
14291            let queue = Queue::at(dir.path().join("queue"));
14292            let questions = ask::Questions::at(dir.path().join("questions"));
14293            let mut waiting = task();
14294            waiting.id = "20261013-202849-ee37".into();
14295            waiting.block(vec!["ca5b".into()], None);
14296            queue.put(&mut waiting).unwrap();
14297            std::fs::write(queue.path_of(name), contents).unwrap();
14298            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14299            assert!(
14300                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14301            );
14302            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14303            assert!(report.asked.is_empty());
14304            resolve_blockers(&queue, &questions);
14305            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14306            assert!(questions.list().is_empty());
14307        }
14308        let dir = tempfile::tempdir().unwrap();
14309        let queue = Queue::at(dir.path().join("queue"));
14310        let questions = ask::Questions::at(dir.path().join("questions"));
14311        let mut waiting = task();
14312        waiting.id = "20261013-202849-ee37".into();
14313        waiting.block(vec!["ca5b".into()], None);
14314        queue.put(&mut waiting).unwrap();
14315        let mut done = task();
14316        done.id = "20261013-193611-ca5b".into();
14317        done.succeed(CompletionContext::new(
14318            CompletionActor::Cli,
14319            None,
14320            dir.path(),
14321            &done,
14322        ));
14323        queue.put(&mut done).unwrap();
14324        // An unreadable second match must not disappear from uniqueness
14325        // checks just because Queue::list skips it.
14326        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14327        assert!(queue.get("ca5b").is_err());
14328        assert_eq!(
14329            crate::queue::dependency(&queue, &questions, "ca5b"),
14330            crate::queue::Dependency::Ambiguous
14331        );
14332        resolve_blockers(&queue, &questions);
14333        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14334        assert!(report.asked.is_empty());
14335        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14336        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14337    }
14338
14339    #[test]
14340    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14341        for held in [false, true] {
14342            for question in [false, true] {
14343                for reference in ["ca5b", "20261013-193611-ca5b"] {
14344                    let dir = tempfile::tempdir().unwrap();
14345                    let queue = Queue::at(dir.path().join("queue"));
14346                    let questions = ask::Questions::at(dir.path().join("questions"));
14347                    let mut prerequisite = task();
14348                    prerequisite.id = "20261013-193611-ca5b".into();
14349                    prerequisite.start("existing-run".into());
14350                    queue.put(&mut prerequisite).unwrap();
14351                    let mut waiting = task();
14352                    waiting.id = "20261013-202849-ee37".into();
14353                    if held {
14354                        waiting.hold_machine(Some("waiting for separate consent".into()));
14355                    }
14356                    queue.put(&mut waiting).unwrap();
14357                    let reason = "Deleting saved data requires separate owner consent";
14358                    crate::conduct::apply(
14359                        &queue,
14360                        &questions,
14361                        &crate::conduct::Verdict {
14362                            decisions: vec![crate::conduct::Decision {
14363                                id: waiting.id.clone(),
14364                                blocked_by: vec![reference.into()],
14365                                question: question.then(|| "May the saved data be deleted?".into()),
14366                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14367                                reason: Some(reason.into()),
14368                                ..crate::conduct::Decision::default()
14369                            }],
14370                        },
14371                    )
14372                    .unwrap();
14373                    let before = queue.get(&waiting.id).unwrap();
14374                    if question {
14375                        assert_eq!(before.status, TaskStatus::Blocked);
14376                        let q = questions.get(&before.blocked_by[0]).unwrap();
14377                        assert_eq!(q.summary, "May the saved data be deleted?");
14378                        assert!(q.status.open());
14379                    } else {
14380                        assert_eq!(before.status, TaskStatus::Held);
14381                        let recorded_reason = before.hold_reason.as_deref().unwrap();
14382                        assert!(recorded_reason.starts_with(reason));
14383                        if held {
14384                            assert!(recorded_reason.contains("waiting for separate consent"));
14385                        }
14386                    }
14387                    prerequisite.succeed(CompletionContext::new(
14388                        CompletionActor::DaemonSettle,
14389                        None,
14390                        dir.path(),
14391                        &prerequisite,
14392                    ));
14393                    queue.put(&mut prerequisite).unwrap();
14394                    resolve_blockers(&queue, &questions);
14395                    let after = queue.get(&waiting.id).unwrap();
14396                    assert_eq!(after.status, before.status);
14397                    assert_eq!(after.blocked_by, before.blocked_by);
14398                    assert_eq!(after.hold_reason, before.hold_reason);
14399                    assert_eq!(after.instruction, waiting.instruction);
14400                    if question {
14401                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14402                    }
14403                    assert!(
14404                        queue.next_runnable().is_none(),
14405                        "dependency completion is not consent"
14406                    );
14407                }
14408            }
14409        }
14410    }
14411
14412    #[test]
14413    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14414        let dir = tempfile::tempdir().unwrap();
14415        let queue = Queue::at(dir.path().join("queue"));
14416        let questions = ask::Questions::at(dir.path().join("questions"));
14417
14418        let mut dep = task();
14419        dep.id = "20260101-000001-dep0".to_owned();
14420        dep.succeed(CompletionContext::new(
14421            CompletionActor::DaemonSettle,
14422            None,
14423            dir.path(),
14424            &dep,
14425        ));
14426        queue.put(&mut dep).unwrap();
14427
14428        let mut still_going = task();
14429        still_going.id = "20260101-000002-dep1".to_owned();
14430        queue.put(&mut still_going).unwrap();
14431
14432        let mut blocked = task();
14433        blocked.id = "20260101-000003-main".to_owned();
14434        blocked.block(
14435            vec![dep.id.clone(), still_going.id.clone()],
14436            Some("waits on both".to_owned()),
14437        );
14438        queue.put(&mut blocked).unwrap();
14439
14440        resolve_blockers(&queue, &questions);
14441
14442        let after = queue.get(&blocked.id).unwrap();
14443        assert_eq!(
14444            after.status,
14445            TaskStatus::Blocked,
14446            "one dependency is still outstanding"
14447        );
14448        assert_eq!(after.blocked_by, [still_going.id.clone()]);
14449    }
14450
14451    #[test]
14452    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14453        let dir = tempfile::tempdir().unwrap();
14454        let queue = Queue::at(dir.path().join("queue"));
14455        let questions = ask::Questions::at(dir.path().join("questions"));
14456
14457        let mut q = crate::ask::Question::new(
14458            "20260101-000001-main".to_owned(),
14459            crate::conduct::NODE.to_owned(),
14460            "conduct".to_owned(),
14461            "Which backend?".to_owned(),
14462            String::new(),
14463            Vec::new(),
14464        );
14465        questions.put(&mut q).unwrap();
14466        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14467            .unwrap();
14468        questions.put(&mut q).unwrap();
14469
14470        let mut blocked = task();
14471        blocked.id = "20260101-000001-main".to_owned();
14472        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14473        queue.put(&mut blocked).unwrap();
14474
14475        resolve_blockers(&queue, &questions);
14476
14477        let after = queue.get(&blocked.id).unwrap();
14478        assert_eq!(
14479            after.status,
14480            TaskStatus::Queued,
14481            "the only blocker resolved"
14482        );
14483        assert_eq!(after.answers.len(), 1);
14484        assert_eq!(after.answers[0].question, "Which backend?");
14485        assert_eq!(after.answers[0].answer, "SQLite");
14486
14487        // And the run this task starts next is told about it.
14488        let instruction = instruction_for(&after);
14489        assert!(instruction.contains("Which backend?"));
14490        assert!(instruction.contains("SQLite"));
14491    }
14492
14493    #[test]
14494    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14495        let dir = tempfile::tempdir().unwrap();
14496        let queue = Queue::at(dir.path().join("queue"));
14497        let questions = ask::Questions::at(dir.path().join("questions"));
14498
14499        let mut q = crate::ask::Question::new(
14500            "20260101-000001-main".to_owned(),
14501            crate::conduct::NODE.to_owned(),
14502            "conduct".to_owned(),
14503            "Is the setup done?".to_owned(),
14504            String::new(),
14505            Vec::new(),
14506        );
14507        q.abandon("no answer within 60s of asking");
14508        questions.put(&mut q).unwrap();
14509
14510        let mut blocked = task();
14511        blocked.id = "20260101-000001-main".to_owned();
14512        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14513        queue.put(&mut blocked).unwrap();
14514
14515        resolve_blockers(&queue, &questions);
14516
14517        let after = queue.get(&blocked.id).unwrap();
14518        assert_eq!(
14519            after.status,
14520            TaskStatus::Held,
14521            "never left blocked on nothing"
14522        );
14523        assert!(!after.operator_held(), "a machine hold, for triage");
14524        assert!(
14525            after
14526                .hold_reason
14527                .as_deref()
14528                .unwrap_or_default()
14529                .contains("went unanswered")
14530        );
14531    }
14532
14533    #[test]
14534    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14535        // Reproduces the reported bug (task 3958): a task held out of
14536        // attempts, blocked on a `crate::conduct` follow-up question, must
14537        // come back `held` once that question is answered - never `queued`,
14538        // whatever the answer said - or it silently re-enters the
14539        // competition queue with its attempts already exhausted.
14540        let dir = tempfile::tempdir().unwrap();
14541        let queue = Queue::at(dir.path().join("queue"));
14542        let questions = ask::Questions::at(dir.path().join("questions"));
14543
14544        let mut q = crate::ask::Question::new(
14545            "20260101-000001-main".to_owned(),
14546            crate::conduct::NODE.to_owned(),
14547            "conduct".to_owned(),
14548            "How should this be handled?".to_owned(),
14549            String::new(),
14550            Vec::new(),
14551        );
14552        questions.put(&mut q).unwrap();
14553        q.answer(crate::ask::Answer::Text(
14554            "leave it held, a human will look at it later".to_owned(),
14555        ))
14556        .unwrap();
14557        questions.put(&mut q).unwrap();
14558
14559        let mut held = task();
14560        held.id = "20260101-000001-main".to_owned();
14561        held.hold_machine(Some("out of attempts".to_owned()));
14562        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14563        queue.put(&mut held).unwrap();
14564
14565        resolve_blockers(&queue, &questions);
14566
14567        let after = queue.get(&held.id).unwrap();
14568        assert_eq!(after.status, TaskStatus::Held);
14569        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14570        assert_eq!(
14571            after.answers[0].answer,
14572            "leave it held, a human will look at it later"
14573        );
14574    }
14575
14576    #[test]
14577    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14578        let dir = tempfile::tempdir().unwrap();
14579        let queue = Queue::at(dir.path().join("queue"));
14580        let questions = ask::Questions::at(dir.path().join("questions"));
14581        let mut dep = task();
14582        dep.id = "20260101-000001-gone".to_owned();
14583        queue.put(&mut dep).unwrap();
14584        let mut blocked = task();
14585        blocked.id = "20260101-000003-main".to_owned();
14586        blocked.block(vec![dep.id.clone()], None);
14587        queue.put(&mut blocked).unwrap();
14588
14589        // Claimed, so `remove` cannot rewrite it and the resolver must.
14590        let claim = queue.claim(&blocked.id).unwrap();
14591        queue.remove(&dep.id, false, &questions).unwrap();
14592        drop(claim);
14593        resolve_blockers(&queue, &questions);
14594
14595        let after = queue.get(&blocked.id).unwrap();
14596        assert_eq!(after.status, TaskStatus::Queued);
14597        assert!(after.blocked_by.is_empty());
14598    }
14599
14600    #[test]
14601    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14602        // Reproduces the reported bug: a task blocked on a task id that was
14603        // removed (`magi task rm`, or deleted by hand) can never see that id
14604        // reach `Done`, so the ordinary per-id loop has nothing to notice and
14605        // would otherwise leave the task `blocked` forever with no way for an
14606        // operator to find out why.
14607        let dir = tempfile::tempdir().unwrap();
14608        let queue = Queue::at(dir.path().join("queue"));
14609        let questions = ask::Questions::at(dir.path().join("questions"));
14610
14611        let mut still_going = task();
14612        still_going.id = "20260101-000002-dep1".to_owned();
14613        queue.put(&mut still_going).unwrap();
14614
14615        let mut blocked = task();
14616        blocked.id = "20260101-000003-main".to_owned();
14617        blocked.block(
14618            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14619            Some("waits on both".to_owned()),
14620        );
14621        queue.put(&mut blocked).unwrap();
14622
14623        resolve_blockers(&queue, &questions);
14624
14625        let after = queue.get(&blocked.id).unwrap();
14626        assert_eq!(
14627            after.status,
14628            TaskStatus::Held,
14629            "a missing dependency must not leave the task blocked forever"
14630        );
14631        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14632        assert!(after.blocked_by.is_empty());
14633        let reason = after.hold_reason.as_deref().unwrap_or_default();
14634        assert!(
14635            reason.contains("20260101-000001-gone"),
14636            "the missing id must be named so an operator can tell what happened: {reason}"
14637        );
14638        assert!(
14639            reason.contains(&still_going.id),
14640            "the still-valid dependency must not silently vanish from the record: {reason}"
14641        );
14642    }
14643
14644    #[test]
14645    fn instruction_for_is_unchanged_without_any_answers() {
14646        let t = task();
14647        assert_eq!(instruction_for(&t), t.instruction);
14648    }
14649
14650    #[test]
14651    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14652        let dir = tempfile::tempdir().unwrap();
14653        let q = Queue::at(dir.path().join("queue"));
14654        let src = dir.path().join("shot.png");
14655        std::fs::write(&src, "x").unwrap();
14656        let mut t = task();
14657        q.attach(&mut t, &[src]).unwrap();
14658        let paths = task_attachments(&q, &t).unwrap();
14659        assert_eq!(paths.len(), 1);
14660        assert!(paths[0].is_absolute() && paths[0].is_file());
14661        std::fs::remove_file(&paths[0]).unwrap();
14662        let err = task_attachments(&q, &t).unwrap_err().to_string();
14663        assert!(err.contains("shot.png"), "{err}");
14664    }
14665
14666    #[tokio::test]
14667    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14668        let dir = tempfile::tempdir().unwrap();
14669        let queue_path = dir.path().join("queue");
14670        let queue = Queue::at(queue_path.clone());
14671        let mut t = task();
14672        t.source = Source::Agent {
14673            run: "originating-chat".into(),
14674            node: crate::queue::CHAT_NODE.into(),
14675        };
14676        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14677            stage: "config-fetch",
14678            target: "origin/main".into(),
14679        });
14680        record_config_failure(&mut t, &fetch);
14681        t.hold_machine(Some(format!("{fetch:#}")));
14682        let fetch_key = t.chat_notice_due().unwrap();
14683        t.chat_notices.push(fetch_key.clone());
14684        queue.put(&mut t).unwrap();
14685
14686        let queue = Queue::at(queue_path);
14687        let mut t = queue.get(&t.id).unwrap();
14688        let a = dir.path().join("a.toml");
14689        let b = dir.path().join("b.toml");
14690        for (path, text, new_cause) in [
14691            (&a, "[graph", true),
14692            (&a, "[verify", false),
14693            (&a, "[graph]\nimplementers = 'invalid-type'", true),
14694            (&b, "[graph]\nimplementers = 'invalid-type'", true),
14695        ] {
14696            t.release_operator("test", None);
14697            std::fs::write(path, text).unwrap();
14698            let error = Config::discover_fetched(dir.path(), Some(path))
14699                .await
14700                .unwrap_err();
14701            record_config_failure(&mut t, &error);
14702            t.hold_machine(Some(format!("{error:#}")));
14703            let due = t.chat_notice_due();
14704            assert_eq!(due.is_some(), new_cause, "{error:#}");
14705            if let Some(key) = due {
14706                assert_ne!(key, fetch_key);
14707                t.chat_notices.push(key);
14708            }
14709        }
14710        t.succeed(CompletionContext::new(
14711            CompletionActor::DaemonSettle,
14712            None,
14713            dir.path(),
14714            &t,
14715        ));
14716        assert_eq!(
14717            t.chat_notice_due(),
14718            Some(format!(
14719                "done:{}",
14720                t.completion_history.last().unwrap().occurrence
14721            ))
14722        );
14723    }
14724
14725    #[test]
14726    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14727        let dir = tempfile::tempdir().unwrap();
14728        let queue_path = dir.path().join("queue");
14729        let queue = Queue::at(queue_path.clone());
14730        let mut t = task();
14731        t.source = crate::queue::Source::Agent {
14732            run: "originating-chat".into(),
14733            node: crate::queue::CHAT_NODE.into(),
14734        };
14735        let a = dir.path().join("a.png");
14736        let b = dir.path().join("b.png");
14737        std::fs::write(&a, "a").unwrap();
14738        std::fs::write(&b, "b").unwrap();
14739        queue.attach(&mut t, &[a, b]).unwrap();
14740        let paths = task_attachments(&queue, &t).unwrap();
14741        for path in &paths {
14742            std::fs::remove_file(path).unwrap();
14743        }
14744        let missing = task_attachments(&queue, &t).unwrap_err();
14745        t.attempts += 1;
14746        let reason = missing.to_string();
14747        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14748        let first = t.chat_notice_due().expect("first attachment notice");
14749        t.chat_notices.push(first.clone());
14750        queue.put(&mut t).unwrap();
14751
14752        let queue = Queue::at(queue_path.clone());
14753        let mut t = queue.get(&t.id).unwrap();
14754        assert!(t.chat_notice_due().is_none(), "restart does not replay");
14755        t.release_operator("test", None);
14756        t.attempts += 1;
14757        let missing = task_attachments(&queue, &t).unwrap_err();
14758        t.fail_startup_target(
14759            "startup-attachments",
14760            missing.name,
14761            "same missing attachment with regenerated wording",
14762            1,
14763        );
14764        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14765
14766        std::fs::write(&paths[0], "restored").unwrap();
14767        t.release_operator("test", None);
14768        t.attempts += 1;
14769        let missing = task_attachments(&queue, &t).unwrap_err();
14770        let reason = missing.to_string();
14771        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14772        let second = t
14773            .chat_notice_due()
14774            .expect("different attachment must notify");
14775        assert_ne!(first, second);
14776        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14777    }
14778
14779    #[test]
14780    fn resumed_instruction_is_unchanged_without_any_answers() {
14781        let t = task();
14782        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14783    }
14784
14785    #[test]
14786    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14787        let mut t = task();
14788        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14789        // The run's own instruction on disk predates the answer: it is the
14790        // plain original text `Runner::start` saved before the operator was
14791        // ever asked anything.
14792        let old = t.instruction.clone();
14793
14794        let refreshed = resumed_instruction(&old, &t);
14795        assert!(refreshed.starts_with(&old), "the original text is kept");
14796        assert!(refreshed.contains("Which backend?"));
14797        assert!(refreshed.contains("SQLite"));
14798    }
14799
14800    #[test]
14801    fn resumed_instruction_keeps_an_original_answers_heading() {
14802        let mut t = task();
14803        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14804        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14805
14806        let refreshed = resumed_instruction(&t.instruction, &t);
14807
14808        assert!(
14809            refreshed.starts_with(&t.instruction),
14810            "an answers heading in the original instruction is not the appended block"
14811        );
14812        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14813        assert!(refreshed.contains("Which backend?"));
14814        assert!(refreshed.contains("SQLite"));
14815
14816        let repeated = resumed_instruction(&refreshed, &t);
14817        assert_eq!(
14818            repeated, refreshed,
14819            "only the final appended block is refreshed"
14820        );
14821    }
14822
14823    #[test]
14824    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
14825        let mut t = task();
14826        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14827
14828        // A first resume appends the block; a second resume of the same run,
14829        // with no new answer in between, must reproduce exactly the same
14830        // text rather than appending the block a second time.
14831        let once = resumed_instruction(&t.instruction, &t);
14832        let twice = resumed_instruction(&once, &t);
14833        assert_eq!(once, twice);
14834        assert_eq!(once.matches("Which backend?").count(), 1);
14835
14836        // A later answer replaces the block wholesale rather than growing it.
14837        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
14838        let refreshed = resumed_instruction(&once, &t);
14839        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
14840        assert!(refreshed.contains("Which backend?"));
14841        assert!(refreshed.contains("Which cache?"));
14842    }
14843
14844    #[test]
14845    fn prepare_instruction_covers_all_three_starters() {
14846        let mut t = task();
14847        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14848
14849        // Start: a fresh run gets the task text plus every answer so far —
14850        // exactly `instruction_for`.
14851        assert_eq!(
14852            prepare_instruction(&Starter::Start, None, &t),
14853            Some(instruction_for(&t))
14854        );
14855
14856        // Resume: the run's prior instruction is refreshed with the answer,
14857        // not discarded and not left stale.
14858        let old = t.instruction.clone();
14859        assert_eq!(
14860            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
14861            Some(resumed_instruction(&old, &t))
14862        );
14863
14864        // Review: a review-only pass builds its own instruction from the
14865        // branch's history in `crate::graph`, with no task statement at all -
14866        // this boundary must leave it alone.
14867        assert_eq!(
14868            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
14869            None
14870        );
14871    }
14872
14873    #[test]
14874    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
14875        assert_eq!(
14876            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
14877            Starter::Review("magi/eba2/A".to_owned())
14878        );
14879    }
14880
14881    #[test]
14882    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
14883        assert_eq!(
14884            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
14885            Starter::Start,
14886            "a vanished review branch must not fall back to resuming the old run either"
14887        );
14888    }
14889
14890    #[test]
14891    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
14892        let mut t = task();
14893        t.start("old-run".to_owned());
14894        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
14895        t.release();
14896        let branch = t.review_branch.take();
14897        assert_eq!(
14898            choose_starter(branch.as_deref(), true, Some("old-run")),
14899            Starter::Review("magi/eba2/A".to_owned()),
14900            "a review wins over resuming the old run"
14901        );
14902    }
14903
14904    #[test]
14905    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
14906        assert_eq!(
14907            choose_starter(None, false, Some("some-run")),
14908            Starter::Resume("some-run".to_owned())
14909        );
14910        assert_eq!(choose_starter(None, false, None), Starter::Start);
14911    }
14912
14913    #[test]
14914    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
14915        let mut released = task();
14916        released.start("stalled-run".to_owned());
14917        released.requeue();
14918        let unfinished = (!released.fresh_start)
14919            .then(|| Some("stalled-run".to_owned()))
14920            .flatten();
14921        assert_eq!(
14922            choose_starter(None, false, unfinished.as_deref()),
14923            Starter::Start,
14924            "release keeps run history but must not resume it"
14925        );
14926        assert_eq!(released.runs, ["stalled-run"]);
14927    }
14928
14929    #[test]
14930    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
14931        let dir = tempfile::tempdir().unwrap();
14932        let queue = Queue::at(dir.path().join("queue"));
14933        let mut state = run_state(RunStatus::Blocked);
14934        state.merge_decision = Some(crate::merge_decision::Decision {
14935            question: "hold-inquiry".into(),
14936            target: crate::merge_decision::Target {
14937                pr: "https://example.test/pull/1".into(),
14938                head: "reviewed-head".into(),
14939                language: "en".into(),
14940            },
14941            choice: land::HOLD.into(),
14942            closed: false,
14943            replacement_run: None,
14944            replacement_pr: None,
14945        });
14946        let mut t = task();
14947        t.start(state.id.clone());
14948        settle_and_diagnose(
14949            &mut t,
14950            Verdict {
14951                status: RunStatus::Blocked,
14952                left_pr: true,
14953                quota_hit: false,
14954                parked: false,
14955                no_viable_candidates: false,
14956            },
14957            "held",
14958            2,
14959            &state,
14960        );
14961        queue.put(&mut t).unwrap();
14962        t.release_operator("chat", None);
14963        t.edit("revised".into(), "revised instruction".into())
14964            .unwrap();
14965        queue.put(&mut t).unwrap();
14966        drop(state);
14967        assert_eq!(
14968            queue
14969                .get(&t.id)
14970                .unwrap()
14971                .decision_effects
14972                .get("hold-inquiry"),
14973            Some(&format!("decision: {}", land::HOLD))
14974        );
14975    }
14976
14977    fn stopped_public_run(status: RunStatus) -> RunState {
14978        let mut state = run_state(status);
14979        state.driver_exited = true;
14980        state.config.graph.land = true;
14981        state.config.graph.review_rounds = 1;
14982        state.reviews = vec![review_round(1)];
14983        state.merge = Some(crate::run::MergeOutcome {
14984            mode: MergeMode::Pr,
14985            ok: false,
14986            detail: "landing stopped".into(),
14987            empty: false,
14988        });
14989        state.pr = Some(crate::run::PrRecord {
14990            url: "https://example.test/pull/1".into(),
14991            number: 1,
14992            state: "open".into(),
14993            checks: "red".into(),
14994            round: 1,
14995            rounds: 1,
14996            red_at_merge: Vec::new(),
14997        });
14998        state
14999    }
15000
15001    #[test]
15002    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15003        for status in [RunStatus::Blocked, RunStatus::Gating] {
15004            let home = tempfile::tempdir().unwrap();
15005            let mut state = stopped_public_run(status);
15006            state.save_under(home.path()).unwrap();
15007            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15008            assert!(!exhausted_review_budget(&state));
15009            let mut task = held_task_with(&state.id);
15010            task.release();
15011            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15012            assert_eq!(
15013                choose_starter(None, false, unfinished.as_deref()),
15014                Starter::Resume(state.id.clone())
15015            );
15016            let question = action_question(&state.id, resume_action(&state.id));
15017            assert_eq!(
15018                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15019                    state.clone()
15020                )),
15021                ActionDecision::Resume(state.id.clone())
15022            );
15023            // The control-plane command uses this same preflight before pinning.
15024            assert_eq!(
15025                crate::resume::validate(home.path(), &state.id).unwrap().id,
15026                state.id
15027            );
15028            let queue = Queue::at(home.path().join("queue"));
15029            let mut controlled = Task::new(
15030                "resume land".into(),
15031                state.instruction.clone(),
15032                state.repo.clone(),
15033                Source::Agent {
15034                    run: "talk".into(),
15035                    node: crate::queue::CHAT_NODE.into(),
15036                },
15037            );
15038            controlled.runs.push(state.id.clone());
15039            controlled.hold_machine(Some("land stopped".into()));
15040            queue.put(&mut controlled).unwrap();
15041            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15042            assert_eq!(resumed.status, TaskStatus::Queued);
15043            assert_eq!(
15044                resumed.resume_override.unwrap().pinned_run,
15045                Some(state.id.clone())
15046            );
15047            assert_eq!(resumed.attempts, 0);
15048        }
15049    }
15050
15051    #[test]
15052    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15053        for review_rounds in [0, 1] {
15054            let home = tempfile::tempdir().unwrap();
15055            let mut state = run_state(RunStatus::Blocked);
15056            state.config.graph.review_rounds = review_rounds;
15057            if review_rounds > 0 {
15058                let mut review = review_round(1);
15059                review.clean = true;
15060                state.reviews = vec![review];
15061            }
15062            state.gate_ran = true;
15063            state.gate = vec![crate::run::CommandOutcome {
15064                command: "verify".into(),
15065                code: Some(1),
15066                output_tail: "gate failed after repair budget exhausted".into(),
15067                duration_ms: 0,
15068                resource_blocked: false,
15069                ..Default::default()
15070            }];
15071            state.save_under(home.path()).unwrap();
15072            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15073            assert!(exhausted_review_budget(&state));
15074            let mut task = held_task_with(&state.id);
15075            task.release();
15076            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15077            let question = action_question(&state.id, resume_action(&state.id));
15078            assert_ne!(
15079                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15080                    state.clone()
15081                )),
15082                ActionDecision::Resume(state.id.clone())
15083            );
15084            let error = crate::resume::validate(home.path(), &state.id)
15085                .unwrap_err()
15086                .to_string();
15087            assert!(!error.contains("review budget exhausted"), "{error}");
15088            assert!(
15089                error.contains(if review_rounds == 0 {
15090                    "review is disabled"
15091                } else {
15092                    "gate already ran"
15093                }),
15094                "{error}"
15095            );
15096
15097            // An unexecuted gate still has work to do with or without reviews.
15098            state.gate_ran = false;
15099            state.gate.clear();
15100            assert!(!exhausted_review_budget(&state));
15101            assert_eq!(
15102                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15103                Some(state.id)
15104            );
15105        }
15106    }
15107
15108    #[test]
15109    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15110        let home = tempfile::tempdir().unwrap();
15111        let mut state = run_state(RunStatus::Blocked);
15112        state.config.graph.review_rounds = 1;
15113        let mut unresolved = review_round(1);
15114        unresolved.blocking = 1;
15115        unresolved.e2e.push(crate::run::CommandOutcome {
15116            command: "verify".into(),
15117            code: Some(1),
15118            output_tail: "previous verification failed".into(),
15119            duration_ms: 0,
15120            resource_blocked: false,
15121            artifact: None,
15122            failure_evidence: None,
15123            rerun_comparison: None,
15124        });
15125        state.reviews.push(unresolved);
15126        state.base_sync = Some(crate::run::BaseSync {
15127            tip: "base".into(),
15128            behind: 1,
15129            attempts: 0,
15130            conflict: None,
15131            already_in: None,
15132        });
15133        state.reserve_base_operation("winner", "base");
15134        state.resource_block = Some(crate::run::ResourceBlock {
15135            cause: crate::run::ResourceBlockCause::Other,
15136            node: "rebase".into(),
15137            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15138            detail: "recording exec failed".into(),
15139            at: jiff::Timestamp::now(),
15140        });
15141        state.save_under(home.path()).unwrap();
15142        assert_eq!(
15143            crate::resume::validate(home.path(), &state.id).unwrap().id,
15144            state.id
15145        );
15146        assert_eq!(
15147            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15148            crate::repair_budget::legacy::Class::SequencerInfrastructure
15149        );
15150        state.finish_base_operation(None);
15151        state.save_under(home.path()).unwrap();
15152        assert!(crate::resume::validate(home.path(), &state.id).is_err());
15153    }
15154
15155    #[test]
15156    fn resource_blocked_verification_resumes_the_same_run() {
15157        for (kind, stage) in [
15158            ("cache", "clean"),
15159            ("coordination", "clean"),
15160            ("cache", "review-e2e"),
15161            ("coordination", "no-reviews"),
15162            ("coordination", "handoff"),
15163        ] {
15164            let home = tempfile::tempdir().unwrap();
15165            let mut state = run_state(RunStatus::Blocked);
15166            state.config.graph.review_rounds = 1;
15167            let mut review = review_round(1);
15168            review.clean = true;
15169            state.reviews = vec![review];
15170            if stage == "review-e2e" {
15171                let review = &mut state.reviews[0];
15172                review.clean = false;
15173                review.blocking = 1;
15174                review.e2e = vec![crate::run::CommandOutcome {
15175                    command: "verify".into(),
15176                    code: None,
15177                    output_tail: "resource wait expired".into(),
15178                    duration_ms: 0,
15179                    resource_blocked: true,
15180                    ..Default::default()
15181                }];
15182            } else if stage == "no-reviews" {
15183                state.config.graph.review_rounds = 0;
15184                state.reviews.clear();
15185            } else if stage == "handoff" {
15186                // A completed final verification can hand off to the gate
15187                // even when the review still carries contested findings.
15188                let review = &mut state.reviews[0];
15189                review.clean = false;
15190                review.blocking = 1;
15191                review.e2e = vec![crate::run::CommandOutcome {
15192                    command: "verify".into(),
15193                    code: Some(0),
15194                    output_tail: String::new(),
15195                    duration_ms: 0,
15196                    resource_blocked: false,
15197                    ..Default::default()
15198                }];
15199            }
15200            state.gate_ran = false;
15201            state.resource_block = Some(crate::run::ResourceBlock {
15202                cause: crate::run::ResourceBlockCause::Other,
15203                node: if stage == "review-e2e" {
15204                    "review"
15205                } else {
15206                    "gate"
15207                }
15208                .into(),
15209                kind: kind.into(),
15210                detail: "resource wait expired".into(),
15211                at: jiff::Timestamp::now(),
15212            });
15213            state.save_under(home.path()).unwrap();
15214            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15215            assert!(!exhausted_review_budget(&state));
15216            let mut task = held_task_with(&state.id);
15217            task.release();
15218            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15219            assert_eq!(
15220                choose_starter(None, false, unfinished.as_deref()),
15221                Starter::Resume(state.id.clone())
15222            );
15223            let question = action_question(&state.id, resume_action(&state.id));
15224            assert_eq!(
15225                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15226                    state.clone()
15227                )),
15228                ActionDecision::Resume(state.id.clone())
15229            );
15230            assert_eq!(
15231                crate::resume::validate(home.path(), &state.id).unwrap().id,
15232                state.id
15233            );
15234            let queue = Queue::at(home.path().join("queue"));
15235            let mut controlled = Task::new(
15236                "resume verification".into(),
15237                state.instruction.clone(),
15238                state.repo.clone(),
15239                Source::Agent {
15240                    run: "talk".into(),
15241                    node: crate::queue::CHAT_NODE.into(),
15242                },
15243            );
15244            controlled.runs.push(state.id.clone());
15245            controlled.hold_machine(Some("verification resource unavailable".into()));
15246            queue.put(&mut controlled).unwrap();
15247            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15248            assert_eq!(resumed.status, TaskStatus::Queued);
15249            assert_eq!(
15250                resumed.resume_override.unwrap().pinned_run,
15251                Some(state.id.clone())
15252            );
15253            assert_eq!(resumed.attempts, 0);
15254
15255            // A genuinely unresolved final review still exhausts the budget.
15256            state.config.graph.review_rounds = 1;
15257            let mut unresolved = review_round(1);
15258            unresolved.blocking = 1;
15259            state.reviews = vec![unresolved];
15260            state.resource_block = None;
15261            state.save_under(home.path()).unwrap();
15262            assert!(exhausted_review_budget(&state));
15263            assert!(crate::resume::validate(home.path(), &state.id).is_err());
15264        }
15265    }
15266
15267    #[tokio::test]
15268    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15269        if !crate::standalone_test(
15270            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15271        ) {
15272            return;
15273        }
15274        let home = tempfile::tempdir().unwrap();
15275        let mut owner = stopped_public_run(RunStatus::Blocked);
15276        owner.save_under(home.path()).unwrap();
15277        let history = vec![owner.id.clone()];
15278        let repo = owner.repo.clone();
15279        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15280        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15281        let initial =
15282            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15283        assert!(
15284            initial.is_pending(),
15285            "a busy record must not hold or resume the task"
15286        );
15287        owner.retired_to = Some("20260101-000001-bbbb".into());
15288        owner.save_under(home.path()).unwrap();
15289        drop(lock);
15290        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15291            .await
15292            .expect("ownership lock released")
15293            .expect("read settled owner");
15294        assert!(
15295            result.is_none(),
15296            "the retired owner must not be resumed from a stale read"
15297        );
15298    }
15299
15300    #[tokio::test]
15301    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15302        if !crate::standalone_test(
15303            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15304        ) {
15305            return;
15306        }
15307        let home = tempfile::tempdir().unwrap();
15308        let mut owner = stopped_public_run(RunStatus::Blocked);
15309        let repo = tempfile::tempdir().unwrap();
15310        crate::git::git(repo.path(), &["init"]).await.unwrap();
15311        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15312        owner.id = "20260101-000000-aaaa".into();
15313        owner.save_under(home.path()).unwrap();
15314        let mut successor = run_state(RunStatus::Blocked);
15315        successor.id = "20260101-000001-bbbb".into();
15316        successor.save_under(home.path()).unwrap();
15317        let runs = vec![owner.id.clone(), successor.id.clone()];
15318        assert_eq!(
15319            public_resume_owner(home.path(), &runs, &owner.repo)
15320                .await
15321                .unwrap()
15322                .unwrap()
15323                .id,
15324            owner.id
15325        );
15326        let subdir = owner.repo.join("nested");
15327        std::fs::create_dir(&subdir).unwrap();
15328        assert_eq!(
15329            public_resume_owner(home.path(), &runs, &subdir)
15330                .await
15331                .unwrap()
15332                .unwrap()
15333                .id,
15334            owner.id
15335        );
15336        #[cfg(unix)]
15337        {
15338            let alias = home.path().join("repo-alias");
15339            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15340            assert_eq!(
15341                public_resume_owner(home.path(), &runs, &alias.join("nested"))
15342                    .await
15343                    .unwrap()
15344                    .unwrap()
15345                    .id,
15346                owner.id
15347            );
15348        }
15349        let different = tempfile::tempdir().unwrap();
15350        crate::git::git(different.path(), &["init"]).await.unwrap();
15351        assert!(
15352            public_resume_owner(home.path(), &runs, different.path())
15353                .await
15354                .is_err()
15355        );
15356        std::fs::remove_file(
15357            home.path()
15358                .join("runs")
15359                .join(&successor.id)
15360                .join("run.json"),
15361        )
15362        .unwrap();
15363        assert!(
15364            public_resume_owner(home.path(), &runs, &owner.repo)
15365                .await
15366                .is_err()
15367        );
15368    }
15369
15370    #[test]
15371    fn an_ordinary_release_keeps_a_resumable_run_available() {
15372        let mut released = task();
15373        released.start("stalled-run".to_owned());
15374        released.release();
15375        let unfinished = (!released.fresh_start)
15376            .then(|| Some("stalled-run".to_owned()))
15377            .flatten();
15378        assert_eq!(
15379            choose_starter(None, false, unfinished.as_deref()),
15380            Starter::Resume("stalled-run".to_owned()),
15381            "manual release must preserve the normal resume path"
15382        );
15383    }
15384
15385    #[test]
15386    fn resume_refusals_explain_admission_without_changing_task_or_run() {
15387        use crate::handover::{ResumeRefusal, resume_refusal_under};
15388        let home = tempfile::tempdir().unwrap();
15389        let mut exhausted = run_state(RunStatus::Blocked);
15390        exhausted.driver_exited = true;
15391        exhausted.config.graph.review_rounds = 3;
15392        exhausted.reviews = (1..=3).map(review_round).collect();
15393        for refusal in [
15394            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15395            ResumeRefusal::Status(RunStatus::Ready),
15396            ResumeRefusal::Released("20261022-000000-aaaa".into()),
15397            ResumeRefusal::Retired("retirement-successor".into()),
15398            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15399        ] {
15400            let mut state = exhausted.clone();
15401            let expected = match refusal {
15402                ResumeRefusal::Status(_) => {
15403                    state.status = RunStatus::Ready;
15404                    "status `ready`"
15405                }
15406                ResumeRefusal::Released(ref target) => {
15407                    state.released_to = Some(target.clone());
15408                    "execution was released"
15409                }
15410                ResumeRefusal::Retired(ref target) => {
15411                    state.retired_to = Some(target.clone());
15412                    "execution was retired"
15413                }
15414                ResumeRefusal::OwnershipTransferred(ref target) => {
15415                    state.pr_taken_over_by = Some(target.clone());
15416                    "PR ownership was transferred"
15417                }
15418                _ => "review budget exhausted (3/3 rounds used)",
15419            };
15420            assert_eq!(
15421                resume_refusal_under(&state, Some(home.path())),
15422                Some(refusal.clone())
15423            );
15424            assert_eq!(
15425                refusal.successor(),
15426                state
15427                    .released_to
15428                    .as_deref()
15429                    .or(state.retired_to.as_deref())
15430                    .or(state.pr_taken_over_by.as_deref())
15431            );
15432            state.save_under(home.path()).unwrap();
15433            let queue = Queue::at(home.path().join("queue"));
15434            let mut task = Task::new(
15435                "retained implementation".into(),
15436                state.instruction.clone(),
15437                state.repo.clone(),
15438                Source::Agent {
15439                    run: "talk".into(),
15440                    node: crate::queue::CHAT_NODE.into(),
15441                },
15442            );
15443            task.runs.push(state.id.clone());
15444            task.hold_machine(Some("stopped".into()));
15445            queue.put(&mut task).unwrap();
15446            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15447            let before_run = serde_json::to_value(&state).unwrap();
15448            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15449                .unwrap_err()
15450                .to_string();
15451            assert!(error.contains(expected), "{error}");
15452            assert!(!error.contains("only a stalled or blocked"), "{error}");
15453            if matches!(refusal, ResumeRefusal::Status(_)) {
15454                assert!(
15455                    error.contains("is final; there is nothing left to resume"),
15456                    "{error}"
15457                );
15458            }
15459            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15460                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15461                assert!(error.contains("review-only successor with a new review budget"));
15462                assert!(error.contains("does not resume this run"));
15463            }
15464            for target in [
15465                &state.released_to,
15466                &state.retired_to,
15467                &state.pr_taken_over_by,
15468            ]
15469            .into_iter()
15470            .flatten()
15471            {
15472                let short = if state.retired_to.as_ref() == Some(target) {
15473                    target.as_str()
15474                } else {
15475                    crate::run::short_of(target)
15476                };
15477                assert!(
15478                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
15479                    "{error}"
15480                );
15481                if short != target {
15482                    assert!(!error.contains(target), "full successor id leaked: {error}");
15483                }
15484            }
15485            assert_eq!(
15486                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15487                before_task
15488            );
15489            assert_eq!(
15490                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15491                    .unwrap(),
15492                before_run
15493            );
15494            let question = action_question(&state.id, resume_action(&state.id));
15495            for phrases in [&PHRASES_EN, &PHRASES_JA] {
15496                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15497                    RunState::load_under(id, home.path())
15498                });
15499                let ActionDecision::Refuse(detail) = decision else {
15500                    panic!(
15501                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15502                        state.id,
15503                        home.path().display()
15504                    );
15505                };
15506                assert!(detail.contains(expected), "{detail}");
15507            }
15508        }
15509        // Preserve predicate ordering, while keeping every recorded destination visible.
15510        exhausted.status = RunStatus::Ready;
15511        exhausted.released_to = Some("released".into());
15512        exhausted.retired_to = Some("retired".into());
15513        exhausted.pr_taken_over_by = Some("owner".into());
15514        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15515        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15516        let detail = reason.diagnostic(&exhausted);
15517        for target in ["released", "retired", "owner"] {
15518            assert!(detail.contains(&format!("magi show {target}")));
15519        }
15520    }
15521
15522    #[test]
15523    fn resume_action_ignores_question_checkpoints_in_another_home() {
15524        crate::run::pin_test_home();
15525        let home = tempfile::tempdir().unwrap();
15526        let mut state = run_state(RunStatus::Blocked);
15527        // The private directory reserves this fixture's identity even while
15528        // other tests write questions into the process-wide store.
15529        state.id = format!(
15530            "resume-context-{}",
15531            home.path().file_name().unwrap().to_str().unwrap()
15532        );
15533        state.driver_exited = true;
15534        state.config.graph.review_rounds = 1;
15535        state.reviews = vec![review_round(1)];
15536        state.save_under(home.path()).unwrap();
15537        let task = held_task_with(&state.id);
15538        let answer = action_question(&state.id, resume_action(&state.id));
15539        let mut checkpoint = approval_question(&state.id);
15540        let foreign = Questions::open();
15541        foreign.put(&mut checkpoint).unwrap();
15542        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15543        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15544            RunState::load_under(id, home.path())
15545        });
15546        let matching: Vec<_> = foreign
15547            .list()
15548            .into_iter()
15549            .filter(|q| q.run == state.id && q.status.open())
15550            .collect();
15551        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15552        assert!(
15553            matches!(decision, ActionDecision::Refuse(_)),
15554            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15555            state.id,
15556            home.path().display(),
15557            crate::run::test_home().display()
15558        );
15559        assert_eq!(
15560            refusal,
15561            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15562        );
15563        let local = Questions::at(home.path().join("questions"));
15564        for status in [
15565            ask::QuestionStatus::Open,
15566            ask::QuestionStatus::Answered,
15567            ask::QuestionStatus::Abandoned,
15568        ] {
15569            let mut question = checkpoint.clone();
15570            match status {
15571                ask::QuestionStatus::Open => {}
15572                ask::QuestionStatus::Answered => {
15573                    question
15574                        .answer(ask::Answer::Choice(question.choices[0].clone()))
15575                        .unwrap();
15576                }
15577                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15578            }
15579            local.put(&mut question).unwrap();
15580            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15581                RunState::load_under(id, home.path())
15582            });
15583            if status.open() {
15584                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15585            } else {
15586                assert!(
15587                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15588                    "status={status:?}, decision={decision:?}"
15589                );
15590            }
15591        }
15592    }
15593
15594    #[test]
15595    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15596        let home = tempfile::tempdir().unwrap();
15597        let mut state = run_state(RunStatus::Stalled);
15598        state.id = format!(
15599            "resume-driver-{}",
15600            home.path().file_name().unwrap().to_str().unwrap()
15601        );
15602        state.driver_claimed = Some(false);
15603        state.save_under(home.path()).unwrap();
15604        let task = held_task_with(&state.id);
15605        let question = action_question(&state.id, resume_action(&state.id));
15606        let decide = || {
15607            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15608                RunState::load_under(id, home.path())
15609            })
15610        };
15611        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15612        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15613        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15614        match decide() {
15615            ActionDecision::Refuse(detail) => {
15616                assert!(
15617                    detail.starts_with("run already has a live driver: "),
15618                    "{detail}"
15619                );
15620                assert!(
15621                    detail.contains(&expected_lock.display().to_string()),
15622                    "{detail}"
15623                );
15624            }
15625            other => panic!("expected live driver refusal, got {other:?}"),
15626        }
15627        drop(lease);
15628        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15629    }
15630
15631    #[test]
15632    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15633        let home = tempfile::tempdir().unwrap();
15634        let mut state = run_state(RunStatus::Blocked);
15635        state.driver_exited = true;
15636        state.config.graph.review_rounds = 1;
15637        state.reviews = vec![review_round(1)];
15638        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15639        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15640            let mut saved = state.clone();
15641            match checkpoint {
15642                "publication" => saved.pr_publication_pending = true,
15643                "approval" => {
15644                    saved.land_approval = Some(crate::run::LandApproval {
15645                        question: "approval".into(),
15646                        head: "head".into(),
15647                    })
15648                }
15649                "armed" => saved.land_armed_head = Some("head".into()),
15650                "landing" => saved.status = RunStatus::Landing,
15651                _ => {
15652                    let mut question = ask::Question::new(
15653                        saved.id.clone(),
15654                        "review".into(),
15655                        "review-1".into(),
15656                        "continue?".into(),
15657                        String::new(),
15658                        vec!["continue".into()],
15659                    );
15660                    ask::Questions::at(home.path().join("questions"))
15661                        .put(&mut question)
15662                        .unwrap();
15663                }
15664            }
15665            saved.save_under(home.path()).unwrap();
15666            assert!(
15667                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15668                "{checkpoint}"
15669            );
15670            assert!(
15671                crate::resume::validate(home.path(), &saved.id).is_ok(),
15672                "{checkpoint}"
15673            );
15674        }
15675    }
15676
15677    #[test]
15678    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15679        let mut state = run_state(RunStatus::Blocked);
15680        state.config.graph.review_rounds = 3;
15681        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15682        assert!(exhausted_review_budget(&state));
15683
15684        // One round still unused: resuming can still ask a reviewer something.
15685        state.reviews.pop();
15686        assert!(!exhausted_review_budget(&state));
15687
15688        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
15689        // count: only a `Blocked` run re-enters the review loop on resume.
15690        let mut stalled = run_state(RunStatus::Stalled);
15691        stalled.config.graph.review_rounds = 1;
15692        stalled.reviews = vec![review_round(1)];
15693        assert!(!exhausted_review_budget(&stalled));
15694    }
15695
15696    fn review_round(round: usize) -> crate::run::ReviewRound {
15697        crate::run::ReviewRound {
15698            round,
15699            head: "deadbeef".to_owned(),
15700            verified_head: None,
15701            verified_at: None,
15702            reviews: Vec::new(),
15703            e2e: Vec::new(),
15704            verify_retried: false,
15705            e2e_deferred: false,
15706            e2e_defer_reason: None,
15707            fix: None,
15708            blocking: 0,
15709            answered: 1,
15710            expected: 1,
15711            clean: false,
15712            progressed: true,
15713            vote_split: false,
15714            reconsideration: Vec::new(),
15715            verdict: None,
15716        }
15717    }
15718
15719    #[test]
15720    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15721        let mut run = RunState::new(
15722            PathBuf::from("/repo"),
15723            "main".to_owned(),
15724            "abc1234def".to_owned(),
15725            "add retries".to_owned(),
15726            Config::default(),
15727        );
15728        run.status = RunStatus::Judging;
15729        run.parked = true;
15730        let mut task = Task::new(
15731            "add retries".to_owned(),
15732            "add retries".to_owned(),
15733            PathBuf::from("/repo"),
15734            crate::queue::Source::Human,
15735        );
15736        task.status = TaskStatus::Failed;
15737        task.runs = vec![run.id.clone()];
15738        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15739        assert!(with(&task, &run), "parked after judging is the case");
15740        let mut parked_task = task.clone();
15741        parked_task.status = TaskStatus::Parked;
15742        assert!(with(&parked_task, &run), "the Parked status is the case");
15743
15744        let mut not_parked = run.clone();
15745        not_parked.parked = false;
15746        not_parked.status = RunStatus::Stalled;
15747        assert!(!with(&task, &not_parked), "a stall is the conductor's");
15748
15749        let mut fresh = task.clone();
15750        fresh.fresh_start = true;
15751        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15752
15753        let mut review = task.clone();
15754        review.review_branch = Some("magi/x/A".to_owned());
15755        assert!(!with(&review, &run), "review is ranked before resume");
15756
15757        let mut held = task.clone();
15758        held.status = TaskStatus::Held;
15759        assert!(!with(&held, &run), "a hold stays visible to the conductor");
15760
15761        let mut released = run.clone();
15762        released.released_to = Some("20260901-000000-new1".to_owned());
15763        assert!(!with(&task, &released), "nothing left to resume into");
15764
15765        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15766            "unreadable"
15767        )));
15768    }
15769
15770    #[test]
15771    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15772        let mut released = RunState::new(
15773            PathBuf::from("/repo"),
15774            "main".to_owned(),
15775            "abc1234def".to_owned(),
15776            "add retries".to_owned(),
15777            Config::default(),
15778        );
15779        released.status = RunStatus::Blocked;
15780        assert_eq!(
15781            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15782            Some(released.id.clone())
15783        );
15784        released.released_to = Some("20260901-000000-new1".to_owned());
15785        assert_eq!(
15786            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15787            None,
15788            "there is nothing left to resume it into"
15789        );
15790    }
15791
15792    #[test]
15793    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
15794        // Mirrors the failure this exists to close: a task's last run ended
15795        // `Blocked` with the review budget spent, `crate::conduct` chose
15796        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
15797        // evidence), and without this check `attempt` would go on treating
15798        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
15799        // review loop iterates zero times over an already-spent budget, so
15800        // the resumed run settles right back to `Blocked` having asked nobody
15801        // anything, and `Requeue`'s promised fresh competition never happens.
15802        let mut exhausted = RunState::new(
15803            PathBuf::from("/repo"),
15804            "main".to_owned(),
15805            "abc1234def".to_owned(),
15806            "add retries".to_owned(),
15807            Config::default(),
15808        );
15809        exhausted.status = RunStatus::Blocked;
15810        exhausted.config.graph.review_rounds = 1;
15811        exhausted.reviews = vec![review_round(1)];
15812
15813        assert_eq!(
15814            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
15815            None,
15816            "an exhausted `Blocked` run must not be offered as resumable"
15817        );
15818
15819        // A `Blocked` run with rounds still unused is genuinely worth
15820        // resuming, and must still be found.
15821        let mut has_budget_left = RunState::new(
15822            PathBuf::from("/repo"),
15823            "main".to_owned(),
15824            "abc1234def".to_owned(),
15825            "add retries".to_owned(),
15826            Config::default(),
15827        );
15828        has_budget_left.status = RunStatus::Blocked;
15829        has_budget_left.config.graph.review_rounds = 3;
15830        has_budget_left.reviews = vec![review_round(1)];
15831
15832        assert_eq!(
15833            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
15834                Ok(has_budget_left.clone())
15835            }),
15836            Some(has_budget_left.id.clone())
15837        );
15838    }
15839
15840    #[test]
15841    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
15842        let mut run = RunState::new(
15843            PathBuf::from("/repo"),
15844            "main".to_owned(),
15845            "abc1234def".to_owned(),
15846            "add retries".to_owned(),
15847            Config::default(),
15848        );
15849        run.status = RunStatus::Blocked;
15850        run.config.graph.review_rounds = 1;
15851        run.reviews = vec![review_round(1)];
15852        run.pr_publication_pending = true;
15853        assert_eq!(
15854            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
15855            Some(run.id.clone()),
15856            "a spent review budget must not turn a failed publication into a re-competition"
15857        );
15858    }
15859
15860    #[test]
15861    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
15862        let mut task = Task::new(
15863            "recover work".into(),
15864            "recover work".into(),
15865            PathBuf::from("/repo"),
15866            crate::queue::Source::Human,
15867        );
15868        let mut history = std::collections::BTreeMap::new();
15869        for index in 0..8 {
15870            let mut run = run_state(RunStatus::Blocked);
15871            run.id = format!("20260101-000000-{index:04}");
15872            run.base_commit = format!("upstream-{index}");
15873            // Seven empty newer attempts must not erase the old recovery owner.
15874            if index > 0 {
15875                run.candidates.clear();
15876            }
15877            task.runs.extend([run.id.clone(), run.id.clone()]);
15878            history.insert(run.id.clone(), run);
15879            task.requeue();
15880        }
15881        let check = |task: &Task, starter: &Starter, limit| {
15882            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
15883        };
15884        assert!(
15885            check(&task, &Starter::Start, 8)
15886                .unwrap()
15887                .contains("8 unretired")
15888        );
15889        assert!(check(&task, &Starter::Start, 9).is_none());
15890        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
15891        task.release_operator("owner", None);
15892        assert_eq!(task.attempts, 0);
15893        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15894        assert!(check(&restored, &Starter::Start, 8).is_some());
15895        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
15896        assert!(check(&restored, &Starter::Start, 0).is_none());
15897    }
15898
15899    #[test]
15900    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
15901        let tmp = tempfile::tempdir().unwrap();
15902        let mut task = Task::new(
15903            "recover selected PR".into(),
15904            "preserve implementation".into(),
15905            tmp.path().join("repo"),
15906            crate::queue::Source::Human,
15907        );
15908        let mut failed = run_state(RunStatus::Failed);
15909        failed.id = "20260101-000000-fail".into();
15910        failed.candidates.clear();
15911        failed.prep_complete = Some(false);
15912        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15913        failed.startup = Some(crate::run::Startup {
15914            kind: "pr-recovery".into(),
15915            branch: Some("selected-public-head".into()),
15916            stage: "worktree-setup".into(),
15917            complete: false,
15918            failure: Some("setup modified a tracked file and failed".into()),
15919        });
15920        // Setup may fail before a candidate is recorded; its dirty worktree
15921        // still needs protection and consumes the independent retained bound.
15922        let worktree = failed.worktree_root().join("under-review");
15923        std::fs::create_dir_all(&worktree).unwrap();
15924        let retained_edit = worktree.join("implementation");
15925        std::fs::write(&retained_edit, "retained setup edit").unwrap();
15926        task.record_startup_failure(crate::run::StartupFailure {
15927            run: failed.id.clone(),
15928            stage: "worktree-setup".into(),
15929        });
15930        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15931        assert!(task.runs.is_empty() && task.passes.is_empty());
15932        assert_eq!(task.attempts, 0);
15933        let starter = Starter::Review("selected-public-head".into());
15934        assert!(
15935            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
15936                .unwrap()
15937                .contains("1 unretired")
15938        );
15939        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
15940        assert!(
15941            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
15942                .unwrap()
15943                .contains("Cannot verify")
15944        );
15945        // Older or mixed writers can link the same reservation in both lists.
15946        let mut mixed = task.clone();
15947        mixed.runs.push(failed.id.clone());
15948        mixed
15949            .startup_failures
15950            .push(task.startup_failures[0].clone());
15951        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
15952        failed.retired_to = Some("verified-recovery-owner".into());
15953        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
15954        assert!(
15955            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
15956                panic!("resuming the existing owner must not allocate a new attempt")
15957            })
15958            .is_none()
15959        );
15960        assert_eq!(
15961            std::fs::read_to_string(retained_edit).unwrap(),
15962            "retained setup edit"
15963        );
15964        assert!(task.runs.is_empty() && task.passes.is_empty());
15965        assert_eq!(task.attempts, 0);
15966    }
15967
15968    #[test]
15969    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
15970        let mut task = Task::new(
15971            "recover work".into(),
15972            "recover work".into(),
15973            PathBuf::from("/repo"),
15974            crate::queue::Source::Human,
15975        );
15976        let mut run = run_state(RunStatus::Superseded);
15977        run.candidates.clear();
15978        task.runs.push(run.id.clone());
15979        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
15980        run.retired_to = Some("authority".into());
15981        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15982        run.retired_to = None;
15983        run.released_to = Some("authority".into());
15984        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15985        assert!(
15986            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
15987                .unwrap()
15988                .contains("Cannot verify")
15989        );
15990        // Resuming an existing owner needs no new inventory or worktree budget.
15991        assert!(
15992            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
15993                panic!("resume must not load historical attempts")
15994            })
15995            .is_none()
15996        );
15997    }
15998
15999    #[test]
16000    fn retired_resume_requires_a_valid_same_repository_authority() {
16001        let mut source = run_state(RunStatus::Blocked);
16002        let mut empty = run_state(RunStatus::Blocked);
16003        empty.retired_to = Some(source.id.clone());
16004        let runs = vec![source.id.clone(), empty.id.clone()];
16005        let resolve = |source: &RunState, empty: &RunState| {
16006            unfinished_run_with(&runs, "fixture", |id| {
16007                if id == source.id {
16008                    Ok(source.clone())
16009                } else if id == empty.id {
16010                    Ok(empty.clone())
16011                } else {
16012                    bail!("unreadable authority")
16013                }
16014            })
16015        };
16016        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16017        assert_eq!(
16018            choose_starter(None, false, resolve(&source, &empty).as_deref()),
16019            Starter::Resume(source.id.clone())
16020        );
16021        source.retired_to = Some(empty.id.clone());
16022        assert!(
16023            resolve(&source, &empty).is_none(),
16024            "cycles do not revive obsolete runs"
16025        );
16026        source.retired_to = None;
16027        source.repo = PathBuf::from("/another-repository");
16028        assert!(resolve(&source, &empty).is_none());
16029        source.repo = empty.repo.clone();
16030        source.released_to = Some("later".into());
16031        assert!(resolve(&source, &empty).is_none());
16032        empty.retired_to = Some("unlisted-run".into());
16033        assert!(resolve(&source, &empty).is_none());
16034    }
16035
16036    #[test]
16037    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16038        // A task whose history holds an *older* run that still looks
16039        // resumable (say, a competition `Runner::review` was started
16040        // alongside after that older run went `Stalled`) and a *newest* run
16041        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
16042        // on this task must mean a fresh competition — falling back to the
16043        // stale, superseded `Stalled` run instead would resurrect history
16044        // nothing asked to revisit and silently defeat the requeue.
16045        let mut older_stalled = RunState::new(
16046            PathBuf::from("/repo"),
16047            "main".to_owned(),
16048            "abc1234def".to_owned(),
16049            "add retries".to_owned(),
16050            Config::default(),
16051        );
16052        older_stalled.status = RunStatus::Stalled;
16053
16054        let mut newest_exhausted = RunState::new(
16055            PathBuf::from("/repo"),
16056            "main".to_owned(),
16057            "abc1234def".to_owned(),
16058            "add retries".to_owned(),
16059            Config::default(),
16060        );
16061        newest_exhausted.status = RunStatus::Blocked;
16062        newest_exhausted.config.graph.review_rounds = 1;
16063        newest_exhausted.reviews = vec![review_round(1)];
16064
16065        assert_eq!(
16066            unfinished_run_with(
16067                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16068                "t",
16069                |_| Ok(newest_exhausted.clone())
16070            ),
16071            None,
16072            "the newest run is exhausted, so nothing here is worth resuming - \
16073             least of all the older, already-superseded run"
16074        );
16075    }
16076
16077    #[test]
16078    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16079        assert_eq!(
16080            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16081                Err(anyhow::anyhow!("fixture is absent"))
16082            }),
16083            None
16084        );
16085    }
16086
16087    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16088        let mut q = ask::Question::new(
16089            run.to_owned(),
16090            "implement".to_owned(),
16091            "impl-A".to_owned(),
16092            "continue?".to_owned(),
16093            String::new(),
16094            vec!["resume で続行する".to_owned(), "other".to_owned()],
16095        );
16096        q.actions.insert("resume で続行する".to_owned(), action);
16097        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16098            .unwrap();
16099        q
16100    }
16101
16102    fn held_task_with(run: &str) -> Task {
16103        let mut t = task();
16104        t.runs = vec![run.to_owned()];
16105        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16106        t
16107    }
16108
16109    fn resume_action(run: &str) -> ask::ChoiceAction {
16110        ask::ChoiceAction::Resume { run: run.into() }
16111    }
16112
16113    #[test]
16114    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16115        let home = crate::run::test_home();
16116        for parked in [false, true] {
16117            let mut t = task();
16118            t.start("A".into());
16119            t.start("B".into());
16120            assert_eq!(t.runs, vec!["A", "B"]);
16121            t.start("A".into());
16122            let mut resumed = run_state(RunStatus::Blocked);
16123            resumed.id = "A".into();
16124            resumed.parked = parked;
16125            resumed.driver_exited = true;
16126            t.hold_machine(Some("resumed run stopped".into()));
16127            let q = action_question("A", resume_action("A"));
16128            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16129            assert_eq!(
16130                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16131                    assert_eq!(id, "A");
16132                    Ok(resumed.clone())
16133                }),
16134                ActionDecision::Resume("A".into())
16135            );
16136            assert_eq!(
16137                action_standing(&t, &action_question("B", resume_action("B"))),
16138                ActionStanding::Stale
16139            );
16140            t.release_operator("cli", None);
16141            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16142                assert_eq!(id, "A");
16143                Ok(resumed.clone())
16144            });
16145            assert_eq!(
16146                choose_starter(None, false, unfinished.as_deref()),
16147                Starter::Resume("A".into())
16148            );
16149            assert_eq!(t.runs, vec!["B", "A"]);
16150        }
16151    }
16152
16153    #[test]
16154    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16155        let home = crate::run::test_home();
16156        let mut state = crate::land::tests::repair_state(true, true);
16157        state.status = RunStatus::Landing;
16158        state.parked = true;
16159        state.driver_exited = true;
16160        let mut q = ask::Question::new(
16161            state.id.clone(),
16162            land::APPROVAL_NODE.into(),
16163            "land".into(),
16164            "Merge?".into(),
16165            String::new(),
16166            vec![land::APPROVE.into(), land::HOLD.into()],
16167        );
16168        q.id = state.id.clone();
16169        state.land_approval = Some(crate::run::LandApproval {
16170            question: q.id.clone(),
16171            head: "current-head".into(),
16172        });
16173        assert!(land::upgrade_repair_choice(&mut q, &state));
16174        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16175        let mut task = held_task_with(&state.id);
16176        task.status = TaskStatus::Parked;
16177        assert_eq!(
16178            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16179            ActionDecision::Resume(state.id.clone())
16180        );
16181        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16182        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16183        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16184        assert_eq!(
16185            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16186            ActionDecision::Resume(state.id.clone()),
16187            "a repair answer newer than the manual hold resumes the existing owner"
16188        );
16189        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16190        for answered_at in [q.answered_at, None] {
16191            let mut older = q.clone();
16192            older.answered_at = answered_at;
16193            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
16194                panic!("a later manual hold must prevent dispatch")
16195            });
16196            let ActionDecision::Refuse(reason) = refused else {
16197                panic!("expected an actionable refusal, got {refused:?}");
16198            };
16199            assert!(reason.contains("later operator decision"));
16200            assert!(reason.contains(&format!("magi task release {}", task.id)));
16201        }
16202        task.operator_decided_at = None;
16203        let mut superseded = state.clone();
16204        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16205        assert_eq!(
16206            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16207            ActionDecision::Stale
16208        );
16209        for case in 1..4 {
16210            let mut changed = state.clone();
16211            match case {
16212                1 => changed.status = RunStatus::Blocked,
16213                2 => changed.released_to = Some("new-owner".into()),
16214                _ => changed.land_approval.as_mut().unwrap().head.clear(),
16215            }
16216            assert!(matches!(
16217                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16218                ActionDecision::Refuse(_)
16219            ));
16220        }
16221        assert!(matches!(
16222            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16223                "missing owner"
16224            )),
16225            ActionDecision::Refuse(_)
16226        ));
16227        task.runs.push("replacement".into());
16228        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16229        assert_eq!(
16230            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16231                "old owner must not load"
16232            )),
16233            ActionDecision::Stale
16234        );
16235    }
16236
16237    #[test]
16238    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16239        let mut state = crate::land::tests::repair_state(true, true);
16240        state.status = RunStatus::Landing;
16241        state.parked = true;
16242        state.driver_exited = true;
16243        let mut q = ask::Question::new(
16244            state.id.clone(),
16245            land::APPROVAL_NODE.into(),
16246            "land".into(),
16247            "Merge?".into(),
16248            String::new(),
16249            vec![land::APPROVE.into(), land::HOLD.into()],
16250        );
16251        q.id = state.id.clone();
16252        state.land_approval = Some(crate::run::LandApproval {
16253            question: q.id.clone(),
16254            head: "current-head".into(),
16255        });
16256        state.save().unwrap();
16257        land::upgrade_repair_choice(&mut q, &state);
16258        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16259        Questions::open().put(&mut q).unwrap();
16260        let tmp = tempfile::tempdir().unwrap();
16261        let queue = Queue::at(tmp.path().join("queue"));
16262        let mut task = held_task_with(&state.id);
16263        task.status = TaskStatus::Parked;
16264        queue.put(&mut task).unwrap();
16265        let empty = Arc::new(tokio::sync::Semaphore::new(0));
16266        let free = Arc::new(tokio::sync::Semaphore::new(1));
16267        assert!(matches!(
16268            claim_dispatch(&queue, &task, false, &empty, &free),
16269            Err(SkipReason::OrdinaryCapacity)
16270        ));
16271        assert!(matches!(
16272            claim_dispatch(&queue, &task, true, &free, &free),
16273            Err(SkipReason::CoolingDown)
16274        ));
16275        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16276        assert!(claim.permit.is_some());
16277        assert!(matches!(
16278            claim_dispatch(&queue, &task, false, &free, &free),
16279            Err(SkipReason::ClaimUnavailable)
16280        ));
16281        drop(claim);
16282        Questions::open()
16283            .update(&q.id, |q| {
16284                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16285                Ok(())
16286            })
16287            .unwrap();
16288        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16289        assert!(claim.permit.is_none());
16290        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16291    }
16292
16293    #[test]
16294    fn decide_action_resumes_only_the_latest_resumable_run() {
16295        let home = crate::run::test_home();
16296        let t = held_task_with("r1");
16297        let q = action_question("r1", resume_action("r1"));
16298        let load = |s: RunState| move |_: &str| Ok(s);
16299        assert_eq!(
16300            decide_action(
16301                &home,
16302                &t,
16303                &q,
16304                &PHRASES_EN,
16305                load(run_state(RunStatus::Blocked))
16306            ),
16307            ActionDecision::Resume("r1".into())
16308        );
16309        // Not the latest run of the task.
16310        let q_other = action_question("r1", resume_action("r0"));
16311        assert!(matches!(
16312            decide_action(
16313                &home,
16314                &t,
16315                &q_other,
16316                &PHRASES_EN,
16317                load(run_state(RunStatus::Blocked))
16318            ),
16319            ActionDecision::Refuse(_)
16320        ));
16321        // A finished run cannot make progress.
16322        assert!(matches!(
16323            decide_action(
16324                &home,
16325                &t,
16326                &q,
16327                &PHRASES_EN,
16328                load(run_state(RunStatus::Ready))
16329            ),
16330            ActionDecision::Refuse(_)
16331        ));
16332        // A released one either.
16333        let mut released = run_state(RunStatus::Blocked);
16334        released.released_to = Some("elsewhere".into());
16335        assert!(matches!(
16336            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16337            ActionDecision::Refuse(_)
16338        ));
16339        // Unreadable state is a refusal, never a fresh competition.
16340        assert!(matches!(
16341            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16342            ActionDecision::Refuse(_)
16343        ));
16344    }
16345
16346    #[test]
16347    fn decide_action_ignores_a_question_about_an_earlier_run() {
16348        let home = crate::run::test_home();
16349        let mut t = held_task_with("r1");
16350        t.runs.push("r2".to_owned());
16351        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16352        assert_eq!(
16353            decide_action(
16354                &home,
16355                &t,
16356                &action_question("r1", ask::ChoiceAction::Done),
16357                &PHRASES_EN,
16358                never
16359            ),
16360            ActionDecision::Stale
16361        );
16362    }
16363
16364    #[test]
16365    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16366        let home = crate::run::test_home();
16367        let mut t = held_task_with("r1");
16368        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16369        assert_eq!(
16370            decide_action(
16371                &home,
16372                &t,
16373                &action_question("r1", ask::ChoiceAction::Requeue),
16374                &PHRASES_EN,
16375                never
16376            ),
16377            ActionDecision::Requeue
16378        );
16379        let done_q = action_question("r1", ask::ChoiceAction::Done);
16380        assert_eq!(
16381            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16382            ActionDecision::Done
16383        );
16384        t.mark_action_applied(&done_q.id);
16385        assert_eq!(
16386            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16387            ActionDecision::Skip
16388        );
16389
16390        // A plain answer (no action for that label) does nothing.
16391        let mut plain = action_question("r1", ask::ChoiceAction::Done);
16392        plain.actions.clear();
16393        assert_eq!(
16394            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16395            ActionDecision::Skip
16396        );
16397        // A running task is left alone.
16398        let mut running = held_task_with("r1");
16399        running.status = TaskStatus::Running;
16400        assert_eq!(
16401            decide_action(
16402                &home,
16403                &running,
16404                &action_question("r1", ask::ChoiceAction::Done),
16405                &PHRASES_EN,
16406                never
16407            ),
16408            ActionDecision::Skip
16409        );
16410    }
16411
16412    #[test]
16413    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16414        crate::run::pin_test_home();
16415        for legacy in [false, true] {
16416            let dir = tempfile::tempdir().unwrap();
16417            let queue = Queue::at(dir.path().join("queue"));
16418            let questions = Questions::at(dir.path().join("questions"));
16419            let run = "20260101-000000-hold";
16420            let mut task = held_task_with(run);
16421            task.status = TaskStatus::Parked;
16422            let mut q = ask::Question::new(
16423                run.into(),
16424                land::APPROVAL_NODE.into(),
16425                "land".into(),
16426                "Repair?".into(),
16427                String::new(),
16428                vec![land::REPAIR.into()],
16429            );
16430            q.actions.insert(land::REPAIR.into(), resume_action(run));
16431            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16432            // Deterministically order the answer before the actual manual hold.
16433            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16434            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16435            questions.put(&mut q).unwrap();
16436            task.hold_manual(Some("Keep this PR paused".into()));
16437            if legacy {
16438                task.hold_source = None;
16439            }
16440            queue.put(&mut task).unwrap();
16441
16442            apply_task_choice_actions(&queue, &questions, dir.path());
16443            let after = queue.get(&task.id).unwrap();
16444            assert!(after.operator_held());
16445            assert_eq!(after.hold_source, task.hold_source);
16446            assert_eq!(after.operator_decided_at, task.operator_decided_at);
16447            assert_eq!(after.runs, task.runs);
16448            assert_eq!(after.instruction, task.instruction);
16449            assert!(after.resume_override.is_none());
16450            assert!(after.action_applied(&q.id));
16451            let reason = after.hold_reason.as_deref().unwrap();
16452            assert!(reason.starts_with("Keep this PR paused"));
16453            assert!(reason.contains("later operator decision"));
16454            assert!(reason.contains(&format!("magi task release {}", task.id)));
16455
16456            for recovery in [
16457                crate::conduct::Recovery::Review,
16458                crate::conduct::Recovery::Requeue,
16459            ] {
16460                crate::conduct::apply(
16461                    &queue,
16462                    &questions,
16463                    &crate::conduct::Verdict {
16464                        decisions: vec![crate::conduct::Decision {
16465                            id: task.id.clone(),
16466                            recovery: Some(recovery),
16467                            ..Default::default()
16468                        }],
16469                    },
16470                )
16471                .unwrap();
16472            }
16473            // Reconciliation is idempotent, and automatic recovery cannot
16474            // reopen this owner after it observes the rejected repair answer.
16475            apply_task_choice_actions(&queue, &questions, dir.path());
16476            let still_held = queue.get(&task.id).unwrap();
16477            assert!(still_held.operator_held());
16478            assert_eq!(still_held.hold_reason, after.hold_reason);
16479            assert_eq!(still_held.runs, task.runs);
16480            assert!(still_held.review_branch.is_none());
16481            assert!(!still_held.fresh_start);
16482            assert!(queue.next_runnable().is_none());
16483        }
16484    }
16485
16486    #[test]
16487    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16488        for held in [false, true] {
16489            for retry in [false, true] {
16490                let dir = tempfile::tempdir().unwrap();
16491                let queue = Queue::at(dir.path().join("queue"));
16492                let questions = Questions::at(dir.path().join("questions"));
16493                let home = dir.path().join("home");
16494                let mut t = task();
16495                if held {
16496                    t.hold_machine(Some("driver state unknown".into()));
16497                }
16498                queue.put(&mut t).unwrap();
16499                let verdict = serde_json::from_value(serde_json::json!({
16500                    "decisions": [{
16501                        "id": t.id,
16502                        "question": "Driver state unknown; retry the checks or hold?",
16503                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16504                        "actions": {
16505                            "daemon: recheck and retry": {"do": "requeue"},
16506                            "daemon: hold the task": {"do": "hold"}
16507                        }
16508                    }]
16509                }))
16510                .unwrap();
16511                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16512                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16513                let mut q = questions.list().pop().unwrap();
16514                let choice = if retry {
16515                    "daemon: recheck and retry"
16516                } else {
16517                    "daemon: hold the task"
16518                };
16519                assert_eq!(q.actions.len(), 2);
16520                q.answer(ask::Answer::Choice(choice.into())).unwrap();
16521                questions.put(&mut q).unwrap();
16522
16523                // A Web answer does not remove the deputy's fresh lease.
16524                questions.beat(&q.id, ask::WaiterKind::Deputy);
16525                for _ in 0..2 {
16526                    resolve_blockers(&queue, &questions);
16527                    apply_task_choice_actions(&queue, &questions, &home);
16528                    let waiting = queue.get(&t.id).unwrap();
16529                    assert_eq!(waiting.status, TaskStatus::Blocked);
16530                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
16531                    assert!(waiting.answers.is_empty());
16532                    assert!(!waiting.action_applied(&q.id));
16533                    assert!(runnable(&queue).is_empty());
16534                    let free = Arc::new(tokio::sync::Semaphore::new(1));
16535                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16536                }
16537                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16538
16539                // Releasing the blocker and applying the operation share one save.
16540                resolve_blockers(&queue, &questions);
16541                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16542                apply_task_choice_actions(&queue, &questions, &home);
16543                let after = queue.get(&t.id).unwrap();
16544                assert_eq!(
16545                    after.status,
16546                    if retry {
16547                        TaskStatus::Queued
16548                    } else {
16549                        TaskStatus::Held
16550                    }
16551                );
16552                assert!(after.action_applied(&q.id));
16553                assert_eq!(after.operator_held(), !retry);
16554                assert_eq!(after.answers.len(), 1);
16555
16556                // A later operator decision must not replay this answer.
16557                let mut changed = after;
16558                if retry {
16559                    changed.hold_manual(Some("later hold".into()));
16560                } else {
16561                    changed.release_operator("test", None);
16562                }
16563                let expected = changed.status;
16564                queue.put(&mut changed).unwrap();
16565                apply_task_choice_actions(&queue, &questions, &home);
16566                assert_eq!(queue.get(&t.id).unwrap().status, expected);
16567            }
16568        }
16569    }
16570
16571    #[test]
16572    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16573        let dir = tempfile::tempdir().unwrap();
16574        let queue = Queue::at(dir.path().join("queue"));
16575        let questions = Questions::at(dir.path().join("questions"));
16576        let home = dir.path().join("home");
16577        let mut state = run_state(RunStatus::Blocked);
16578        state.id = "20260101-000000-act1".to_owned();
16579        state.save_under(&home).unwrap();
16580
16581        let mut t = held_task_with(&state.id);
16582        queue.put(&mut t).unwrap();
16583        let mut q = action_question(&state.id, resume_action(&state.id));
16584        questions.put(&mut q).unwrap();
16585
16586        apply_task_choice_actions(&queue, &questions, &home);
16587        let after = queue.get(&t.id).unwrap();
16588        assert_eq!(after.status, TaskStatus::Queued);
16589        assert!(!after.fresh_start);
16590        assert!(after.action_applied(&q.id));
16591        let pin = after.resume_override.clone().unwrap();
16592        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16593        assert!(pin.forced);
16594
16595        // Held again later: the same answer does not release it a second time.
16596        let mut again = queue.get(&t.id).unwrap();
16597        again.hold_machine(Some("later".into()));
16598        queue.put(&mut again).unwrap();
16599        apply_task_choice_actions(&queue, &questions, &home);
16600        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16601    }
16602
16603    #[test]
16604    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16605        let dir = tempfile::tempdir().unwrap();
16606        let home = dir.path();
16607        let queue = Queue::at(home.join("queue"));
16608        let questions = Questions::at(home.join("questions"));
16609        let mut state = run_state(RunStatus::Blocked);
16610        state.save_under(home).unwrap();
16611        let mut task = held_task_with(&state.id);
16612        queue.put(&mut task).unwrap();
16613        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16614        questions.put(&mut question).unwrap();
16615
16616        apply_task_choice_actions(&queue, &questions, home);
16617
16618        let after = queue.get(&task.id).unwrap();
16619        assert_eq!(after.status, TaskStatus::Held);
16620        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16621        assert_eq!(after.runs, task.runs);
16622        assert!(after.completion_history.is_empty());
16623        assert!(!after.decision_effects.contains_key(&question.id));
16624        assert_eq!(
16625            RunState::load_under(&state.id, home).unwrap().status,
16626            RunStatus::Blocked
16627        );
16628    }
16629
16630    #[test]
16631    fn a_delivered_answer_is_still_acted_on_exactly_once() {
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-act2".to_owned();
16638        state.save_under(&home).unwrap();
16639
16640        let mut t = held_task_with(&state.id);
16641        queue.put(&mut t).unwrap();
16642        let mut q = action_question(&state.id, resume_action(&state.id));
16643        q.answer_delivered = true;
16644        questions.put(&mut q).unwrap();
16645
16646        // Delivered, and the agent then died: the task is still held, so the
16647        // chosen action applies.
16648        apply_task_choice_actions(&queue, &questions, &home);
16649        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16650        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16651
16652        // Held again: the same answer does nothing a second time.
16653        let mut again = queue.get(&t.id).unwrap();
16654        again.hold_machine(Some("later".into()));
16655        queue.put(&mut again).unwrap();
16656        apply_task_choice_actions(&queue, &questions, &home);
16657        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16658    }
16659
16660    #[test]
16661    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16662        let dir = tempfile::tempdir().unwrap();
16663        let queue = Queue::at(dir.path().join("queue"));
16664        let questions = Questions::at(dir.path().join("questions"));
16665        let home = dir.path().join("home");
16666        let mut state = run_state(RunStatus::Blocked);
16667        state.id = "20260101-000000-act3".to_owned();
16668        state.save_under(&home).unwrap();
16669        let mut t = held_task_with(&state.id);
16670        queue.put(&mut t).unwrap();
16671        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16672        questions.put(&mut q).unwrap();
16673
16674        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16675        apply_task_choice_actions(&queue, &questions, &home);
16676        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16677
16678        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16679        apply_task_choice_actions(&queue, &questions, &home);
16680        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16681    }
16682
16683    #[test]
16684    fn action_standing_tells_the_reasons_apart() {
16685        let mut t = held_task_with("r1");
16686        let q = action_question("r1", ask::ChoiceAction::Requeue);
16687        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16688        let mut plain = q.clone();
16689        plain.actions.clear();
16690        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16691
16692        // Applied wins over everything, even a running task.
16693        t.mark_action_applied(&q.id);
16694        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16695
16696        // A newer attempt running: the old question is Stale, not Busy.
16697        let mut t = held_task_with("r1");
16698        t.start("r2".to_owned());
16699        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16700        // The same question about the latest run just waits.
16701        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16702        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16703        t.status = TaskStatus::Blocked;
16704        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16705
16706        // A conductor question is keyed by the task, never stale.
16707        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16708        c.node = crate::conduct::NODE.to_owned();
16709        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
16710        assert!(!ActionStanding::Busy.daemon_owns());
16711    }
16712
16713    #[test]
16714    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
16715        let dir = tempfile::tempdir().unwrap();
16716        let queue = Queue::at(dir.path().join("queue"));
16717        let questions = Questions::at(dir.path().join("questions"));
16718        let home = dir.path().join("home");
16719        // Execution finished before task settlement; Done is not a discard.
16720        let mut state = run_state(RunStatus::Ready);
16721        state.id = "20260101-000000-act4".to_owned();
16722        state.save_under(&home).unwrap();
16723        let mut t = held_task_with(&state.id);
16724        t.status = TaskStatus::Running;
16725        queue.put(&mut t).unwrap();
16726        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
16727        q.cwd = Some(dir.path().display().to_string());
16728        questions.put(&mut q).unwrap();
16729
16730        // While the task runs the daemon will not act, so the waiter still
16731        // delivers the word to the dead asker's seat ...
16732        let running = queue.get(&t.id).unwrap();
16733        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
16734        assert!(matches!(
16735            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
16736            crate::waiter::Action::Deliver(_)
16737        ));
16738        // ... and the daemon waits while the task runs, then applies once.
16739        apply_task_choice_actions(&queue, &questions, &home);
16740        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
16741        let mut back = queue.get(&t.id).unwrap();
16742        back.hold_machine(Some("later".into()));
16743        queue.put(&mut back).unwrap();
16744        apply_task_choice_actions(&queue, &questions, &home);
16745        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
16746        let mut again = queue.get(&t.id).unwrap();
16747        again.hold_machine(Some("again".into()));
16748        queue.put(&mut again).unwrap();
16749        apply_task_choice_actions(&queue, &questions, &home);
16750        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16751    }
16752
16753    #[test]
16754    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
16755     {
16756        let dir = tempfile::tempdir().unwrap();
16757        let home = dir.path();
16758        let queue = Queue::at(home.join("queue"));
16759        let mut state = run_state(RunStatus::Blocked);
16760        state.id = "20261125-084544-669a".to_owned();
16761        state.driver_exited = true;
16762        state.driver_pid = None;
16763        state.driver_started_at = None;
16764        state.save_under(home).unwrap();
16765
16766        let mut t = held_task_with(&state.id);
16767        queue.put(&mut t).unwrap();
16768
16769        // Simulate a task worker that finished and was archived to results/,
16770        // while daemon.json still has a fresh heartbeat referencing that worker.
16771        let worker_id = "fc769e65-0000-4000-8000-000000000001";
16772        let retained_dir = home.join("workers").join("results").join(worker_id);
16773        std::fs::create_dir_all(&retained_dir).unwrap();
16774        let finished_job = crate::worker::Job {
16775            id: worker_id.to_owned(),
16776            sequence: 1,
16777            kind: "task".to_owned(),
16778            key: format!("task:{}", t.id),
16779            payload: serde_json::json!({
16780                "queue": home.join("queue"),
16781                "task": t.id,
16782                "opts": Opts::default(),
16783                "standalone": false,
16784            }),
16785            generation: "a".repeat(64),
16786            version: Some("0.260.0".to_owned()),
16787            status: crate::worker::Status::Finished,
16788            result: Some("completed".to_owned()),
16789            pid: Some(37456),
16790            created_at: 1,
16791            finished_at: Some(2),
16792        };
16793        std::fs::write(
16794            retained_dir.join("job.json"),
16795            serde_json::to_vec(&finished_job).unwrap(),
16796        )
16797        .unwrap();
16798
16799        let now = Timestamp::now();
16800        let mut status = Status::new();
16801        status.updated_at = now;
16802        status.current = vec![Current {
16803            worker: Some(worker_id.to_owned()),
16804            task: t.id.clone(),
16805            run: state.id.clone(),
16806        }];
16807        write_status_to(&home.join("daemon.json"), &status).unwrap();
16808
16809        assert!(
16810            claim_for_run(home, &state.id, now).is_none(),
16811            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
16812        );
16813        assert!(crate::resume::validate(home, &state.id).is_ok());
16814
16815        // Legacy heartbeat without worker id remains protected.
16816        status.current = vec![Current {
16817            worker: None,
16818            task: t.id.clone(),
16819            run: state.id.clone(),
16820        }];
16821        write_status_to(&home.join("daemon.json"), &status).unwrap();
16822        let legacy_err = crate::resume::validate(home, &state.id)
16823            .unwrap_err()
16824            .to_string();
16825        assert!(
16826            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16827            "{legacy_err}"
16828        );
16829        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
16830
16831        // Heartbeat naming a missing/unreadable worker record remains protected.
16832        let missing_id = "fc769e65-0000-4000-8000-000000000002";
16833        status.current = vec![Current {
16834            worker: Some(missing_id.to_owned()),
16835            task: t.id.clone(),
16836            run: state.id.clone(),
16837        }];
16838        write_status_to(&home.join("daemon.json"), &status).unwrap();
16839        let missing_err = crate::resume::validate(home, &state.id)
16840            .unwrap_err()
16841            .to_string();
16842        assert!(
16843            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16844            "{missing_err}"
16845        );
16846        assert!(missing_err.contains(missing_id), "{missing_err}");
16847        assert!(missing_err.contains("status=unknown"), "{missing_err}");
16848
16849        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
16850        // still remains protected conservatively until fenced to a terminal status.
16851        let running_id = "fc769e65-0000-4000-8000-000000000003";
16852        let running_dir = home.join("workers").join("jobs").join(running_id);
16853        std::fs::create_dir_all(&running_dir).unwrap();
16854        let running_job = crate::worker::Job {
16855            id: running_id.to_owned(),
16856            status: crate::worker::Status::Running,
16857            pid: Some(42424),
16858            finished_at: None,
16859            result: None,
16860            ..finished_job
16861        };
16862        std::fs::write(
16863            running_dir.join("job.json"),
16864            serde_json::to_vec(&running_job).unwrap(),
16865        )
16866        .unwrap();
16867        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
16868        status.current = vec![Current {
16869            worker: Some(running_id.to_owned()),
16870            task: t.id.clone(),
16871            run: state.id.clone(),
16872        }];
16873        write_status_to(&home.join("daemon.json"), &status).unwrap();
16874        let running_err = crate::resume::validate(home, &state.id)
16875            .unwrap_err()
16876            .to_string();
16877        assert!(
16878            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16879            "{running_err}"
16880        );
16881        assert!(running_err.contains(running_id), "{running_err}");
16882        assert!(running_err.contains("pid=42424"), "{running_err}");
16883        assert!(running_err.contains("status=running"), "{running_err}");
16884    }
16885
16886    #[test]
16887    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
16888        let dir = tempfile::tempdir().unwrap();
16889        let home = dir.path();
16890        let queue = Queue::at(home.join("queue"));
16891        let mut state = run_state(RunStatus::Blocked);
16892        state.id = "20261125-090000-evid".to_owned();
16893        state.driver_exited = true;
16894        state.save_under(home).unwrap();
16895        let mut t = held_task_with(&state.id);
16896        queue.put(&mut t).unwrap();
16897
16898        // 1. Live task worker holding live.lock.
16899        let payload = serde_json::json!({
16900            "queue": home.join("queue"),
16901            "task": t.id,
16902            "opts": Opts::default(),
16903            "standalone": false,
16904        });
16905        let (job, lease) =
16906            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
16907        let worker_err = crate::resume::validate(home, &state.id)
16908            .unwrap_err()
16909            .to_string();
16910        assert!(
16911            worker_err.starts_with("run already has a live driver: worker claim"),
16912            "{worker_err}"
16913        );
16914        assert!(worker_err.contains(&job.id), "{worker_err}");
16915        assert!(
16916            worker_err.contains(&format!("pid={}", std::process::id())),
16917            "{worker_err}"
16918        );
16919        assert!(worker_err.contains("status=running"), "{worker_err}");
16920        assert!(worker_err.contains("live.lock held"), "{worker_err}");
16921        drop(lease);
16922        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
16923
16924        // 2. Unfenced Starting worker reservation.
16925        let starting_id = "fc769e65-0000-4000-8000-000000000010";
16926        let starting_dir = home.join("workers").join("jobs").join(starting_id);
16927        std::fs::create_dir_all(&starting_dir).unwrap();
16928        let starting_job = crate::worker::Job {
16929            id: starting_id.to_owned(),
16930            sequence: 2,
16931            kind: "task".to_owned(),
16932            key: format!("task:{}", t.id),
16933            payload: serde_json::json!({
16934                "queue": home.join("queue"),
16935                "task": t.id,
16936                "opts": Opts::default(),
16937                "standalone": false,
16938            }),
16939            generation: "a".repeat(64),
16940            version: None,
16941            status: crate::worker::Status::Starting,
16942            result: None,
16943            pid: None,
16944            created_at: 1,
16945            finished_at: None,
16946        };
16947        std::fs::write(
16948            starting_dir.join("job.json"),
16949            serde_json::to_vec(&starting_job).unwrap(),
16950        )
16951        .unwrap();
16952        let starting_err = crate::resume::validate(home, &state.id)
16953            .unwrap_err()
16954            .to_string();
16955        assert!(
16956            starting_err.starts_with("run already has a live driver: worker claim"),
16957            "{starting_err}"
16958        );
16959        assert!(starting_err.contains(starting_id), "{starting_err}");
16960        assert!(starting_err.contains("status=starting"), "{starting_err}");
16961        assert!(
16962            starting_err.contains("unfenced starting reservation"),
16963            "{starting_err}"
16964        );
16965        std::fs::remove_dir_all(&starting_dir).unwrap();
16966
16967        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
16968        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
16969        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
16970        std::fs::create_dir_all(&corrupt_dir).unwrap();
16971        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
16972        let store_err = crate::resume::validate(home, &state.id)
16973            .unwrap_err()
16974            .to_string();
16975        assert!(
16976            store_err.starts_with(
16977                "run already has a live driver: worker store observation failed (conservative protection):"
16978            ),
16979            "{store_err}"
16980        );
16981        assert!(store_err.contains(corrupt_id), "{store_err}");
16982        std::fs::remove_dir_all(&corrupt_dir).unwrap();
16983
16984        // 4. Held execution lease (driver.lock path).
16985        state.driver_exited = false;
16986        state.driver_claimed = Some(false);
16987        state.driver_pid = None;
16988        state.driver_started_at = None;
16989        state.save_under(home).unwrap();
16990        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
16991        let lease_err = crate::resume::validate(home, &state.id)
16992            .unwrap_err()
16993            .to_string();
16994        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
16995        assert!(
16996            lease_err.starts_with("run already has a live driver: execution lease held"),
16997            "{lease_err}"
16998        );
16999        assert!(
17000            lease_err.contains(&lock_path.display().to_string()),
17001            "{lease_err}"
17002        );
17003        drop(exec_lease);
17004
17005        // 5. Live process identity (pid + identity).
17006        let pid = std::process::id();
17007        let identity = crate::proc::process_started_at(pid).expect("current process identity");
17008        state.driver_claimed = None;
17009        state.driver_pid = Some(pid);
17010        state.driver_started_at = Some(identity.clone());
17011        state.save_under(home).unwrap();
17012        let pid_err = crate::resume::validate(home, &state.id)
17013            .unwrap_err()
17014            .to_string();
17015        assert!(
17016            pid_err.starts_with("run already has a live driver: live driver process"),
17017            "{pid_err}"
17018        );
17019        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17020        assert!(
17021            pid_err.contains(&format!("identity={identity}")),
17022            "{pid_err}"
17023        );
17024
17025        // decide_action uses the exact same refusal format for process identity too.
17026        let question = action_question(&state.id, resume_action(&state.id));
17027        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17028            RunState::load_under(id, home)
17029        });
17030        assert_eq!(decision, ActionDecision::Refuse(pid_err));
17031    }
17032}