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        if (repair || stopping)
1092            && let ask::ChoiceAction::Resume { run } = action
1093            && task.execution_runs().last() == Some(run)
1094            && load(run).is_ok_and(|s| s.approval_revoked_by_revision(&q.id))
1095        {
1096            return ActionDecision::Stale;
1097        }
1098        return if repair || stopping {
1099            ActionDecision::Refuse(format!(
1100                "{} 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 {}`",
1101                if repair { "repair" } else { "stop" },
1102                q.id,
1103                q.run,
1104                task.id
1105            ))
1106        } else {
1107            ActionDecision::Stale
1108        };
1109    }
1110    match action {
1111        a if a.maintenance() => ActionDecision::Skip,
1112        ask::ChoiceAction::RecoverBase { .. }
1113        | ask::ChoiceAction::ResumeRun { .. }
1114        | ask::ChoiceAction::ReleaseTask { .. }
1115        | ask::ChoiceAction::RerunChecks { .. }
1116        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1117        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1118        ask::ChoiceAction::Hold => ActionDecision::Hold,
1119        ask::ChoiceAction::Done => ActionDecision::Done,
1120        ask::ChoiceAction::Resume { run } => {
1121            if task.execution_runs().last() != Some(run) {
1122                return ActionDecision::Refuse((p.resume_not_latest)(
1123                    q.short(),
1124                    ask::short_id(run),
1125                ));
1126            }
1127            match load(run) {
1128                // An answer given for an approval that the owner's later
1129                // instruction revision revoked must never resume or merge.
1130                Ok(s) if s.approval_revoked_by_revision(&q.id) => ActionDecision::Stale,
1131                Ok(s) if stopping => {
1132                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1133                        || !s
1134                            .land_approval
1135                            .as_ref()
1136                            .is_some_and(|binding| binding.question == q.id)
1137                    {
1138                        ActionDecision::Stale
1139                    } else if s.liveness_under(home, false) == Liveness::Live {
1140                        ActionDecision::Skip
1141                    } else if s.status == RunStatus::Landing
1142                        && !s.released()
1143                        && s.retired_to.is_none()
1144                    {
1145                        ActionDecision::Resume(run.clone())
1146                    } else {
1147                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1148                    }
1149                }
1150                Ok(s)
1151                    if q.node == land::APPROVAL_NODE
1152                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1153                {
1154                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1155                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1156                    {
1157                        // A live/manual driver already consumed or superseded
1158                        // this answer. Do not hold its fresh approval wait.
1159                        ActionDecision::Stale
1160                    } else if s.liveness_under(home, false) == Liveness::Live {
1161                        ActionDecision::Skip
1162                    } else if s.status != RunStatus::Landing
1163                        || s.released()
1164                        || s.reviews.is_empty()
1165                        || !implementers_match(task, &s)
1166                        || !s
1167                            .land_approval
1168                            .as_ref()
1169                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1170                    {
1171                        ActionDecision::Refuse(format!(
1172                            "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",
1173                            q.id, run, run
1174                        ))
1175                    } else {
1176                        ActionDecision::Resume(run.clone())
1177                    }
1178                }
1179                Ok(s) => {
1180                    let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1181                    if assessment.verdict == Liveness::Live {
1182                        ActionDecision::Refuse(assessment.live_driver_refusal())
1183                    } else {
1184                        match crate::handover::resume_refusal_under(&s, Some(home)) {
1185                            None => ActionDecision::Resume(run.clone()),
1186                            Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1187                                q.short(),
1188                                ask::short_id(run),
1189                                &reason.diagnostic(&s),
1190                            )),
1191                        }
1192                    }
1193                }
1194                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1195                    q.short(),
1196                    ask::short_id(run),
1197                    &format!("{e:#}"),
1198                )),
1199            }
1200        }
1201    }
1202}
1203
1204/// The fixed prose the daemon writes into [`Task::last_error`] and
1205/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1206/// `triage::Wording` and `land::Words`: only English and Japanese are
1207/// translated, anything else falls back to English.
1208///
1209/// Rendered when the reason is *generated*, so a reason keeps the language it
1210/// was written in if the setting changes later. The notification frame
1211/// (`Task <id> is held:`) is not here and stays English.
1212///
1213/// Deliberately **not** translated, because other code reads them back by
1214/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1215/// and `gate red`. IDs, node names, paths and external error text are embedded
1216/// as they are.
1217struct Phrases {
1218    /// `{}` = status label, then the detail.
1219    graph_stopped: fn(&str, &str) -> String,
1220    quorum_lost: &'static str,
1221    /// Followed by the seats' names.
1222    quota_took_out: &'static str,
1223    /// Followed by the status label.
1224    run_ended: &'static str,
1225    /// Followed by the question's short id.
1226    waiting_for_answer: &'static str,
1227    recovered_running: &'static str,
1228    no_run_to_recover: &'static str,
1229    could_not_start: &'static str,
1230    resume_not_latest: fn(&str, &str) -> String,
1231    resume_cannot_progress: fn(&str, &str, &str) -> String,
1232    resume_unreadable: fn(&str, &str, &str) -> String,
1233    /// A takeover refusal: the operator-facing text. English is the error's own
1234    /// `Display`; a translation keeps the machine detail apart in parentheses.
1235    handover_refused: fn(&crate::handover::Refused) -> String,
1236    /// Appended to a refused handover's hold reason (leading space included).
1237    handover_hint: &'static str,
1238    /// (seats that never answered, review rounds) for the review loop's
1239    /// "refusing to call it clean" stop.
1240    reviewers_never_answered: fn(usize, usize) -> String,
1241}
1242
1243const PHRASES_EN: Phrases = Phrases {
1244    graph_stopped: |status, detail| {
1245        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1246    },
1247    quorum_lost: "the judging panel lost its quorum",
1248    quota_took_out: "; quota took out ",
1249    run_ended: "run ended ",
1250    waiting_for_answer: " - waiting for operator answer to question ",
1251    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1252    no_run_to_recover: "task was `running` with no live daemon and no readable \
1253                        run to recover; held for a human to check what happened",
1254    could_not_start: "could not start the run: ",
1255    resume_not_latest: |q, run| {
1256        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1257    },
1258    resume_cannot_progress: |q, run, reason| {
1259        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1260    },
1261    resume_unreadable: |q, run, e| {
1262        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1263    },
1264    handover_refused: |r| r.to_string(),
1265    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1266    reviewers_never_answered: |missing, rounds| {
1267        format!(
1268            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1269             refusing to call it clean"
1270        )
1271    },
1272};
1273
1274const PHRASES_JA: Phrases = Phrases {
1275    graph_stopped: |status, detail| {
1276        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1277    },
1278    quorum_lost: "審査パネルが定足数を失いました",
1279    quota_took_out: "。クォータで脱落: ",
1280    run_ended: "run 終了: ",
1281    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1282    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1283    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1284                        何が起きたか人が確認するため保留にしました",
1285    could_not_start: "run を開始できませんでした: ",
1286    resume_not_latest: |q, run| {
1287        format!(
1288            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1289        )
1290    },
1291    resume_cannot_progress: |q, run, reason| {
1292        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1293    },
1294    resume_unreadable: |q, run, e| {
1295        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1296    },
1297    handover_refused: |r| {
1298        use crate::handover::Refused;
1299        match r {
1300            Refused::Foreign { branch, path, why } => format!(
1301                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1302                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1303                 から、やり直してください(詳細: {why})"
1304            ),
1305            Refused::Unsafe { branch, path, why } => format!(
1306                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1307                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1308                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1309            ),
1310            Refused::ReleaseFailed { branch, path, run } => format!(
1311                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1312                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1313                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1314            ),
1315        }
1316    },
1317    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1318    reviewers_never_answered: |missing, rounds| {
1319        format!(
1320            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1321             クリーンとは認めません"
1322        )
1323    },
1324};
1325
1326fn phrases(language: &str) -> &'static Phrases {
1327    if crate::lang::is_japanese(language) {
1328        &PHRASES_JA
1329    } else {
1330        &PHRASES_EN
1331    }
1332}
1333
1334/// The language of the repository a task belongs to, read best-effort for the
1335/// paths that have no run (and so no config of their own) to ask. An unreadable
1336/// config is English, not an error: a hold reason must still get written.
1337fn language_of(task: &Task, fallback: &Path) -> String {
1338    crate::lang::of_repo(&repo_for(task, fallback))
1339}
1340
1341/// The task an answered question speaks for: the one whose runs include the
1342/// question's run, or - for a conductor question, filed under the task's own
1343/// id - the task with that id.
1344pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1345    if q.node == crate::conduct::NODE {
1346        return tasks.iter().find(|t| t.id == q.run);
1347    }
1348    tasks.iter().find(|t| t.runs.contains(&q.run))
1349}
1350
1351/// Legacy conductor prose never becomes a maintenance command by inference.
1352/// Replace unsupported open labels under the question lock before dispatch.
1353fn repair_choice_offers(questions: &Questions) {
1354    let ownership = crate::task_chat::InquiryOwnership::default();
1355    for q in questions
1356        .list_for_effects_in(&ownership)
1357        .into_iter()
1358        .filter(|q| {
1359            q.status.open()
1360                && q.node == crate::conduct::NODE
1361                && q.choices
1362                    .iter()
1363                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1364        })
1365    {
1366        let _ = questions.update_in(&q.id, &ownership, |current| {
1367            if current.status.open() {
1368                crate::choice_effect::executable_conductor(current);
1369                if let Some(deputy) = &mut current.deputy {
1370                    deputy.brief = crate::deputy::brief(
1371                        &current.run,
1372                        &current.detail,
1373                        &current.choices,
1374                        &current.actions,
1375                    );
1376                }
1377            }
1378            Ok(())
1379        });
1380    }
1381}
1382
1383/// Apply answered typed choices. Only the daemon calls this in production;
1384/// deputies settle the question and never execute its actions.
1385pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1386    apply_maintenance_choices(queue, questions, home).await;
1387    apply_task_choice_actions(queue, questions, home);
1388}
1389
1390/// Apply bounded maintenance effects independently of question ownership: a
1391/// release watcher need not have a queue task, and a predecessor is another run.
1392async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1393    let ownership = crate::task_chat::InquiryOwnership::default();
1394    for q in questions.list_for_effects_in(&ownership) {
1395        // Read again under the same fence used by explicit settlement.
1396        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1397            continue;
1398        };
1399        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1400            continue;
1401        };
1402        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1403            continue;
1404        };
1405        // Receipt paths use question IDs, whose format is independent of run
1406        // IDs. Apply the question store's filename safety rule to both eras.
1407        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1408            continue;
1409        }
1410        if queue.list().iter().any(|task| {
1411            (task.id == q.run
1412                || task.runs.contains(&q.run)
1413                || q.routed_task.as_deref() == Some(&task.id))
1414                && task.stale_question(&q)
1415        }) {
1416            continue;
1417        }
1418        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1419            let tasks = queue.list();
1420            let owner = crate::task_chat::task_of(&q, &tasks);
1421            if let Some(owner) = owner
1422                && q.routed_task
1423                    .as_deref()
1424                    .is_none_or(|routed| routed == owner)
1425            {
1426                let result = crate::base_recovery_control::recover(
1427                    queue,
1428                    home,
1429                    crate::base_recovery_control::Request {
1430                        run: run.clone(),
1431                        head: stop.head.clone(),
1432                        actor: "decisions".into(),
1433                        request: q.id.clone(),
1434                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1435                        expected_stop: Some((stop.clone(), *episode)),
1436                        evidence_digest: None,
1437                    },
1438                )
1439                .await;
1440                if let Err(error) = result {
1441                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1442                    notices::raise_in(home, Notice::warn(
1443                        &format!("base-recovery:{}", q.id),
1444                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1445                    ).link(Link::Run { id: run.clone() }));
1446                }
1447            }
1448            continue;
1449        }
1450        let dir = home.join("choice-actions");
1451        if std::fs::create_dir_all(&dir).is_err() {
1452            continue;
1453        }
1454        let Ok(lock) = std::fs::OpenOptions::new()
1455            .create(true)
1456            .truncate(false)
1457            .write(true)
1458            .open(dir.join(format!("{}.lock", q.id)))
1459        else {
1460            continue;
1461        };
1462        if crate::pr_head::try_lock_file(&lock).is_err() {
1463            continue;
1464        }
1465        let fresh = !home
1466            .join("choice-actions")
1467            .join(format!("{}.json", q.id))
1468            .exists();
1469        let result = async {
1470            let receipt = dir.join(format!("{}.json", q.id));
1471            if receipt.exists() {
1472                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1473                anyhow::ensure!(
1474                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1475                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1476                );
1477                return Ok::<_, anyhow::Error>(());
1478            }
1479            // Never retry an uncertain external effect. The receipt is written
1480            // before calling gh, exactly like release_watch's rerun record.
1481            let record = |status: &str| -> anyhow::Result<()> {
1482                let tmp = receipt.with_extension("tmp");
1483                std::fs::write(
1484                    &tmp,
1485                    serde_json::to_vec(&serde_json::json!({
1486                        "action": action, "status": status,
1487                    }))?,
1488                )?;
1489                std::fs::rename(tmp, &receipt)?;
1490                Ok(())
1491            };
1492            let applied = async {
1493                match action {
1494                    ask::ChoiceAction::ResumeRun { run } => {
1495                        crate::resume::validate(home, run)?;
1496                        record("started")?;
1497                        let decided = q.answered_at.unwrap_or(q.asked_at);
1498                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1499                            crate::resume::validate_unqueued(home, run)?;
1500                            crate::resume::start(home, run.clone()).await?;
1501                        }
1502                    }
1503                    ask::ChoiceAction::ReleaseTask {
1504                        task,
1505                        held_at,
1506                        reason,
1507                    } => {
1508                        anyhow::ensure!(
1509                            queue.resolve_id(task)? == *task,
1510                            "task action requires an exact task ID"
1511                        );
1512                        let _claim = queue.claim(task)?;
1513                        let mut task = queue.get(task)?;
1514                        if task.action_applied(&q.id) {
1515                            return Ok(());
1516                        }
1517                        // Filing this conductor question temporarily wraps the
1518                        // original hold in a Blocked state. Restore only that
1519                        // exact blocker on the local copy before checking the
1520                        // hold binding; unrelated waits never authorize release.
1521                        if q.node == crate::conduct::NODE
1522                            && q.run == task.id
1523                            && task.status == TaskStatus::Blocked
1524                            && task.blocked_from == Some(TaskStatus::Held)
1525                            && task.blocked_by.as_slice() == [q.id.as_str()]
1526                        {
1527                            task.unblock(&q.id);
1528                        }
1529                        anyhow::ensure!(
1530                            task.status == TaskStatus::Held
1531                                && task.held_at == Some(*held_at)
1532                                && task.hold_reason.as_deref() == reason.as_deref()
1533                                && task
1534                                    .operator_decided_at
1535                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1536                            "task no longer has the hold this question names"
1537                        );
1538                        task.release_operator("choice", Some(&q.id));
1539                        task.mark_action_applied(&q.id);
1540                        queue.put(&mut task)?;
1541                    }
1542                    ask::ChoiceAction::AbandonRun { run } => {
1543                        record("started")?;
1544                        crate::driver::abandon_proven_dead(home, run)?;
1545                    }
1546                    ask::ChoiceAction::RerunChecks {
1547                        repo,
1548                        pr,
1549                        head,
1550                        runs,
1551                    } => {
1552                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1553                            .await?;
1554                    }
1555                    _ => unreachable!(),
1556                }
1557                Ok::<_, anyhow::Error>(())
1558            }
1559            .await;
1560            match applied {
1561                Ok(()) => record("applied"),
1562                Err(e) => {
1563                    record(&format!("refused or failed: {e:#}"))?;
1564                    Err(e)
1565                }
1566            }
1567        }
1568        .await;
1569        // Retire the originating blocker as well as the target operation.
1570        // A foreign resume leaves its issuer held instead of competing beside
1571        // the execution just started. Other successful maintenance lets the
1572        // original task retry its normal, guarded path.
1573        if home
1574            .join("choice-actions")
1575            .join(format!("{}.json", q.id))
1576            .exists()
1577            && let Some(listed) = task_of_question(&queue.list(), &q)
1578            && !listed.action_applied(&q.id)
1579            && let Ok(_claim) = queue.claim(&listed.id)
1580            && let Ok(mut origin) = queue.get(&listed.id)
1581        {
1582            if !origin.operator_held()
1583                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1584                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1585            {
1586                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1587                    origin.hold_machine(Some(format!(
1588                        "Maintenance choice {} settled; inspect its target before releasing this task",
1589                        q.id
1590                    )));
1591                } else {
1592                    origin.unblock(&q.id);
1593                }
1594            }
1595            origin.mark_action_applied(&q.id);
1596            let _ = queue.put(&mut origin);
1597        }
1598        if let Err(e) = result
1599            && fresh
1600        {
1601            notices::raise_in(
1602                home,
1603                Notice::warn(
1604                    &format!("action:{}", q.id),
1605                    format!("Choice action {} was not completed: {e:#}", q.id),
1606                )
1607                .link(if q.run_names_task() {
1608                    Link::Task { id: q.run.clone() }
1609                } else {
1610                    Link::Run { id: q.run.clone() }
1611                }),
1612            );
1613        }
1614    }
1615}
1616
1617/// Rerun the named failed workflow runs of a pull request, each at most once
1618/// per `request` (a question id, or a chat operation identity). The head,
1619/// lifecycle and failed state are re-read from the forge first; `started` is
1620/// called once those checks pass and before the first external call, and the
1621/// ledger entry is written before every `gh` call, so an uncertain result is
1622/// never repeated automatically.
1623pub(crate) async fn rerun_checks_once(
1624    home: &Path,
1625    request: &str,
1626    repo: &Path,
1627    pr: &str,
1628    head: &str,
1629    runs: &[String],
1630    started: impl FnOnce() -> anyhow::Result<()>,
1631) -> anyhow::Result<()> {
1632    use crate::release_watch::{GhForge, ReleaseForge};
1633    anyhow::ensure!(
1634        !runs.is_empty()
1635            && runs.len() <= 20
1636            && runs
1637                .iter()
1638                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1639            && !pr.starts_with('-'),
1640        "invalid rerun targets"
1641    );
1642    let snap = GhForge.snapshot(repo, pr).await?;
1643    anyhow::ensure!(
1644        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1645        "pull request head or lifecycle changed"
1646    );
1647    anyhow::ensure!(
1648        runs.iter().all(|r| snap
1649            .checks
1650            .iter()
1651            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1652        "named workflow is no longer failed on this pull request"
1653    );
1654    started()?;
1655    let dir = home.join("choice-actions");
1656    std::fs::create_dir_all(&dir)?;
1657    let rerun_lock = std::fs::OpenOptions::new()
1658        .create(true)
1659        .truncate(false)
1660        .write(true)
1661        .open(dir.join("reruns.lock"))?;
1662    crate::pr_head::try_lock_file(&rerun_lock)?;
1663    let ledger = dir.join("reruns.json");
1664    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1665        serde_json::from_slice(&std::fs::read(&ledger)?)?
1666    } else {
1667        Default::default()
1668    };
1669    for run in runs {
1670        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1671        if !recorded.insert(key) {
1672            continue;
1673        }
1674        let tmp = ledger.with_extension("tmp");
1675        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1676        std::fs::rename(tmp, &ledger)?;
1677        GhForge.rerun(repo, run).await?;
1678    }
1679    Ok(())
1680}
1681
1682/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1683///
1684/// Runs on every poll before the conductor looks at the queue. The task is
1685/// re-read under its claim, so a task somebody completed or held by hand in
1686/// the meantime is judged on what it is now. `Resume` releases the task and
1687/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1688/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1689/// ordinary `unfinished_run` logic resumes that same run.
1690pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1691    let tasks = queue.list();
1692    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1693    for q in questions.list_for_effects_in(&ownership) {
1694        // Read again under the same fence used by explicit settlement.
1695        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1696            continue;
1697        };
1698        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1699            continue;
1700        };
1701        // Dismissal is committed by the question writer, never a resume.
1702        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1703            continue;
1704        }
1705        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1706            continue;
1707        }
1708        let Some(listed) = task_of_question(&tasks, &q) else {
1709            if q.node == land::APPROVAL_NODE
1710                && q.resolution().as_deref().is_some_and(|choice| {
1711                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1712                })
1713            {
1714                notices::raise_in(
1715                    home,
1716                    Notice::warn(
1717                        &format!("repair-owner:{}", q.id),
1718                        format!(
1719                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1720                            q.run, q.run
1721                        ),
1722                    ).link(Link::Run { id: q.run.clone() }),
1723                );
1724            }
1725            continue;
1726        };
1727        if listed.action_applied(&q.id) {
1728            continue;
1729        }
1730        let Ok(_claim) = queue.claim(&listed.id) else {
1731            continue;
1732        };
1733        let Ok(mut task) = queue.get(&listed.id) else {
1734            continue;
1735        };
1736        // Work only on this local copy until the action can be committed.
1737        // In particular, a fresh lease below leaves the persisted task blocked.
1738        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1739            let blockers: Vec<_> = task
1740                .blocked_by
1741                .iter()
1742                .filter(|id| {
1743                    crate::queue::dependency(queue, questions, id)
1744                        == crate::queue::Dependency::Question(q.id.clone())
1745                })
1746                .cloned()
1747                .collect();
1748            if !blockers.is_empty() {
1749                for id in blockers {
1750                    task.unblock(&id);
1751                }
1752                let answer = match &q.answer {
1753                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1754                    None => String::new(),
1755                };
1756                task.record_answer(q.summary.clone(), answer);
1757            }
1758        }
1759        let language = language_of(&task, Path::new("."));
1760        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1761            RunState::load_under(id, home)
1762        });
1763        let completion = if matches!(decision, ActionDecision::Done) {
1764            match crate::task_completion::prepare_close(
1765                &task,
1766                home,
1767                CompletionActor::DaemonSettle,
1768                Some(format!(
1769                    "Question {}: {} — {}",
1770                    q.id,
1771                    q.summary,
1772                    q.resolution().unwrap_or_default()
1773                )),
1774                false,
1775            ) {
1776                Ok(context) => Some(context),
1777                Err(error) => {
1778                    decision = ActionDecision::Refuse(error.to_string());
1779                    None
1780                }
1781            }
1782        } else {
1783            None
1784        };
1785        let ran = matches!(
1786            decision,
1787            ActionDecision::Resume(_)
1788                | ActionDecision::Requeue
1789                | ActionDecision::Hold
1790                | ActionDecision::Done
1791        );
1792        if ran && asker_may_still_read(questions, &q, home) {
1793            // The asking process or its seat can still take the word; act
1794            // once it has gone quiet. Bound on the remaining window: the
1795            // check is not atomic with the write below, so an asker that
1796            // takes the word in between (at most one poll, never more than
1797            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1798            // and `Task::actions_applied` under the claim keeps the action to
1799            // one application. The waiter does not deliver an answer that
1800            // carries an action (`waiter::decide_owned`), so it cannot race.
1801            continue;
1802        }
1803        let done = matches!(decision, ActionDecision::Done);
1804        // Resume owes an execution pass; only these task-local effects finish
1805        // in this write. Stale/refused actions never acquire an effect receipt.
1806        let completed = matches!(
1807            decision,
1808            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1809        );
1810        match decision {
1811            ActionDecision::Skip => continue,
1812            ActionDecision::Resume(run) => {
1813                task.release_operator("choice", Some(&q.id));
1814                task.resume_override = Some(crate::queue::OperatorResume {
1815                    question_id: q.id.clone(),
1816                    at: Timestamp::now(),
1817                    conductor_rehold: None,
1818                    forced: true,
1819                    pinned_run: Some(run),
1820                });
1821            }
1822            ActionDecision::Stale => {}
1823            ActionDecision::Requeue => {
1824                task.release_operator("choice-requeue", Some(&q.id));
1825                task.requeue();
1826            }
1827            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1828            ActionDecision::Done => {
1829                task.succeed(completion.expect("done passed completion admission"));
1830            }
1831            ActionDecision::Refuse(why) => {
1832                let _ =
1833                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1834                if task.operator_held() {
1835                    // A rejected answer does not release the operator's hold
1836                    // or reclassify it as recoverable by the conductor.
1837                    task.hold_reason = Some(match task.hold_reason.take() {
1838                        Some(reason) => format!("{reason}\n\n{why}"),
1839                        None => why,
1840                    });
1841                } else {
1842                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1843                    task.hold_machine(Some(why));
1844                }
1845                notices::raise(
1846                    Notice::warn(
1847                        &format!("action:{}", q.id),
1848                        "An answered task action could not be applied; the task stays held.",
1849                    )
1850                    .link(Link::Task {
1851                        id: task.id.clone(),
1852                    }),
1853                );
1854            }
1855        }
1856        task.mark_action_applied(&q.id);
1857        if completed {
1858            task.decision_effects.insert(
1859                q.id.clone(),
1860                format!("decision: {}", q.resolution().expect("answered action")),
1861            );
1862        }
1863        // The applied id travels with the transition, so a failed save loses
1864        // neither and the answer is acted on at the next poll.
1865        record(queue, &mut task);
1866        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1867            supersede_prior_runs(&task, home);
1868        }
1869        // Delivery is only a note of who has read the answer; the task's own
1870        // mark above is the authority. Best effort.
1871        let _ = questions.update_in(&q.id, &ownership, |r| {
1872            r.answer_delivered = true;
1873            Ok(())
1874        });
1875    }
1876}
1877
1878/// Whether something may still read the answer to `q`: a fresh lease, or the
1879/// asking seat still listed as active in its run (its CLI can outlive the
1880/// `magi ask` that was killed).
1881fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1882    let now = Timestamp::now();
1883    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1884        return true;
1885    }
1886    q.node != crate::conduct::NODE
1887        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1888            s.seats_active()
1889                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1890        })
1891}
1892
1893/// Retire an unanswered conductor question after its task no longer refers to
1894/// it. Conductor questions use the task id in `Question::run`, so run-based
1895/// cleanup cannot observe a manual release or completion.
1896///
1897/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1898/// own question also carries a `run`, and a run id that happens to collide
1899/// with some task's id is not this loop's business — only a conductor
1900/// question actually uses the task id that way. One `Questions::list()` scan
1901/// is taken up front and matched against the in-memory task set, rather than
1902/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1903fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1904    let tasks = queue.list();
1905    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1906    let by_id: std::collections::BTreeMap<&str, &Task> =
1907        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1908    let referenced: Vec<&str> = tasks
1909        .iter()
1910        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1911        .collect();
1912
1913    for mut question in questions.list_for_effects_in(&ownership) {
1914        if !question.status.open()
1915            || question.node != crate::conduct::NODE
1916            || questions.held_reply_in(&question.id, &ownership)
1917        {
1918            continue;
1919        }
1920        // Keep questions a task still names, including when the reference
1921        // moved to a dependent task.
1922        // Preserve even ambiguous references: retiring a possibly referenced
1923        // question is unsafe until the operator disambiguates it.
1924        if referenced
1925            .iter()
1926            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1927        {
1928            continue;
1929        }
1930        let Some(task) = by_id.get(question.run.as_str()) else {
1931            continue;
1932        };
1933        question.abandon(format!(
1934            "task {} no longer waits for this answer",
1935            task.short()
1936        ));
1937        if let Err(e) = questions.put_in(&mut question, &ownership) {
1938            tracing::warn!(
1939                "could not retire question {} for task {}: {e:#}",
1940                question.short(),
1941                task.short()
1942            );
1943        }
1944    }
1945}
1946
1947/// What a finished run tells the queue about the task it came from.
1948///
1949/// A struct rather than a fourth and fifth boolean argument: the two flags
1950/// answer different questions about the same run, and a call site passing
1951/// `(…, true, false)` is one transposition away from refunding attempts
1952/// forever.
1953#[derive(Debug, Clone, Copy)]
1954pub struct Verdict {
1955    /// Where the graph stopped.
1956    pub status: RunStatus,
1957    /// The run opened a pull request.
1958    pub left_pr: bool,
1959    /// At least one seat was lost to a rate limit.
1960    pub quota_hit: bool,
1961    /// The run parked at a node boundary because it was asked to.
1962    pub parked: bool,
1963    /// The run never produced a single candidate a judge could look at.
1964    ///
1965    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1966    /// still have another candidate worth judging, in which case the loss was
1967    /// not the reason nothing came of the run. This is `true` only when the
1968    /// implement wave ended with nothing viable at all.
1969    pub no_viable_candidates: bool,
1970}
1971
1972/// Record a finished run against the task it came from.
1973///
1974/// Kept pure and separate from the loop because this mapping *is* the retry
1975/// policy, and a policy that can only be exercised by spawning a graph is a
1976/// policy nobody checks. The table:
1977///
1978/// | run status                           | task becomes        | attempt spent |
1979/// |---------------------------------------|---------------------|---------------|
1980/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1981/// | `Merged`, `Ready`                      | `Done`               | yes          |
1982/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1983/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1984/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1985/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1986/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1987/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1988/// | `Blocked` with a PR                    | `Held`               | yes          |
1989/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1990/// | `VerifiedNoop`                          | `Held`               | yes          |
1991/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1992///
1993/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1994/// deliberately: every candidate agreeing there is nothing to write is not a
1995/// machine fact about a rate limit, it is an unverified claim about the
1996/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1997/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1998/// claim could be wrong (a misread instruction, a stale check), and closing
1999/// the task automatically on an implementer's say-so would be the exact
2000/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
2001/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
2002/// above, which settles through the same [`Task::handed_off`]: `Held` is not
2003/// `Failed`-and-requeued, so nothing retries this task on the same unverified
2004/// claim regardless of whether the one already-spent attempt is refunded, and
2005/// [`Task::release`] resets the count to zero anyway the moment a human looks
2006/// at the evidence and lets it run again.
2007///
2008/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
2009/// twice, together. A quorum lost to rate limits is a property of the machine
2010/// and not of the task, so the attempt is refunded and a reset quota picks
2011/// the work up where it stopped — and that is just as true when every
2012/// implement seat lost the same race and `after_implement` bails with nothing
2013/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
2014/// machine fact. The `no_viable_candidates` guard is what keeps that row
2015/// narrow: a `Failed` run that produced a real candidate which then lost for
2016/// some other reason still spends the attempt, exactly like the quorum lost
2017/// to judges that answered with the wrong shape is ordinary flakiness, and
2018/// refunding *that* takes the bound off the retry loop entirely: run e633
2019/// stalled with `quota: []` after two judges wrote unusable JSON, was
2020/// refunded, and the next attempt paid for a fresh hour-long implement wave
2021/// before it could fail the same way. `max_attempts` exists precisely so
2022/// that cannot repeat forever.
2023///
2024/// A non-terminal status means `execute` returned while the graph was still
2025/// mid-flight, which is a bug rather than a verdict; it is treated as a
2026/// failure so that a task cannot loop on it either.
2027///
2028/// `left_pr` splits the `Blocked` row, and it is the difference between a run
2029/// that failed and a run that finished into a gate. See [`Task::handed_off`].
2030pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2031    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2032}
2033
2034/// [`settle`], with the daemon's own fixed prose in `p`'s language.
2035fn settle_in(
2036    task: &mut Task,
2037    verdict: Verdict,
2038    detail: &str,
2039    max_attempts: usize,
2040    p: &Phrases,
2041    state: Option<&RunState>,
2042) {
2043    // A parked run is the operator's own doing, and its work is intact on
2044    // disk. The task goes back in line with its attempt refunded so the next
2045    // loop resumes the same run - which `one_task` prefers over competing
2046    // again - and so that swapping the binary a few times cannot exhaust a
2047    // budget meant for agents that actually misbehaved.
2048    if verdict.parked {
2049        task.park(detail);
2050        return;
2051    }
2052    let completion = |task: &Task| match state {
2053        Some(state) => CompletionContext::from_run(
2054            CompletionActor::DaemonSettle,
2055            Some(detail.to_owned()),
2056            task,
2057            state,
2058        ),
2059        None => CompletionContext::new(
2060            CompletionActor::DaemonSettle,
2061            Some(detail.to_owned()),
2062            &crate::run::home(),
2063            task,
2064        ),
2065    };
2066    match verdict.status {
2067        RunStatus::Merged | RunStatus::Ready
2068            if task.pr_recovery.as_ref().is_some_and(|s| {
2069                s.disposition != Some(crate::pr_recovery::Disposition::Review)
2070            }) =>
2071        {
2072            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()));
2073        }
2074        RunStatus::Merged => {
2075            if task.investigation && task.current_investigation_result().is_none() {
2076                task.hold_unrequested_retry(Some(
2077                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2078                        .into(),
2079                ));
2080            } else {
2081                task.succeed(completion(task));
2082            }
2083        }
2084        RunStatus::Ready => {
2085            if task.investigation {
2086                if task.current_investigation_result().is_some() {
2087                    task.succeed(completion(task));
2088                } else {
2089                    task.hold_unrequested_retry(Some(
2090                        "Investigation finished without recorded findings; complete it with a nonblank --result."
2091                            .into(),
2092                    ));
2093                }
2094            } else if state.is_some_and(crate::landing::run_landed_for_settle) {
2095                task.succeed(completion(task));
2096            } else {
2097                // `Ready` means mergeable, not merged: `[merge] mode = "none"`,
2098                // an empty winner, or an unmerged PR all stop here. Keep the
2099                // branch and attempt intact without re-competing.
2100                let reason = "Ready but not landed: the run finished without a confirmed merge \
2101                    into the base branch, so the task is not done. Review the retained branch \
2102                    and land it (then `magi task done`), release the task to run it again, or \
2103                    mark it with `magi task investigation` if it was never meant to change the \
2104                    repository."
2105                    .to_owned();
2106                if let Some(run_id) = state
2107                    .map(|s| s.id.clone())
2108                    .or_else(|| task.execution_runs().last().cloned())
2109                {
2110                    task.hold_awaiting_landing(run_id, reason);
2111                } else {
2112                    task.hold_unrequested_retry(Some(reason));
2113                }
2114            }
2115        }
2116        RunStatus::AlreadyInBase => {
2117            if task.investigation && task.current_investigation_result().is_none() {
2118                task.hold_unrequested_retry(Some(
2119                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2120                        .into(),
2121                ));
2122            } else {
2123                task.already_landed(detail, completion(task));
2124            }
2125        }
2126        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2127        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2128            task.stall(detail)
2129        }
2130        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2131        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2132        RunStatus::Blocked => task.fail(detail, max_attempts),
2133        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2134            task.handed_off(detail)
2135        }
2136        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2137        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2138    }
2139}
2140
2141/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
2142/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
2143/// itself has actually finished *and* its own last attempt is provably why:
2144/// this loads that run and requires `Merged`/`Ready` before touching
2145/// anything earlier in `runs`, since `Task::succeed` can also be called
2146/// directly on a task whose last attempt never landed at all.
2147///
2148/// Called right after whatever call set `task.status` to
2149/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
2150/// `reclaim`'s, but also every other place a task can be closed by hand
2151/// without the loop ever settling it itself: `magi task done`
2152/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
2153/// (`web::queue_done`). Closing a task by hand — after confirming a manual
2154/// GitHub merge, say, exactly the workflow this repository's own
2155/// "Landing a run's winner by hand" documents — is just as much "this task's
2156/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
2157/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
2158/// forever, which is the exact backlog this status exists to clear. `pub`
2159/// for those two out-of-module callers; everything else about this stays
2160/// internal bookkeeping.
2161///
2162/// A run something is still actually driving is left alone: a
2163/// task cannot be `Done` while one of its *own* attempts is still in flight,
2164/// so a live one at this point can only be an unrelated process — a manual
2165/// `--resume` of this old, now-moot run — and rewriting under it would just
2166/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
2167/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
2168/// pair `run_report`/`run_detail` use for the same question elsewhere:
2169/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
2170/// --resume` invoked by hand outside it, which `liveness` also checks via
2171/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
2172/// (already terminal in some other way, or itself mid-run) is left untouched
2173/// too.
2174///
2175/// Best-effort, like the rest of this module's bookkeeping: a load or save
2176/// failure here is a `tracing::warn`, not a failed settle, and the next time
2177/// this same task's completion is recorded — or a daemon restart replays
2178/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2179/// separate reconciliation pass; if that gap ever matters in practice, one
2180/// can be added then.
2181///
2182/// `home` is a parameter, not the process-global [`crate::run::home`], for
2183/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2184/// calls this with `ui.home`, which is `crate::run::home()` in a real
2185/// process but a fixture's own directory under test — falling through to
2186/// the global there would read and write through whichever home some other
2187/// test in the same binary happened to pin into that `OnceLock` first, not
2188/// the run this call actually means.
2189pub fn supersede_prior_runs(task: &Task, home: &Path) {
2190    if task
2191        .completion_history
2192        .last()
2193        .is_some_and(|event| event.discard)
2194    {
2195        return;
2196    }
2197    let now = Timestamp::now();
2198    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2199    // right behind a `Merged`/`Ready` verdict) from one set directly by
2200    // `magi task done`/its web equivalent/the conductor on a task whose last
2201    // recorded attempt never actually landed - that requires reading the
2202    // run itself, which is exactly what this does before trusting anything
2203    // in `runs` is safe to relabel.
2204    let last_run_succeeded = task
2205        .runs
2206        .last()
2207        .and_then(|id| RunState::load_under(id, home).ok())
2208        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2209    for id in task.superseded_attempts(last_run_succeeded) {
2210        let mut state = match RunState::load_under(id, home) {
2211            Ok(s) => s,
2212            Err(e) => {
2213                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2214                continue;
2215            }
2216        };
2217        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2218            continue;
2219        }
2220        let daemon_claims = is_working_on(home, id, now);
2221        if state.liveness(daemon_claims) == Liveness::Live {
2222            continue;
2223        }
2224        state.status = RunStatus::Superseded;
2225        if let Err(e) = state.save_under(home) {
2226            tracing::warn!("could not mark run {id} superseded: {e:#}");
2227        }
2228    }
2229}
2230
2231/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2232/// finish the moment it was called, because one of its earlier attempts was
2233/// still live then - a `magi run --resume` invoked by hand on an old run,
2234/// most likely.
2235///
2236/// That skip is correct at the time (rewriting under a run something is
2237/// still actively saving would just be undone), but recording a completion
2238/// does not schedule another settlement, so without this nothing would look at it
2239/// again: if that manual process later ends anywhere other than
2240/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2241/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2242/// backlog this status exists to clear. Called on the same idle-only
2243/// cadence as [`janitor`], next to it rather than folded into it: this
2244/// walks `queue` and `janitor` never otherwise needs one.
2245///
2246/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2247/// more than one attempt, every pass: each call is a handful of local file
2248/// reads bounded by that task's own attempt count, the same order of cost
2249/// [`clean::fold_due`] already pays scanning every run on disk on the same
2250/// cadence, and a task already fully resolved costs one failed liveness
2251/// check turned no-op the moment its lingering attempt is no longer live.
2252fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2253    for task in queue.list() {
2254        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2255            continue;
2256        }
2257        supersede_prior_runs(&task, home);
2258    }
2259}
2260
2261/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2262/// task ends up held.
2263///
2264/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2265/// dead daemon never got back to) share this, so the two cannot drift into
2266/// disagreeing about which held tasks get a diagnostic.
2267fn settle_and_diagnose(
2268    task: &mut Task,
2269    verdict: Verdict,
2270    detail: &str,
2271    max_attempts: usize,
2272    state: &RunState,
2273) {
2274    let mut verdict = verdict;
2275    let mut detail = detail;
2276    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2277        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2278        // to bypass settlement into a no-change handoff, and never rewrite the
2279        // historical run record on disk: settle the task as an ordinary failure.
2280        verdict.status = RunStatus::Failed;
2281        verdict.quota_hit = false;
2282        detail = "no-change result lacks verified evidence";
2283    }
2284    let p = phrases(&state.config.graph.language);
2285    // Shared by normal completion and crash recovery, under the task claim.
2286    // No new attempt can own the task until the old driver has exited.
2287    if let Some(d) = &state.merge_decision {
2288        use crate::merge_decision as md;
2289        if task
2290            .execution_runs()
2291            .last()
2292            .is_some_and(|id| id != &state.id)
2293        {
2294            return;
2295        }
2296        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2297            if task.investigation && task.current_investigation_result().is_none() {
2298                task.hold_unrequested_retry(Some(
2299                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2300                        .into(),
2301                ));
2302            } else {
2303                task.succeed(CompletionContext::from_run(
2304                    CompletionActor::DaemonSettle,
2305                    Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2306                    task,
2307                    state,
2308                ));
2309            }
2310        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2311            if state.liveness(false) != Liveness::Dead {
2312                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2313                return;
2314            }
2315            let replacement = md::Replacement {
2316                question: d.question.clone(),
2317                run: state.id.clone(),
2318                pr: d.target.pr.clone(),
2319                agent: agent.to_owned(),
2320                context: format!(
2321                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2322                    d.target.pr,
2323                    state.id,
2324                    serde_json::to_string(&state.reviews).unwrap_or_default()
2325                ),
2326            };
2327            task.requeue();
2328            task.pr_recovery = None;
2329            task.review_of = None;
2330            task.replacement = Some(replacement);
2331        } else {
2332            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2333                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2334            } 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())) }));
2335        }
2336        task.mark_action_applied(&d.question);
2337        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2338            task.decision_effects
2339                .insert(d.question.clone(), format!("decision: {}", d.choice));
2340        }
2341        if let Some(pass) = state.passes.last() {
2342            task.record_pass_at(
2343                &state.id,
2344                pass.index,
2345                Some(pass.started_at),
2346                task.attempts,
2347                None,
2348            );
2349        }
2350        return;
2351    }
2352    if let Some(replacement) = &task.replacement
2353        && !state.parked
2354        && state.resource_block.is_none()
2355        && (state.viable().is_empty()
2356            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2357    {
2358        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)));
2359        return;
2360    }
2361    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2362        let mut agents: Vec<_> = state
2363            .quota
2364            .iter()
2365            .filter(|q| {
2366                q.cause == crate::agent::QuotaCause::Authentication
2367                    && state
2368                        .passes
2369                        .last()
2370                        .is_none_or(|pass| q.at >= pass.started_at)
2371            })
2372            .map(|q| q.agent.as_str())
2373            .collect();
2374        agents.sort_unstable();
2375        agents.dedup();
2376        if !agents.is_empty() {
2377            task.stall(detail);
2378            task.notice_cause("agent-authentication", None, None);
2379            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2380            return;
2381        }
2382    }
2383    let attempts_before = task.attempts;
2384    // A run that stopped because a shared resource stayed busy was never a
2385    // failure of the task or of an agent. Earlier nodes may have run; only
2386    // the blocked operation lacks a result. The attempt is
2387    // refunded and the task is held by the machine, under a reason `triage`
2388    // can re-check, so the same run resumes with the same agents once the
2389    // resource is free. A park request still wins (it is the operator's).
2390    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2391        let disk_checked_at = task.disk_checked_at;
2392        task.notice_cause(
2393            &format!("resource:{}:{}", block.kind, block.node),
2394            None,
2395            None,
2396        );
2397        task.last_error = Some(detail.to_owned());
2398        task.diagnostic = None;
2399        task.attempts = task.attempts.saturating_sub(1);
2400        if block.kind == "agent authentication" {
2401            task.hold_machine(Some(format!(
2402                "[authentication] {}; no attempt was spent",
2403                block.detail
2404            )));
2405        } else if block.kind == "agent usage limit" {
2406            // Usage limits keep the existing cooldown-and-resume policy.
2407            if let Some(agent) = &state.config.graph.selected_implementer {
2408                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.")));
2409            } else {
2410                task.status = TaskStatus::Failed;
2411                task.last_error = Some(block.detail.clone());
2412            }
2413        } else if block.kind == "disk pressure" {
2414            task.hold_machine(Some(format!(
2415                "{}{}",
2416                crate::disk::RUNNING_PRESSURE,
2417                block.detail
2418            )));
2419        } else {
2420            task.hold_machine(Some(format!(
2421                "{}{}; no attempt was spent; resume to retry the affected operation",
2422                crate::cache::RESOURCE_HOLD,
2423                block.description()
2424            )));
2425        }
2426        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2427            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2428        {
2429            task.mark_disk_capacity();
2430            task.disk_checked_at = disk_checked_at;
2431        }
2432        if let Some(pass) = state.passes.last() {
2433            task.record_pass_at(
2434                &state.id,
2435                pass.index,
2436                Some(pass.started_at),
2437                attempts_before,
2438                None,
2439            );
2440        }
2441        return;
2442    }
2443    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2444        state.parked
2445            && state.status == RunStatus::Landing
2446            && state
2447                .pr_pushed_head
2448                .as_ref()
2449                .is_none_or(|h| h == &hold.head)
2450            && task.execution_runs().last() == Some(&state.id)
2451    }) {
2452        // Settlement and crash recovery share this idempotency key. A later
2453        // explicit resume is a new pass and may refund its own attempt once.
2454        let pass = state.passes.last().map_or(0, |p| p.index);
2455        if !task
2456            .passes
2457            .iter()
2458            .any(|p| p.run == state.id && p.pass_index == pass)
2459        {
2460            task.attempts = task.attempts.saturating_sub(1);
2461        }
2462        task.hold_machine(Some(format!(
2463            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2464            hold.question
2465        )));
2466        task.last_error = Some(detail.to_owned());
2467        task.diagnostic = None;
2468        task.record_pass_at(
2469            &state.id,
2470            pass,
2471            state.passes.last().map(|p| p.started_at),
2472            attempts_before,
2473            Some(crate::run::ParkCause::Question),
2474        );
2475        return;
2476    }
2477    let unresolved = task.hold_notice_cause.clone();
2478    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2479        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2480    let mut reconsumed_head_e2e = false;
2481    if state.base_sync_blocked() {
2482        // No automatic retry may turn a retained sync stop into a new competition.
2483        task.hold_machine(Some(detail.to_owned()));
2484        task.last_error = Some(detail.to_owned());
2485    } else if state.land_sync_exhausted() {
2486        task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2487        task.last_error = Some(detail.to_owned());
2488    } else if !verdict.parked
2489        && task
2490            .pr_recovery
2491            .as_ref()
2492            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2493        && matches!(
2494            verdict.status,
2495            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2496        )
2497    {
2498        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2499            if task.investigation && task.current_investigation_result().is_none() {
2500                task.hold_unrequested_retry(Some(
2501                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2502                        .into(),
2503                ));
2504            } else {
2505                task.succeed(CompletionContext::from_run(
2506                    CompletionActor::DaemonSettle,
2507                    Some(detail.to_owned()),
2508                    task,
2509                    state,
2510                ));
2511            }
2512        } else {
2513            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()));
2514        }
2515    } else if !verdict.parked
2516        && task.pr_recovery.is_some()
2517        && matches!(
2518            verdict.status,
2519            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2520        )
2521        && !verdict.quota_hit
2522    {
2523        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.")));
2524    } else if let Some(stop) = head_e2e_stop.clone() {
2525        // Conclusive current-head E2E red settles directly to one actionable
2526        // machine hold instead of cycling through runnable `Failed` passes.
2527        // Refund only when this pass provably reconsumed an earlier stop with
2528        // no new verification events, idempotently across reclaim/re-settle.
2529        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2530            reconsumed_head_e2e = true;
2531            let pass = state.passes.last().map_or(0, |p| p.index);
2532            if !task
2533                .passes
2534                .iter()
2535                .any(|p| p.run == state.id && p.pass_index == pass)
2536            {
2537                task.attempts = task.attempts.saturating_sub(1);
2538            }
2539        }
2540        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2541        task.hold_head_e2e(stop, reason, detail.to_owned());
2542    } else {
2543        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2544    }
2545    if !verdict.parked
2546        && !verdict.quota_hit
2547        && !reconsumed_head_e2e
2548        && matches!(
2549            verdict.status,
2550            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2551        )
2552    {
2553        task.recovery_failed(state);
2554    }
2555    if state.prep_failure.is_some() {
2556        // Minting a run whose candidates could not be prepared is not work
2557        // on a newly approved attempt. Keep the unresolved outcome anchor.
2558        task.hold_notice_cause = unresolved;
2559        task.startup_notice_cause("startup-candidates");
2560    }
2561    // Written here, where the refund (or not) is decided, so the history is a
2562    // fact and not a later guess from the run's status.
2563    if let Some(pass) = state.passes.last() {
2564        let parked = match &pass.end {
2565            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2566            _ => None,
2567        };
2568        task.record_pass_at(
2569            &state.id,
2570            pass.index,
2571            Some(pass.started_at),
2572            attempts_before,
2573            parked,
2574        );
2575    }
2576    if task.status == TaskStatus::Held {
2577        if state.base_sync_blocked() {
2578            task.base_sync_notice(state);
2579        } else if state.land_sync_exhausted() {
2580            task.land_sync_notice(state);
2581        } else if let Some(stop) = &head_e2e_stop {
2582            task.head_e2e_notice(stop);
2583        } else if task.has_awaiting_landing_cause() {
2584            task.notice_cause(
2585                "awaiting-landing",
2586                Some(&state.id),
2587                state.passes.last().map(|p| p.index),
2588            );
2589        } else if state.prep_failure.is_none() {
2590            task.notice_cause(
2591                label(verdict.status),
2592                Some(&state.id),
2593                state.passes.last().map(|p| p.index),
2594            );
2595        }
2596        if !task.has_awaiting_landing_cause() {
2597            task.diagnostic = diagnostic(state);
2598        }
2599        note_open_question(task, &state.id, p);
2600    }
2601}
2602
2603/// If `task` is held with a `magi ask` question still open on `run`, name the
2604/// question in [`Task::hold_reason`] rather than leaving the hold reading
2605/// only [`describe`]'s run summary.
2606///
2607/// This is the shape task 20260928-191407-05fd left underspecified: an
2608/// implementer settled a verified no-op and filed a question for the
2609/// operator, and the hold that followed said nothing about the question
2610/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2611/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2612/// marker) and must keep seeing it unchanged.
2613///
2614/// Best-effort: an unreadable question store must not stop a run from
2615/// settling, so this is a no-op rather than a propagated error when
2616/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2617fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2618    let Some(home) = crate::run::try_home() else {
2619        return;
2620    };
2621    let open = Questions::at(home.join("questions")).open_for(run);
2622    let Some(q) = open.first() else {
2623        return;
2624    };
2625    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2626    decisions.sort_unstable();
2627    task.notice_cause(
2628        &format!("questions:{}", decisions.join(",")),
2629        Some(run),
2630        None,
2631    );
2632    let base = task.hold_reason.clone().unwrap_or_default();
2633    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2634}
2635
2636/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2637/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2638/// by some other means entirely, like a manual `magi run` resume that
2639/// finishes the graph outside the queue's bookkeeping.
2640///
2641/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2642/// `settle` is separate from `attempt`: a task recovered this way must land
2643/// exactly where a live daemon would have put it — the same policy table,
2644/// not a second one that quietly drifts from it — and that is only checkable
2645/// without spawning a real run.
2646fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2647    if let Some(request) = task.sync_only.clone() {
2648        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2649        return;
2650    }
2651    match last_run {
2652        Some(state) => {
2653            let verdict = Verdict {
2654                status: state.status,
2655                left_pr: state.pr.is_some(),
2656                quota_hit: state.quota.iter().any(|loss| {
2657                    state
2658                        .passes
2659                        .last()
2660                        .is_none_or(|pass| loss.at >= pass.started_at)
2661                }),
2662                parked: state.parked,
2663                no_viable_candidates: state.viable().is_empty(),
2664            };
2665            let detail = format!(
2666                "{}{}",
2667                phrases(&state.config.graph.language).recovered_running,
2668                describe(&state)
2669            );
2670            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2671        }
2672        None => {
2673            // No run, so no config of its own: `language` is the task's
2674            // repository's setting, read by the caller.
2675            let why = phrases(language).no_run_to_recover;
2676            task.last_error = Some(why.to_owned());
2677            // The phone shows `hold_reason`, so a task held by the machine
2678            // says why there too and not only in `last_error`.
2679            task.notice_cause("missing-run", None, None);
2680            task.hold_machine(Some(why.to_owned()));
2681        }
2682    }
2683}
2684
2685/// Find every task left at `running` that no live process is actually
2686/// driving, and settle each one against whatever its last run became.
2687///
2688/// # Why a claim is proof, not a guess
2689///
2690/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2691/// `running`, and the guard is held for the task's whole time in that status:
2692/// `attempt` does not return, and the loop does not move past the scope
2693/// holding the claim, until the run has settled. So a `running` task whose
2694/// lock is gone cannot have a live owner — this process or any other —
2695/// without needing a staleness threshold or a pid check the way
2696/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2697/// task that never got as far as `running` at all. Taking the claim here is
2698/// the whole test: it either fails, because something really does hold it
2699/// and the task is left alone, or it succeeds, which is the proof — and it is
2700/// kept for the rest of the decision so nothing else can start a competing
2701/// run while this one is being written.
2702///
2703/// Called on every poll, not only at startup, for the reason
2704/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2705/// keep noticing this, not only on the one morning it happened to restart.
2706fn reclaim_orphaned_running(
2707    queue: &Queue,
2708    max_attempts: usize,
2709    live_workers: &std::collections::BTreeSet<String>,
2710) -> Vec<String> {
2711    let mut reclaimed = Vec::new();
2712    for listed in queue.list() {
2713        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2714            continue;
2715        }
2716        let Ok(_claim) = queue.claim(&listed.id) else {
2717            continue;
2718        };
2719        // Re-read under the claim: a release or an edit landed by a human
2720        // between the listing above and the claim just taken must not be
2721        // clobbered by a decision based on the stale copy.
2722        let Ok(mut task) = queue.get(&listed.id) else {
2723            continue;
2724        };
2725        if task.status != TaskStatus::Running {
2726            continue;
2727        }
2728        let last_run = task
2729            .execution_runs()
2730            .last()
2731            .and_then(|id| RunState::load(id).ok());
2732        // `execute` normally abandons a run's own open questions the moment
2733        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2734        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2735        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2736        // with the question still `open`, because the process died before
2737        // reaching that call. `reclaim` itself stays pure on purpose (see its
2738        // own doc), so the same cleanup runs here instead, against the run
2739        // this reclaim is already reading. `settle_run` costs nothing when
2740        // `execute` already got there first.
2741        if let Some(state) = &last_run
2742            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2743        {
2744            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2745        }
2746        let language = if last_run.is_none() {
2747            language_of(&task, Path::new("."))
2748        } else {
2749            String::new()
2750        };
2751        reclaim(&mut task, last_run, max_attempts, &language);
2752        if task.status == TaskStatus::Done {
2753            supersede_prior_runs(&task, &crate::run::home());
2754        }
2755        record(queue, &mut task);
2756        reclaimed.push(task.id.clone());
2757    }
2758    reclaimed
2759}
2760
2761/// Find every run whose `run.json` is provably dead — every seat it still
2762/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2763/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2764/// not merely "no daemon claims it" — and fail it, clearing the leftover
2765/// active seats so the run stops reading as `implementing` (or whichever
2766/// node) forever.
2767///
2768/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2769/// `running`, using whatever `run.json` already says — but nothing in that
2770/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2771/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2772/// never got back to sits exactly where it was left: `active` full of seats
2773/// nobody will ever answer for, `status` stuck on whatever node was in
2774/// flight. `magi show` already tells an operator this in prose (`no live
2775/// daemon claims this run right now`); this is what makes that fact durable
2776/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2777/// stay stuck once nothing is driving it.
2778///
2779/// Runs on every poll, not only at startup, for the reason
2780/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2781/// daemon up for days must keep noticing a run some other, now-dead, daemon
2782/// left behind just as readily as one it trips over on the way up.
2783///
2784/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2785/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2786/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2787/// `runs` directory instead: `home` here is a parameter precisely so a test
2788/// can point it away from the operator's real history (see [`drive`]'s own
2789/// doc), and a scan that fell through to the global home anyway would walk
2790/// whichever directory some *other* process or test pinned into that
2791/// `OnceLock` first — mutating runs this call was never handed.
2792fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2793    reclaim_abandoned_runs_with(
2794        home,
2795        now,
2796        crate::proc::pid_status,
2797        crate::proc::process_started_at,
2798    )
2799}
2800
2801/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2802/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2803/// for the identical reason: this sweep's real damage (wiping a run's active
2804/// seats and failing it) has to be provable against an injected answer in a
2805/// test, not just the real process table.
2806fn reclaim_abandoned_runs_with<F, G>(
2807    home: &Path,
2808    now: Timestamp,
2809    query: F,
2810    identity: G,
2811) -> Vec<String>
2812where
2813    F: Fn(u32) -> Option<bool>,
2814    G: Fn(u32) -> Option<String>,
2815{
2816    let mut abandoned = Vec::new();
2817    for entry in std::fs::read_dir(home.join("runs"))
2818        .into_iter()
2819        .flatten()
2820        .flatten()
2821    {
2822        let id = entry.file_name().to_string_lossy().into_owned();
2823        if !crate::run::is_run_id(&id) {
2824            continue;
2825        }
2826        // Serialize the proof and save with claims and takeover: a new
2827        // execution must not be overwritten after the liveness observation.
2828        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2829            continue;
2830        };
2831        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2832        // that module's docs for why a run this cannot parse is left alone
2833        // rather than guessed at. A different schema number is not that: this
2834        // touches only `status` and `active`, never a field whose meaning a
2835        // schema bump changed, so an old record's values serve this exactly
2836        // as well as a current one's (see `clean::read_state`'s own doc for
2837        // the same reasoning applied to folding).
2838        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2839            continue;
2840        };
2841        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2842            continue;
2843        };
2844        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2845            continue;
2846        }
2847        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2848        // it", which is also the normal, healthy shape of a manual `magi
2849        // run` / `magi review` sharing this same home — this scan walks
2850        // every run on disk, not only ones this daemon itself started. Such
2851        // a run's active seats can legitimately sit past their own timeout
2852        // for a little while (the CLI finishing up, its result still being
2853        // collected) without the process driving it having died. `liveness`
2854        // is what actually tells the two apart, by corroborating
2855        // `driver_pid` against the process it names — see its own doc. Only
2856        // its strongest, provable answer licenses wiping this run's active
2857        // seats and failing it out from under whatever is still running it.
2858        let daemon_claims = is_working_on(home, &id, now);
2859        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2860            != crate::run::Liveness::Dead
2861        {
2862            continue;
2863        }
2864        state.abandon("daemon");
2865        if let Err(e) = state.save_under(home) {
2866            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2867            continue;
2868        }
2869        // This run never passes through `Runner::execute` again, so its end
2870        // is announced here.
2871        if let Some(notice) = notices::run_ended(&state) {
2872            notices::raise_in(home, notice);
2873        }
2874        // The seat that asked is gone for good now, exactly like any other
2875        // door `graph::Runner::settle_questions` closes the moment `status`
2876        // lands somewhere non-resumable - see that method's own doc. Nothing
2877        // else reaches this one before the next `janitor()` startup pass
2878        // (`clean::abandon_settled_questions`), and a daemon that stays up
2879        // for days must not leave an open question badging the operator
2880        // until it happens to restart.
2881        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2882            tracing::warn!("abandon questions for {id}: {e:#}");
2883        }
2884        abandoned.push(id);
2885    }
2886    abandoned
2887}
2888
2889#[derive(Debug, Clone, Serialize, Deserialize)]
2890struct TaskWorker {
2891    opts: Opts,
2892    queue: PathBuf,
2893    task: String,
2894    #[serde(default)]
2895    lane: PermitKind,
2896    #[serde(default)]
2897    standalone: bool,
2898}
2899
2900#[doc(hidden)]
2901pub struct TaskWorkerLease {
2902    pub job: crate::worker::Job,
2903    dir: PathBuf,
2904    lease: Option<crate::worker::Lease>,
2905}
2906
2907impl TaskWorkerLease {
2908    pub fn release_lease(&mut self) {
2909        self.lease = None;
2910    }
2911}
2912
2913impl Drop for TaskWorkerLease {
2914    fn drop(&mut self) {
2915        self.release_lease();
2916        let _ = std::fs::remove_dir_all(&self.dir);
2917    }
2918}
2919
2920/// Reserve a task worker without launching a process, for integration tests.
2921#[doc(hidden)]
2922pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2923    let request = TaskWorker {
2924        opts: Opts::default(),
2925        queue: home.join("queue"),
2926        task: task.to_owned(),
2927        lane: PermitKind::default(),
2928        standalone: true,
2929    };
2930    let (job, lease) = crate::worker::running_fixture(
2931        home,
2932        &format!("task:{task}"),
2933        serde_json::to_value(request)?,
2934    )?;
2935    Ok(TaskWorkerLease {
2936        dir: home.join("workers").join("jobs").join(&job.id),
2937        job,
2938        lease: Some(lease),
2939    })
2940}
2941
2942fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2943    Ok(crate::worker::active(home)?
2944        .into_iter()
2945        .filter(|job| job.kind == "task")
2946        .collect())
2947}
2948
2949fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2950    task_jobs(home)?
2951        .into_iter()
2952        .filter_map(
2953            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2954                Ok(request) if !request.standalone => Some(Ok(job)),
2955                Ok(_) => None,
2956                Err(error) => Some(Err(error.into())),
2957            },
2958        )
2959        .collect()
2960}
2961
2962/// Whether an independent scheduler can be controlled without its web parent.
2963#[must_use]
2964pub fn managed(home: &Path) -> bool {
2965    match crate::worker::active(home) {
2966        Err(error) => {
2967            tracing::error!("cannot determine scheduler ownership: {error:#}");
2968            true
2969        }
2970        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2971        Ok(_) => {
2972            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2973                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2974        }
2975    }
2976}
2977
2978/// Start a detached, singleton scheduler using this executable generation.
2979pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2980    anyhow::ensure!(
2981        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2982        "the scheduler is stopping; wait for retirement before starting it again"
2983    );
2984    crate::worker::spawn(
2985        home,
2986        "scheduler",
2987        "scheduler",
2988        serde_json::to_value(opts.absolute()?)?,
2989    )
2990    .await
2991}
2992
2993fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2994    home.join("worker-parks").join(format!("{}.json", job.id))
2995}
2996
2997fn request_task_park(
2998    home: &Path,
2999    job: &crate::worker::Job,
3000    cause: crate::run::ParkCause,
3001) -> Result<()> {
3002    let path = park_request_path(home, job);
3003    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
3004    std::fs::write(path, serde_json::to_vec(&cause)?)?;
3005    crate::worker::request(home, &job.key, crate::worker::Control::Park)
3006}
3007
3008/// Stop dispatch immediately; only an explicit park reaches existing workers.
3009pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
3010    if control == crate::worker::Control::Park {
3011        for job in owned_task_jobs(home)? {
3012            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
3013        }
3014    }
3015    crate::worker::request(home, "scheduler", control)
3016}
3017
3018/// Resolve what a restart would replace without signalling the scheduler.
3019pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
3020    if let Some(job) = crate::worker::active(home)?
3021        .into_iter()
3022        .find(|job| job.kind == "scheduler")
3023    {
3024        return serde_json::from_value(job.payload)
3025            .context("read detached scheduler options")
3026            .map(Some);
3027    }
3028    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
3029        && crate::worker::try_lease(home, "scheduler")?.is_none()
3030    {
3031        let path = home.join("scheduler-options.json");
3032        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
3033        return serde_json::from_slice(&body)
3034            .context("decode detached scheduler options")
3035            .map(Some);
3036    }
3037    Ok(None)
3038}
3039
3040/// Replace the scheduler, leaving all active task and conversation jobs alone.
3041pub async fn restart_detached(home: &Path) -> Result<()> {
3042    let Some(opts) = scheduler_restart_options(home)? else {
3043        return Ok(());
3044    };
3045    request_control(home, crate::worker::Control::Stop)?;
3046    loop {
3047        let reserved = crate::worker::active(home)?
3048            .iter()
3049            .any(|job| job.kind == "scheduler");
3050        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
3051            break;
3052        }
3053        tokio::time::sleep(Duration::from_millis(100)).await;
3054    }
3055    spawn_detached(home, &opts).await?;
3056    Ok(())
3057}
3058
3059/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
3060pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3061    let opts: Opts = serde_json::from_value(payload)?;
3062    let _ = home;
3063    serve_until(opts, Stop::new()).await
3064}
3065
3066/// Execute and settle one task with the queue claim owned by this process.
3067pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3068    let request: TaskWorker = serde_json::from_value(payload)?;
3069    let queue = Queue::at(request.queue);
3070    let key = format!("task:{}", request.task);
3071    let job = task_jobs(home)?
3072        .into_iter()
3073        .find(|job| job.key == key)
3074        .context("task worker reservation is missing")?;
3075    let park_path = park_request_path(home, &job);
3076    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
3077    // our durable reservation. Never execute before that ownership hand-off.
3078    let _claim = loop {
3079        match queue.claim(&request.task) {
3080            Ok(claim) => break claim,
3081            Err(e) if e.is::<crate::queue::InstructionAdoptionPending>() => return Ok(()),
3082            // Only contention (the claim file exists) is worth waiting out; an
3083            // I/O failure must end this worker instead of pinning its lane.
3084            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3085                return Err(e.context("claim the task for its worker"));
3086            }
3087            Err(_) => {
3088                sweep_stale_claims(&queue, STALE_CLAIM);
3089                tokio::time::sleep(Duration::from_millis(50)).await;
3090            }
3091        }
3092    };
3093    let mut task = queue.get(&request.task)?;
3094    if !task.status.runnable()
3095        || (!request.standalone
3096            && request.lane
3097                != permit_kind(
3098                    land_resume_state(&task) == LandResume::Ready,
3099                    task.immediate,
3100                    task.urgent,
3101                ))
3102    {
3103        return Ok(());
3104    }
3105    let stop = Stop::new();
3106    let watcher = {
3107        let home = home.to_path_buf();
3108        let stop = stop.clone();
3109        let park_path = park_path.clone();
3110        tokio::spawn(async move {
3111            loop {
3112                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3113                    let cause = std::fs::read(&park_path)
3114                        .ok()
3115                        .and_then(|body| serde_json::from_slice(&body).ok())
3116                        .unwrap_or(crate::run::ParkCause::Operator);
3117                    stop.park(cause);
3118                    // Publication of the control precedes delivery to the
3119                    // pause handle. Record delivery for observers.
3120                    if let Err(error) = std::fs::write(park_path.with_extension("ack"), "") {
3121                        tracing::warn!("could not record park delivery: {error}");
3122                    }
3123                    return;
3124                }
3125                tokio::time::sleep(Duration::from_millis(200)).await;
3126            }
3127        })
3128    };
3129    let quota = if request.standalone {
3130        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3131    } else {
3132        let status = Arc::new(Mutex::new(Status::new()));
3133        Box::pin(attempt(
3134            &request.opts,
3135            &queue,
3136            &status,
3137            &stop,
3138            crate::graph::Pause::new(),
3139            &mut task,
3140        ))
3141        .await
3142    };
3143    watcher.abort();
3144    let _ = watcher.await;
3145    let _ = std::fs::remove_file(park_path.with_extension("ack"));
3146    let _ = std::fs::remove_file(park_path);
3147    persist_cooldown(home, &quota).await?;
3148    Ok(())
3149}
3150
3151/// Launch the standalone task worker with a claim-to-reservation handoff.
3152/// Returns only after the worker owns a durable execution reservation.
3153pub async fn spawn_claimed(
3154    home: &Path,
3155    opts: &Opts,
3156    queue: &Queue,
3157    task: &Task,
3158    claim: crate::queue::Claim,
3159) -> Result<crate::worker::Job> {
3160    let request = TaskWorker {
3161        opts: opts.absolute()?,
3162        queue: std::path::absolute(queue.root())?,
3163        task: task.id.clone(),
3164        lane: permit_kind(
3165            land_resume_state(task) == LandResume::Ready,
3166            task.immediate,
3167            task.urgent,
3168        ),
3169        standalone: true,
3170    };
3171    let job = crate::worker::spawn(
3172        home,
3173        "task",
3174        &format!("task:{}", task.id),
3175        serde_json::to_value(request)?,
3176    )
3177    .await?;
3178    drop(claim);
3179    Ok(job)
3180}
3181
3182/// Transfer a standalone caller's claim only after the detached worker is live,
3183/// then follow that worker to its final (non-automatically-retrying) outcome.
3184pub async fn run_detached_claimed(
3185    opts: &Opts,
3186    queue: &Queue,
3187    task: &mut Task,
3188    claim: crate::queue::Claim,
3189) -> Result<()> {
3190    let home = crate::run::home();
3191    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3192    loop {
3193        // Reconcile execution leases even without a scheduler. A dead worker
3194        // must become a reported failure, never an infinite persisted wait.
3195        crate::worker::active(&home)?;
3196        let current = crate::worker::get(&home, &job.id)?;
3197        if matches!(
3198            current.status,
3199            crate::worker::Status::Finished | crate::worker::Status::Failed
3200        ) {
3201            *task = queue.get(&task.id)?;
3202            anyhow::ensure!(
3203                current.status != crate::worker::Status::Failed,
3204                "task worker failed: {}",
3205                current.result.as_deref().unwrap_or("unknown failure")
3206            );
3207            return Ok(());
3208        }
3209        tokio::time::sleep(Duration::from_millis(200)).await;
3210    }
3211}
3212
3213async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3214    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3215        let _lease = loop {
3216            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3217                break lease;
3218            }
3219            tokio::time::sleep(Duration::from_millis(10)).await;
3220        };
3221        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3222            let path = home.join("task-quota-cooldown.json");
3223            let temporary = path.with_extension("json.tmp");
3224            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3225            std::fs::rename(temporary, path)?;
3226        }
3227    }
3228    Ok(())
3229}
3230
3231fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3232    match std::fs::read(home.join("task-quota-cooldown.json")) {
3233        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3234        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3235        Err(error) => Err(error.into()),
3236    }
3237}
3238
3239/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3240///
3241/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3242/// sets, so there is one loop body rather than two that drift apart the first
3243/// time the retry policy changes on only one of them.
3244pub async fn serve(opts: Opts) -> Result<()> {
3245    tracing::info!(
3246        "automatic update and restart requires magi web; standalone serve does not restart"
3247    );
3248    serve_until(opts, Stop::new()).await
3249}
3250
3251/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3252///
3253/// A stop retires dispatch promptly, including while a worker launch is being
3254/// acknowledged. Already reserved workers own their attempts independently and
3255/// finish with their started executable. Explicit park additionally forwards
3256/// durable park requests; neither scheduler retirement nor update does so.
3257///
3258/// While the queue is empty the stop is honoured within one wakeup rather than
3259/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3260/// caller that taps stop does not sit through the remainder of a sleep.
3261pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3262    let opts = opts.absolute()?;
3263    let home = crate::run::home();
3264    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3265        .context("another scheduler already owns this home")?;
3266    if let Some(reading) = read_status(&home)
3267        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3268    {
3269        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3270    }
3271    if !crate::worker::active(&home)?
3272        .iter()
3273        .any(|job| job.kind == "scheduler")
3274    {
3275        crate::worker::clear_control(&home, "scheduler")?;
3276    }
3277    std::fs::write(
3278        home.join("scheduler-options.json"),
3279        serde_json::to_vec(&opts)?,
3280    )?;
3281    let control = {
3282        let home = home.clone();
3283        let stop = stop.clone();
3284        tokio::spawn(async move {
3285            loop {
3286                match crate::worker::control(&home, "scheduler").ok().flatten() {
3287                    Some(crate::worker::Control::Park) => {
3288                        let _ = request_control(&home, crate::worker::Control::Park);
3289                        stop.park(crate::run::ParkCause::Operator);
3290                        break;
3291                    }
3292                    Some(crate::worker::Control::Stop) => {
3293                        stop.stop();
3294                        break;
3295                    }
3296                    None => {}
3297                }
3298                tokio::time::sleep(Duration::from_millis(100)).await;
3299            }
3300        })
3301    };
3302    let signal = {
3303        let stop = stop.clone();
3304        tokio::spawn(async move {
3305            if tokio::signal::ctrl_c().await.is_ok() {
3306                stop.stop();
3307                tracing::info!("scheduler shutdown requested; independent workers continue");
3308            }
3309        })
3310    };
3311
3312    let worktrees_root = opts
3313        .worktrees_root
3314        .clone()
3315        .unwrap_or_else(crate::run::default_worktree_root);
3316    let outcome = drive(
3317        &opts,
3318        &Queue::open(),
3319        &status_path(),
3320        &crate::run::home(),
3321        &worktrees_root,
3322        &stop,
3323    )
3324    .await;
3325
3326    signal.abort();
3327    control.abort();
3328    outcome
3329}
3330
3331/// The loop proper: setup, poll, teardown, with the queue and the status file
3332/// supplied rather than discovered.
3333///
3334/// All three of `home`, `worktrees_root` and the queue/status paths are
3335/// parameters rather than resolved here, for the same reason:
3336/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3337/// so a unit test that pinned it would fight every other test in the binary,
3338/// and a loop that resolved its own worktree bay could only be exercised
3339/// against the operator's real `~/wt/<repo>` - publishing over a live
3340/// daemon's status file, claiming tasks out of a live backlog, and, since
3341/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3342/// whatever the operator actually has on disk.
3343async fn drive(
3344    opts: &Opts,
3345    queue: &Queue,
3346    status_file: &Path,
3347    home: &Path,
3348    worktrees_root: &Path,
3349    stop: &Stop,
3350) -> Result<()> {
3351    // The status file is a *snapshot*, not a stream of events: a reader only
3352    // ever wants the latest values, and every tick rewrites the whole file
3353    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3354    // while an mpsc channel would force the loop to re-send unchanged fields on
3355    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3356    // for no gain. The lock is only ever held across a field assignment, never
3357    // across an await.
3358    let recovery_cfg = prepare(&opts.repo, opts).ok();
3359    let daemon_cfg = recovery_cfg
3360        .as_ref()
3361        .map(|c| c.daemon.clone())
3362        .unwrap_or_default();
3363    let reconciled = crate::driver::reconcile(home);
3364    if !reconciled.is_empty() {
3365        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3366    }
3367    let mut initial_status = Status::new();
3368    let owned = owned_task_jobs(home)?;
3369    initial_status.current = current_work(home, Timestamp::now())
3370        .into_iter()
3371        .filter(|current| {
3372            owned
3373                .iter()
3374                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3375        })
3376        .collect();
3377    initial_status.idle = initial_status.current.is_empty();
3378    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3379        recovery_cfg.as_ref(),
3380        daemon_cfg.max_deputies,
3381    ));
3382    let status = Arc::new(Mutex::new(initial_status));
3383    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3384    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3385
3386    // Read once at startup, not per task: how many runs this loop drives at
3387    // once is a property of the machine running it, not of whichever
3388    // repository a given task happens to name - see
3389    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3390    // fact in the same sense the agent roster is.
3391    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3392
3393    tracing::info!(
3394        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3395        queue.root().display(),
3396        opts.poll.as_secs(),
3397        opts.max_attempts,
3398        concurrency,
3399        if daemon_cfg.pause_for_interrupts {
3400            ", interrupts enabled"
3401        } else {
3402            ""
3403        }
3404    );
3405
3406    let outcome = tokio::select! {
3407        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3408            max_concurrent: concurrency,
3409            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3410            recovery_cfg,
3411        }) => outcome,
3412        () = async {
3413            while !stop.stopped() {
3414                tokio::time::sleep(Duration::from_millis(25)).await;
3415            }
3416        } => {
3417            if stop.parking() {
3418                request_control(home, crate::worker::Control::Park)?;
3419            }
3420            Ok(())
3421        }
3422    };
3423
3424    stop.busy.store(0, Ordering::SeqCst);
3425    beat.abort();
3426    clear_status_at(status_file);
3427    outcome
3428}
3429
3430/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3431/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3432pub(crate) fn release_watch_settings_from_config(
3433    home: &Path,
3434    repo: &Path,
3435    cfg: &Config,
3436) -> (Vec<PathBuf>, u64) {
3437    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3438        .into_iter()
3439        .map(|r| r.path)
3440        .collect();
3441    // Repositories the daemon has worked in, wherever they live: a task may
3442    // name one outside `[repos] roots`, and its release PR must be watched too.
3443    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3444        .list()
3445        .into_iter()
3446        .map(|t| t.repo)
3447        .collect();
3448    let runs = home.join("runs");
3449    for id in crate::run::list_ids_in(&runs) {
3450        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3451            .ok()
3452            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3453            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3454        known.extend(repo);
3455    }
3456    for k in known {
3457        let k = k.canonicalize().unwrap_or(k);
3458        if k.join(".git").exists() && !paths.contains(&k) {
3459            paths.push(k);
3460        }
3461    }
3462    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3463    if !paths.contains(&own) {
3464        paths.push(own);
3465    }
3466    (paths, cfg.daemon.release_stall_minutes)
3467}
3468
3469/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3470const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3471
3472/// Refresh the status file on a fixed tick.
3473///
3474/// Separate from the loop because a run takes tens of minutes: a status file
3475/// written only between tasks would look stale for the whole of every run, and
3476/// a reader would report the daemon dead exactly while it was busiest.
3477async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3478    loop {
3479        tokio::time::sleep(HEARTBEAT).await;
3480        let snapshot = {
3481            let mut guard = lock(&status);
3482            guard.updated_at = Timestamp::now();
3483            guard.clone()
3484        };
3485        if let Err(e) = write_status_to(&path, &snapshot) {
3486            // A failed heartbeat must not take the daemon down: the loop is the
3487            // product, the status file is only the window onto it.
3488            tracing::warn!("could not refresh the daemon status file: {e:#}");
3489        }
3490    }
3491}
3492
3493/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3494/// if so, whether that wait is over.
3495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3496enum LandResume {
3497    /// The task's last run is not parked on a land approval; schedule it
3498    /// like any other candidate.
3499    NotLanding,
3500    /// Parked in `land`, waiting on a question nobody has answered yet.
3501    /// Left alone: attempting it now would only re-observe the same pull
3502    /// request and park again, spending a `gh` call on a decision that has
3503    /// not changed since the last time this was checked.
3504    StillWaiting,
3505    /// Parked in `land`, and the question is settled - answered or
3506    /// abandoned. Resuming this is the one kind of candidate that must not
3507    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3508    Ready,
3509}
3510
3511/// Classify a runnable candidate by whether it is parked on a land-merge
3512/// approval. Read-only - no claim taken, nothing written - so it is cheap
3513/// enough to call on every candidate, every poll.
3514fn land_resume_state(task: &Task) -> LandResume {
3515    if task.sync_only.is_some() {
3516        return LandResume::NotLanding;
3517    }
3518    let Some(run_id) = task.execution_runs().last() else {
3519        return LandResume::NotLanding;
3520    };
3521    let Ok(state) = RunState::load(run_id) else {
3522        return LandResume::NotLanding;
3523    };
3524    if !state.parked {
3525        return LandResume::NotLanding;
3526    }
3527    if state.status == RunStatus::Landing
3528        && state.land_approval.as_ref().is_some_and(|binding| {
3529            ask::Questions::open()
3530                .get_for_effects(&binding.question)
3531                .is_ok_and(|q| {
3532                    q.run == state.id
3533                        && q.resolution()
3534                            .as_deref()
3535                            .is_some_and(crate::merge_decision::stops)
3536                })
3537        })
3538    {
3539        return LandResume::Ready;
3540    }
3541    if !implementers_match(task, &state) {
3542        return LandResume::NotLanding;
3543    }
3544    // Parked in `land` on the merge approval, or at `merge` on the owner's
3545    // word about a title/body the posting gate withheld. Told apart by the
3546    // run's own record, not by a status both can share.
3547    let node = if state.status == RunStatus::Landing {
3548        land::APPROVAL_NODE
3549    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3550        crate::github_text::ASK_NODE
3551    } else {
3552        return LandResume::NotLanding;
3553    };
3554    let store = ask::Questions::open();
3555    let waiting = store
3556        .list_for_effects()
3557        .into_iter()
3558        .filter(|q| &q.run == run_id && q.node == node)
3559        .max_by(|a, b| a.id.cmp(&b.id));
3560    let Some(mut q) = waiting else {
3561        return LandResume::Ready;
3562    };
3563    if !q.status.open() {
3564        // Repair spends agent resources and must obey concurrency and quota
3565        // waits; only a merge/hold decision may use the decision-only lane.
3566        if q.resolution().as_deref() == Some(land::REPAIR) {
3567            return if state.liveness(false) == Liveness::Live {
3568                LandResume::StillWaiting
3569            } else {
3570                LandResume::NotLanding
3571            };
3572        }
3573        return LandResume::Ready;
3574    }
3575    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3576    // nobody ever answered; land's approval bypasses that wait entirely (see
3577    // `land::approval_gate`), so the same deadline has to be enforced here
3578    // instead, or `graph.answer_timeout` silently stops meaning anything for
3579    // a land approval and a run can sit `StillWaiting` forever with nobody
3580    // told to look at it.
3581    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3582    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3583    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3584        q.abandon(format!(
3585            "no answer within {}s of asking",
3586            timeout.as_secs().max(1)
3587        ));
3588        // If this can't be persisted, do not treat the wait as settled on a
3589        // guess: fall through and try again next poll.
3590        if store.put(&mut q).is_ok() {
3591            return LandResume::Ready;
3592        }
3593    }
3594    LandResume::StillWaiting
3595}
3596
3597/// How often the loop rechecks for new work while something it already
3598/// started is still running, rather than sleeping out the whole
3599/// [`Opts::poll`] interval.
3600///
3601/// Short on purpose: this is what lets a land-merge approval that comes back
3602/// while another task is mid-competition be noticed and resumed within a
3603/// fraction of a second, not within the next multi-second poll.
3604const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3605
3606/// How often [`poll`] rechecks the shared build cache against its cap at a
3607/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3608/// waiting for the queue to run dry.
3609///
3610/// A queue that never empties means the `janitor` call at the bottom of this
3611/// loop's fully-idle branch can go unreached for as long as the backlog
3612/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3613/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3614/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3615/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3616/// backlog of short tasks does not pay for that walk on every poll.
3617const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3618
3619/// State of [`poll`]'s own interrupt-scheduling sequence - see
3620/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3621/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3622/// both kept free of `Task`'s non-identity fields on purpose: every decision
3623/// here turns only on task ids and which ones are in flight, so the "never
3624/// more than one run at once" and "exactly one resume" invariants can be
3625/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3626/// queue - which is exactly the coverage this feature's first two attempts
3627/// were missing.
3628///
3629/// Persisted after every transition, so scheduler replacement preserves the
3630/// interrupt's exclusive turn and the interrupted task's priority resume.
3631#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3632enum Interrupt {
3633    /// No interrupt sequence in progress. Ordinary dispatch applies.
3634    Idle,
3635    /// `interrupt_task` is runnable and exactly one other run is in flight;
3636    /// `parked` names that one task's id. Dispatch is withheld from
3637    /// everyone, including `interrupt_task` itself, until it has left
3638    /// flight - only then is `interrupt_task` let through.
3639    ///
3640    /// `parked` is a `Vec` rather than a bare id for symmetry with
3641    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3642    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3643    /// when exactly one run is in flight, so it is guaranteed to hold
3644    /// exactly one entry in practice - see that branch's own doc for why
3645    /// more than one is deliberately never attempted.
3646    Parking {
3647        parked: Vec<String>,
3648        interrupt_task: String,
3649    },
3650    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3651    /// withheld from everyone until it leaves flight - merged, failed, held,
3652    /// it makes no difference - at which point the sequence moves to
3653    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3654    /// going straight to `Idle` would hand `parked` back to ordinary
3655    /// priority-order dispatch, where a higher-priority task filed in the
3656    /// meantime could start ahead of it.
3657    Running {
3658        parked: Vec<String>,
3659        interrupt_task: String,
3660    },
3661    /// `interrupt_task` left flight; `parked` still names the one run this
3662    /// sequence owes a resume. Dispatch is withheld from everyone except
3663    /// that task - see [`interrupt_gate`] - so the resume this feature
3664    /// promises is never raced by, or run alongside, an unrelated candidate.
3665    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3666    /// own doc on abandonment - the moment it is no longer runnable at all.
3667    Resuming { parked: Vec<String> },
3668}
3669
3670/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3671/// and `runnable` are read-only snapshots of this tick's reality, and the
3672/// only side effect the caller still owes the world is asking whichever
3673/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3674/// site.
3675///
3676/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3677/// accepted rather than a narrower type because that is what [`poll`] already
3678/// has on hand from [`runnable`], and building a second, smaller list on
3679/// every tick just to satisfy this signature would cost more than it proves.
3680///
3681/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3682/// back to a task they are waiting on no longer being [`runnable`] - held,
3683/// blocked, deleted, or finished by some other means entirely, all of which
3684/// an operator can do to a task sitting in the queue with no claim on it at
3685/// all, at any moment, interrupt sequence or not. Without this check the
3686/// sequence would wait forever for a dispatch that can never come, and
3687/// `interrupt_gate` would withhold every other task in the queue right along
3688/// with it - a single `magi task hold` on the wrong id turning into a
3689/// daemon that never dispatches anything again.
3690fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3691    match state {
3692        Interrupt::Idle => {
3693            // Not just "something to interrupt": exactly one thing. More
3694            // than one run in flight only happens above the default
3695            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3696            // one resume, never run alongside anything else" only because
3697            // it is only ever seeded with exactly one id - see
3698            // `Interrupt::Resuming`'s own doc on why releasing more than one
3699            // parked id back to ordinary dispatch cannot be made safe
3700            // against that same setting's own extra concurrency slots.
3701            // Waiting here for the herd to settle to one is the
3702            // simplification this feature's own constraints ask for rather
3703            // than a second concurrency model to reconcile with the first.
3704            if in_flight.len() != 1 {
3705                return Interrupt::Idle;
3706            }
3707            match runnable.iter().find(|t| t.interrupt) {
3708                Some(t) => Interrupt::Parking {
3709                    parked: in_flight.to_vec(),
3710                    interrupt_task: t.id.clone(),
3711                },
3712                None => Interrupt::Idle,
3713            }
3714        }
3715        Interrupt::Parking {
3716            parked,
3717            interrupt_task,
3718        } => {
3719            if in_flight.iter().any(|id| parked.contains(id)) {
3720                // Still waiting for what was in flight to actually stop.
3721                Interrupt::Parking {
3722                    parked,
3723                    interrupt_task,
3724                }
3725            } else if in_flight.contains(&interrupt_task) {
3726                Interrupt::Running {
3727                    parked,
3728                    interrupt_task,
3729                }
3730            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3731                // The parked run(s) are gone, but the interrupt task has not
3732                // been dispatched yet on this tick - `interrupt_gate` is
3733                // what lets it through next.
3734                Interrupt::Parking {
3735                    parked,
3736                    interrupt_task,
3737                }
3738            } else {
3739                // The interrupt task itself is no longer runnable - see this
3740                // function's own doc on abandonment. The parked run(s) still
3741                // get their guaranteed resume; there is simply no interrupt
3742                // to run ahead of them any longer.
3743                Interrupt::Resuming { parked }
3744            }
3745        }
3746        Interrupt::Running {
3747            parked,
3748            interrupt_task,
3749        } => {
3750            if in_flight.contains(&interrupt_task) {
3751                Interrupt::Running {
3752                    parked,
3753                    interrupt_task,
3754                }
3755            } else {
3756                // The interrupt task's own run reached a terminal status,
3757                // whichever one - this is the *only* trigger that moves the
3758                // sequence on, driven straight off the same in-flight
3759                // bookkeeping `poll` already reaps every tick, not a second,
3760                // independent poll of anything.
3761                Interrupt::Resuming { parked }
3762            }
3763        }
3764        Interrupt::Resuming { parked } => {
3765            if in_flight.iter().any(|id| parked.contains(id)) {
3766                // One of the parked runs has been dispatched - the resume
3767                // this sequence owed is fulfilled. Whatever else is left in
3768                // `parked` (ordinarily nothing, at the default concurrency
3769                // of one) rejoins ordinary priority-order dispatch, same as
3770                // any other runnable task.
3771                Interrupt::Idle
3772            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3773                Interrupt::Resuming { parked }
3774            } else {
3775                // Abandonment (see this function's own doc): nothing left in
3776                // `parked` is even runnable any longer.
3777                Interrupt::Idle
3778            }
3779        }
3780    }
3781}
3782
3783/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3784/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3785/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3786/// indistinguishable from any other runnable task - exactly the "off does
3787/// nothing" this feature promises.
3788fn advance_interrupt_tick(
3789    enabled: bool,
3790    state: Interrupt,
3791    in_flight: &[String],
3792    runnable: &[Task],
3793) -> Interrupt {
3794    if !enabled {
3795        return Interrupt::Idle;
3796    }
3797    advance_interrupt(state, in_flight, runnable)
3798}
3799
3800/// Which of this tick's runnable candidates the interrupt sequence actually
3801/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3802/// each half is assertable on its own: this is the half that keeps a
3803/// competition and an interrupt from ever running at the same moment.
3804fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3805    match state {
3806        Interrupt::Idle => candidates,
3807        Interrupt::Parking {
3808            parked,
3809            interrupt_task,
3810        } => {
3811            if in_flight.iter().any(|id| parked.contains(id)) {
3812                Vec::new()
3813            } else {
3814                candidates
3815                    .into_iter()
3816                    .filter(|t| &t.id == interrupt_task)
3817                    .collect()
3818            }
3819        }
3820        Interrupt::Running { .. } => Vec::new(),
3821        // At most one: even if `parked` names more than one id (more than
3822        // one run was in flight when the sequence began, only possible
3823        // above the default `max_concurrent_runs = 1`), only the first match
3824        // is offered. Capping this to a single candidate - not merely to
3825        // `parked`'s own ids - is what makes "exactly one resume, never two
3826        // dispatched together" true regardless of how many ordinary slots
3827        // happen to be free this tick.
3828        Interrupt::Resuming { parked } => candidates
3829            .into_iter()
3830            .find(|t| parked.contains(&t.id))
3831            .into_iter()
3832            .collect(),
3833    }
3834}
3835
3836/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3837/// bundled into one parameter so `poll`'s own signature stays readable -
3838/// see [`drive`]'s call site for where these are actually read.
3839struct DispatchLimits {
3840    /// How many *ordinary* candidates run at once. See
3841    /// [`crate::config::Daemon::max_concurrent_runs`].
3842    max_concurrent: usize,
3843    /// See [`crate::config::Daemon::pause_for_interrupts`].
3844    pause_for_interrupts: bool,
3845    recovery_cfg: Option<Config>,
3846}
3847
3848/// Which semaphore, if any, dispatching a candidate should draw its permit
3849/// from.
3850///
3851/// Pure and separate from [`poll`]'s loop body for the same reason
3852/// [`advance_interrupt`] is: the choice between "decision-only land resume",
3853/// "owner-selected immediate lane", "spend the one urgent slot" and "spend an
3854/// ordinary slot" is explicit and directly unit-testable.
3855#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3856pub(crate) enum PermitKind {
3857    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3858    /// Checked first - a task can be both a land resume and marked
3859    /// [`Task::immediate`] or [`Task::urgent`], and the resume's own
3860    /// decision-only lane takes precedence.
3861    None,
3862    /// [`Task::immediate`]: owner-selected immediate execution lane.
3863    /// Consumes no semaphore permit and does not count against ordinary or
3864    /// urgent capacity, allowing multiple immediate tasks to dispatch even
3865    /// when both ordinary and urgent lanes are full. Kept distinct from
3866    /// [`PermitKind::None`] so decision-only resumes and immediate runs stay
3867    /// separable in persisted worker reservations and diagnostics.
3868    Immediate,
3869    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3870    /// (never in addition to trying) the ordinary pool. This is what lets
3871    /// an urgent task dispatch while every ordinary slot is already checked
3872    /// out, and what stops a second urgent task from opening a third run: it
3873    /// waits on this same one-slot semaphore rather than falling through to
3874    /// the ordinary one.
3875    Urgent,
3876    /// The ordinary `max_concurrent_runs` pool - unaffected by any of the
3877    /// above.
3878    #[default]
3879    Ordinary,
3880}
3881
3882impl PermitKind {
3883    pub(crate) fn label(self) -> &'static str {
3884        match self {
3885            Self::None => "decision",
3886            Self::Immediate => "immediate",
3887            Self::Urgent => "urgent",
3888            Self::Ordinary => "ordinary",
3889        }
3890    }
3891}
3892
3893/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3894/// own boolean, already computed by the caller from [`land_resume_state`].
3895/// Precedence: decision resume (`None`) > `Immediate` > `Urgent` > `Ordinary`.
3896fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3897    if priority {
3898        PermitKind::None
3899    } else if immediate {
3900        PermitKind::Immediate
3901    } else if urgent {
3902        PermitKind::Urgent
3903    } else {
3904        PermitKind::Ordinary
3905    }
3906}
3907
3908fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3909    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3910        (0usize, 0usize),
3911        |(ordinary, urgent), request| match request.lane {
3912            PermitKind::Ordinary => (ordinary + 1, urgent),
3913            PermitKind::Urgent => (ordinary, urgent + 1),
3914            PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3915        },
3916    );
3917    (
3918        limit.saturating_sub(ordinary),
3919        1usize.saturating_sub(urgent),
3920    )
3921}
3922
3923/// Why a runnable candidate was not dispatched. This does not alter policy.
3924#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3925enum SkipReason {
3926    ClaimUnavailable,
3927    RereadFailed,
3928    NoLongerRunnable,
3929    WaitingOnLanding,
3930    CoolingDown,
3931    OrdinaryCapacity,
3932    UrgentCapacity,
3933    InterruptGate,
3934}
3935
3936impl SkipReason {
3937    fn key(self) -> &'static str {
3938        match self {
3939            Self::ClaimUnavailable => "claim_unavailable",
3940            Self::RereadFailed => "reread_failed",
3941            Self::NoLongerRunnable => "no_longer_runnable",
3942            Self::WaitingOnLanding => "waiting_on_landing",
3943            Self::CoolingDown => "cooling_down",
3944            Self::OrdinaryCapacity => "ordinary_capacity",
3945            Self::UrgentCapacity => "urgent_capacity",
3946            Self::InterruptGate => "interrupt_gate",
3947        }
3948    }
3949
3950    fn describe(self) -> &'static str {
3951        match self {
3952            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3953            Self::RereadFailed => "could not re-read it",
3954            Self::NoLongerRunnable => "no longer runnable",
3955            Self::WaitingOnLanding => "waiting on landing",
3956            Self::CoolingDown => "quota cooldown",
3957            Self::OrdinaryCapacity => "no free ordinary slot",
3958            Self::UrgentCapacity => "urgent slot busy",
3959            Self::InterruptGate => "withheld by the interrupt sequence",
3960        }
3961    }
3962}
3963
3964/// A reason count from a completed dispatch scan.
3965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3966pub struct DispatchReasonCount {
3967    /// Stable string key, so readers can preserve future reasons.
3968    pub reason: String,
3969    /// Candidates skipped for this reason.
3970    pub count: usize,
3971}
3972
3973/// Observations from a completed scan, not a fresh queue estimate.
3974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3975pub struct DispatchWait {
3976    /// Runnable candidates before the interrupt gate.
3977    pub runnable: usize,
3978    /// Counts in descending order, with stable reason order for ties.
3979    pub reasons: Vec<DispatchReasonCount>,
3980}
3981
3982type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3983
3984fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3985    if runnable == 0 {
3986        return None;
3987    }
3988    let mut counts = std::collections::BTreeMap::new();
3989    for (_, reason) in skips {
3990        *counts.entry(*reason).or_insert(0usize) += 1;
3991    }
3992    let mut counts: Vec<_> = counts.into_iter().collect();
3993    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3994    Some(DispatchWait {
3995        runnable,
3996        reasons: counts
3997            .into_iter()
3998            .map(|(reason, count)| DispatchReasonCount {
3999                reason: reason.key().to_owned(),
4000                count,
4001            })
4002            .collect(),
4003    })
4004}
4005
4006fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
4007    before
4008        .iter()
4009        .filter(|id| !after.iter().any(|task| &task.id == *id))
4010        .map(|id| (id.clone(), SkipReason::InterruptGate))
4011        .collect()
4012}
4013
4014fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
4015    if *previous == current {
4016        return false;
4017    }
4018    *previous = current;
4019    true
4020}
4021
4022/// Read-only task-level admission view shared by CLI (`magi task list` / `show`)
4023/// and Web (`TaskView`). Distinguishes configured mode, active persisted
4024/// reservation lane, and concrete blockers without ever mutating state.
4025#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4026pub struct TaskAdmission {
4027    /// Configured dispatch mode from the task record (`"immediate"`, `"urgent"`, `"ordinary"`).
4028    pub mode: &'static str,
4029    /// Persisted active worker reservation lane, if currently reserved/running
4030    /// (`"decision"`, `"immediate"`, `"urgent"`, `"ordinary"`).
4031    #[serde(default, skip_serializing_if = "Option::is_none")]
4032    pub reservation_lane: Option<&'static str>,
4033    /// True when the active worker reservation is standalone (`magi run`/`review`).
4034    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
4035    pub standalone: bool,
4036    /// Admission state: `"next_poll"`, `"waiting"`, `"running"`, `"completed"`, `"unknown"`.
4037    pub state: &'static str,
4038    /// Human-readable admission status label (e.g. `"Immediate: next poll"`,
4039    /// `"Immediate: waiting — ..."`).
4040    pub label: String,
4041    /// Concrete blocker or unconfirmed-state diagnostic when waiting/unknown/resource-blocked.
4042    #[serde(default, skip_serializing_if = "Option::is_none")]
4043    pub blocker: Option<String>,
4044}
4045
4046/// One read-only snapshot of scheduler, worker, cooldown, and interrupt state
4047/// captured once per list or detail request.
4048#[derive(Debug, Clone)]
4049pub struct AdmissionSnapshot {
4050    now: Timestamp,
4051    daemon: std::result::Result<Option<Reading>, String>,
4052    scheduler_running: bool,
4053    active_workers:
4054        std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
4055    owned_in_flight: Vec<String>,
4056    owned_ordinary_count: usize,
4057    urgent_busy: bool,
4058    cache_service_active: bool,
4059    cooldown_until: std::result::Result<Option<Timestamp>, String>,
4060    interrupt: std::result::Result<Interrupt, String>,
4061}
4062
4063fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
4064    let path = home.join("daemon.json");
4065    match std::fs::read_to_string(&path) {
4066        Ok(body) => serde_json::from_str(&body)
4067            .map(Some)
4068            .map_err(|e| format!("parse {}: {e}", path.display())),
4069        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
4070        Err(e) => Err(format!("read {}: {e}", path.display())),
4071    }
4072}
4073
4074fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
4075    let path = home.join("scheduler-interrupt.json");
4076    match std::fs::read(&path) {
4077        Ok(body) => {
4078            serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
4079        }
4080        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
4081        Err(e) => Err(format!("read {}: {e}", path.display())),
4082    }
4083}
4084
4085fn skip_reason_label(key: &str) -> String {
4086    match key {
4087        "claim_unavailable" => "claimed by another process".to_owned(),
4088        "reread_failed" => "could not re-read task".to_owned(),
4089        "no_longer_runnable" => "no longer runnable".to_owned(),
4090        "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4091        "cooling_down" => "quota cooldown".to_owned(),
4092        "ordinary_capacity" => "no free ordinary slot".to_owned(),
4093        "urgent_capacity" => "urgent slot busy".to_owned(),
4094        "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4095        other => other.replace('_', " "),
4096    }
4097}
4098
4099/// Pure read-only companion to [`land_resume_state`]: reads `home` explicitly
4100/// and never abandons or writes any question file.
4101fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4102    if task.sync_only.is_some() {
4103        return LandResume::NotLanding;
4104    }
4105    let Some(run_id) = task.execution_runs().last() else {
4106        return LandResume::NotLanding;
4107    };
4108    let Ok(state) = RunState::load_under(run_id, home) else {
4109        return LandResume::NotLanding;
4110    };
4111    if !state.parked {
4112        return LandResume::NotLanding;
4113    }
4114    let store = ask::Questions::at(home.join("questions"));
4115    if state.status == RunStatus::Landing
4116        && state.land_approval.as_ref().is_some_and(|binding| {
4117            store.get_for_effects(&binding.question).is_ok_and(|q| {
4118                q.run == state.id
4119                    && q.resolution()
4120                        .as_deref()
4121                        .is_some_and(crate::merge_decision::stops)
4122            })
4123        })
4124    {
4125        return LandResume::Ready;
4126    }
4127    if !implementers_match(task, &state) {
4128        return LandResume::NotLanding;
4129    }
4130    let node = if state.status == RunStatus::Landing {
4131        land::APPROVAL_NODE
4132    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4133        crate::github_text::ASK_NODE
4134    } else {
4135        return LandResume::NotLanding;
4136    };
4137    let waiting = store
4138        .list_for_effects()
4139        .into_iter()
4140        .filter(|q| &q.run == run_id && q.node == node)
4141        .max_by(|a, b| a.id.cmp(&b.id));
4142    let Some(q) = waiting else {
4143        return LandResume::Ready;
4144    };
4145    if !q.status.open() {
4146        if q.resolution().as_deref() == Some(land::REPAIR) {
4147            return if is_working_on(home, &state.id, now) {
4148                LandResume::StillWaiting
4149            } else {
4150                LandResume::NotLanding
4151            };
4152        }
4153        return LandResume::Ready;
4154    }
4155    LandResume::StillWaiting
4156}
4157
4158impl AdmissionSnapshot {
4159    /// Capture scheduler, worker, cooldown, and interrupt state once, read-only.
4160    #[must_use]
4161    pub fn capture(home: &Path, now: Timestamp) -> Self {
4162        let daemon = read_status_checked(home);
4163        let scheduler_running = daemon
4164            .as_ref()
4165            .ok()
4166            .and_then(Option::as_ref)
4167            .is_some_and(|reading| reading.running(now));
4168        let mut cache_service_active = false;
4169        let mut owned_in_flight = Vec::new();
4170        let mut owned_ordinary_count = 0usize;
4171        let mut urgent_busy = false;
4172        let active_workers = match crate::worker::observe_active_detailed(home) {
4173            Ok(entries) => {
4174                let mut map = std::collections::BTreeMap::new();
4175                let mut parse_err = None;
4176                for entry in entries {
4177                    if entry.job.key == "service:daemon-cache" {
4178                        cache_service_active = true;
4179                        continue;
4180                    }
4181                    if entry.job.kind != "task" {
4182                        continue;
4183                    }
4184                    match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4185                        Ok(request) => {
4186                            if !request.standalone {
4187                                owned_in_flight.push(request.task.clone());
4188                                match request.lane {
4189                                    PermitKind::Ordinary => owned_ordinary_count += 1,
4190                                    PermitKind::Urgent => urgent_busy = true,
4191                                    PermitKind::Immediate | PermitKind::None => {}
4192                                }
4193                            }
4194                            map.entry(request.task)
4195                                .and_modify(|existing: &mut (PermitKind, bool)| {
4196                                    if existing.1 && !request.standalone {
4197                                        *existing = (request.lane, request.standalone);
4198                                    }
4199                                })
4200                                .or_insert((request.lane, request.standalone));
4201                        }
4202                        Err(e) => {
4203                            parse_err = Some(format!(
4204                                "invalid task worker payload for {}: {e}",
4205                                entry.job.id
4206                            ));
4207                            break;
4208                        }
4209                    }
4210                }
4211                match parse_err {
4212                    Some(err) => Err(err),
4213                    None => Ok(map),
4214                }
4215            }
4216            Err(e) => Err(format!("{e:#}")),
4217        };
4218        let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4219        let interrupt = read_interrupt_checked(home);
4220        Self {
4221            now,
4222            daemon,
4223            scheduler_running,
4224            active_workers,
4225            owned_in_flight,
4226            owned_ordinary_count,
4227            urgent_busy,
4228            cache_service_active,
4229            cooldown_until,
4230            interrupt,
4231        }
4232    }
4233
4234    fn format_waiting(task: &Task, reason: &str) -> String {
4235        if task.immediate {
4236            format!("Immediate: waiting — {reason}")
4237        } else if task.urgent {
4238            format!("Urgent: waiting — {reason}")
4239        } else {
4240            format!("Waiting — {reason}")
4241        }
4242    }
4243
4244    /// Evaluate admission for `task` using this pre-captured snapshot.
4245    /// Read-only: never mutates queue, run, worker, or question files.
4246    #[must_use]
4247    pub fn evaluate(
4248        &self,
4249        task: &Task,
4250        queue: &Queue,
4251        inv: Option<&crate::blockers::Inventory>,
4252        home: &Path,
4253    ) -> TaskAdmission {
4254        let mode = if task.immediate {
4255            "immediate"
4256        } else if task.urgent {
4257            "urgent"
4258        } else {
4259            "ordinary"
4260        };
4261
4262        if task.status == TaskStatus::Done {
4263            return TaskAdmission {
4264                mode,
4265                reservation_lane: None,
4266                standalone: false,
4267                state: "completed",
4268                label: "Completed".to_owned(),
4269                blocker: None,
4270            };
4271        }
4272
4273        if let Ok(workers) = &self.active_workers
4274            && let Some(&(lane, standalone)) = workers.get(&task.id)
4275        {
4276            let lane_label = lane.label();
4277            let base = if standalone {
4278                format!("Running (standalone, {lane_label} lane)")
4279            } else {
4280                format!("Running ({lane_label} lane)")
4281            };
4282            let resource_blocker = task
4283                .execution_runs()
4284                .last()
4285                .and_then(|run_id| RunState::load_under(run_id, home).ok())
4286                .and_then(|state| state.resource_wait)
4287                .map(|wait| {
4288                    if wait.holder.trim().is_empty() {
4289                        format!("waiting for {}", wait.kind)
4290                    } else {
4291                        format!("waiting for {} ({})", wait.kind, wait.holder)
4292                    }
4293                });
4294            let label = match &resource_blocker {
4295                Some(reason) => format!("{base} — {reason}"),
4296                None => base,
4297            };
4298            return TaskAdmission {
4299                mode,
4300                reservation_lane: Some(lane_label),
4301                standalone,
4302                state: "running",
4303                label,
4304                blocker: resource_blocker,
4305            };
4306        }
4307
4308        if task.status == TaskStatus::Running {
4309            if self.active_workers.is_err() {
4310                let reason = "worker state unreadable".to_owned();
4311                return TaskAdmission {
4312                    mode,
4313                    reservation_lane: None,
4314                    standalone: false,
4315                    state: "unknown",
4316                    label: Self::format_waiting(task, &reason),
4317                    blocker: Some(reason),
4318                };
4319            }
4320            return TaskAdmission {
4321                mode,
4322                reservation_lane: None,
4323                standalone: false,
4324                state: "running",
4325                label: "Running".to_owned(),
4326                blocker: None,
4327            };
4328        }
4329
4330        if task.status == TaskStatus::Blocked {
4331            let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4332            let reason = if !waits.is_empty() {
4333                format!("waiting on dependencies ({})", waits.join(", "))
4334            } else if let Some(block_reason) = &task.block_reason {
4335                format!("blocked ({block_reason})")
4336            } else if !task.blocked_by.is_empty() {
4337                let ids: Vec<_> = task
4338                    .blocked_by
4339                    .iter()
4340                    .map(|id| crate::run::short_of(id))
4341                    .collect();
4342                format!("waiting on dependencies ({})", ids.join(", "))
4343            } else {
4344                "blocked on unresolved dependencies".to_owned()
4345            };
4346            return TaskAdmission {
4347                mode,
4348                reservation_lane: None,
4349                standalone: false,
4350                state: "waiting",
4351                label: Self::format_waiting(task, &reason),
4352                blocker: Some(reason),
4353            };
4354        }
4355
4356        if task.status == TaskStatus::Held {
4357            let reason = match &task.machine_hold_cause {
4358                Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4359                    format!("disk admission ({reason})")
4360                }
4361                Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4362                    let detail = task
4363                        .hold_reason
4364                        .as_deref()
4365                        .unwrap_or("current head verify.e2e failed");
4366                    format!("head e2e hold ({detail})")
4367                }
4368                Some(crate::queue::MachineHoldCause::AwaitingLanding { reason, .. }) => {
4369                    format!("awaiting landing ({reason})")
4370                }
4371                None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4372                    let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4373                    if let Some(rest) = detail.strip_prefix("[resource] ") {
4374                        format!("resource hold ({rest})")
4375                    } else if let Some(rest) = detail.strip_prefix("[config] ") {
4376                        format!("config hold ({rest})")
4377                    } else {
4378                        format!("machine hold ({detail})")
4379                    }
4380                }
4381                None => match task.hold_reason.as_deref() {
4382                    Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4383                    _ => "held (release required)".to_owned(),
4384                },
4385            };
4386            return TaskAdmission {
4387                mode,
4388                reservation_lane: None,
4389                standalone: false,
4390                state: "waiting",
4391                label: Self::format_waiting(task, &reason),
4392                blocker: Some(reason),
4393            };
4394        }
4395
4396        // Runnable (`Queued` | `Failed` | `Parked`): evaluate non-concurrency
4397        // gates first, never claiming dispatchability on unconfirmed state and
4398        // never attributing ordinary/urgent capacity waits to immediate tasks.
4399        if self.active_workers.is_err() {
4400            let reason = "worker state unreadable".to_owned();
4401            return TaskAdmission {
4402                mode,
4403                reservation_lane: None,
4404                standalone: false,
4405                state: "unknown",
4406                label: Self::format_waiting(task, &reason),
4407                blocker: Some(reason),
4408            };
4409        }
4410
4411        if queue.is_claimed(&task.id) {
4412            let reason = "claimed by another process".to_owned();
4413            return TaskAdmission {
4414                mode,
4415                reservation_lane: None,
4416                standalone: false,
4417                state: "waiting",
4418                label: Self::format_waiting(task, &reason),
4419                blocker: Some(reason),
4420            };
4421        }
4422
4423        if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4424            let reason = format!("head e2e stop ({})", hold.reason);
4425            return TaskAdmission {
4426                mode,
4427                reservation_lane: None,
4428                standalone: false,
4429                state: "waiting",
4430                label: Self::format_waiting(task, &reason),
4431                blocker: Some(reason),
4432            };
4433        }
4434
4435        let resume = land_resume_state_readonly(task, home, self.now);
4436        if resume == LandResume::StillWaiting {
4437            let reason = "waiting on merge/posting approval".to_owned();
4438            return TaskAdmission {
4439                mode,
4440                reservation_lane: None,
4441                standalone: false,
4442                state: "waiting",
4443                label: Self::format_waiting(task, &reason),
4444                blocker: Some(reason),
4445            };
4446        }
4447        let priority = resume == LandResume::Ready;
4448        let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4449
4450        match &self.interrupt {
4451            Err(_) => {
4452                let reason = "interrupt state unreadable".to_owned();
4453                return TaskAdmission {
4454                    mode,
4455                    reservation_lane: None,
4456                    standalone: false,
4457                    state: "unknown",
4458                    label: Self::format_waiting(task, &reason),
4459                    blocker: Some(reason),
4460                };
4461            }
4462            Ok(interrupt)
4463                if *interrupt != Interrupt::Idle
4464                    && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4465                        .is_empty() =>
4466            {
4467                let reason = "withheld by active interrupt sequence".to_owned();
4468                return TaskAdmission {
4469                    mode,
4470                    reservation_lane: None,
4471                    standalone: false,
4472                    state: "waiting",
4473                    label: Self::format_waiting(task, &reason),
4474                    blocker: Some(reason),
4475                };
4476            }
4477            Ok(_) => {}
4478        }
4479
4480        if effective_lane != PermitKind::None {
4481            match &self.cooldown_until {
4482                Err(_) => {
4483                    let reason = "quota cooldown state unreadable".to_owned();
4484                    return TaskAdmission {
4485                        mode,
4486                        reservation_lane: None,
4487                        standalone: false,
4488                        state: "unknown",
4489                        label: Self::format_waiting(task, &reason),
4490                        blocker: Some(reason),
4491                    };
4492                }
4493                Ok(Some(until)) if self.now < *until => {
4494                    let secs = (until.as_second() - self.now.as_second()).max(1);
4495                    let reason = format!("quota cooldown ({secs}s remaining)");
4496                    return TaskAdmission {
4497                        mode,
4498                        reservation_lane: None,
4499                        standalone: false,
4500                        state: "waiting",
4501                        label: Self::format_waiting(task, &reason),
4502                        blocker: Some(reason),
4503                    };
4504                }
4505                Ok(_) => {}
4506            }
4507        }
4508
4509        if self.cache_service_active {
4510            let reason = "waiting for cache maintenance service".to_owned();
4511            return TaskAdmission {
4512                mode,
4513                reservation_lane: None,
4514                standalone: false,
4515                state: "waiting",
4516                label: Self::format_waiting(task, &reason),
4517                blocker: Some(reason),
4518            };
4519        }
4520
4521        if self.daemon.is_err() {
4522            let reason = "scheduler status unreadable".to_owned();
4523            return TaskAdmission {
4524                mode,
4525                reservation_lane: None,
4526                standalone: false,
4527                state: "unknown",
4528                label: Self::format_waiting(task, &reason),
4529                blocker: Some(reason),
4530            };
4531        }
4532
4533        if self.scheduler_running
4534            && let Ok(Some(reading)) = &self.daemon
4535            && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4536        {
4537            let stale_capacity_skip = match effective_lane {
4538                PermitKind::None | PermitKind::Immediate => {
4539                    matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4540                }
4541                PermitKind::Urgent => skip_key == "ordinary_capacity",
4542                PermitKind::Ordinary => skip_key == "urgent_capacity",
4543            };
4544            if !stale_capacity_skip {
4545                let reason = skip_reason_label(skip_key);
4546                return TaskAdmission {
4547                    mode,
4548                    reservation_lane: None,
4549                    standalone: false,
4550                    state: "waiting",
4551                    label: Self::format_waiting(task, &reason),
4552                    blocker: Some(reason),
4553                };
4554            }
4555        }
4556
4557        if !self.scheduler_running {
4558            let reason = "scheduler not running".to_owned();
4559            return TaskAdmission {
4560                mode,
4561                reservation_lane: None,
4562                standalone: false,
4563                state: "waiting",
4564                label: Self::format_waiting(task, &reason),
4565                blocker: Some(reason),
4566            };
4567        }
4568
4569        match effective_lane {
4570            PermitKind::Immediate => TaskAdmission {
4571                mode,
4572                reservation_lane: None,
4573                standalone: false,
4574                state: "next_poll",
4575                label: "Immediate: next poll".to_owned(),
4576                blocker: None,
4577            },
4578            PermitKind::None => TaskAdmission {
4579                mode,
4580                reservation_lane: None,
4581                standalone: false,
4582                state: "next_poll",
4583                label: if task.immediate {
4584                    "Immediate: next poll".to_owned()
4585                } else {
4586                    "Decision resume: next poll".to_owned()
4587                },
4588                blocker: None,
4589            },
4590            PermitKind::Urgent => {
4591                if self.urgent_busy {
4592                    let reason = "urgent slot busy".to_owned();
4593                    TaskAdmission {
4594                        mode,
4595                        reservation_lane: None,
4596                        standalone: false,
4597                        state: "waiting",
4598                        label: Self::format_waiting(task, &reason),
4599                        blocker: Some(reason),
4600                    }
4601                } else {
4602                    TaskAdmission {
4603                        mode,
4604                        reservation_lane: None,
4605                        standalone: false,
4606                        state: "next_poll",
4607                        label: "Urgent: next poll".to_owned(),
4608                        blocker: None,
4609                    }
4610                }
4611            }
4612            PermitKind::Ordinary => {
4613                if self.owned_ordinary_count == 0 {
4614                    TaskAdmission {
4615                        mode,
4616                        reservation_lane: None,
4617                        standalone: false,
4618                        state: "next_poll",
4619                        label: "Ordinary: next poll".to_owned(),
4620                        blocker: None,
4621                    }
4622                } else {
4623                    TaskAdmission {
4624                        mode,
4625                        reservation_lane: None,
4626                        standalone: false,
4627                        state: "waiting",
4628                        label: "Queued (ordinary lane)".to_owned(),
4629                        blocker: None,
4630                    }
4631                }
4632            }
4633        }
4634    }
4635}
4636
4637struct DispatchClaim {
4638    task: Task,
4639    claim: crate::queue::Claim,
4640    lane: PermitKind,
4641    permit: Option<tokio::sync::OwnedSemaphorePermit>,
4642}
4643
4644/// Claim and re-read before choosing a lane: a queue listing may predate an
4645/// immediate or urgent toggle. All unsuccessful paths release the claim
4646/// without an attempt.
4647fn claim_dispatch(
4648    queue: &Queue,
4649    candidate: &Task,
4650    cooling_down: bool,
4651    ordinary: &Arc<tokio::sync::Semaphore>,
4652    urgent: &Arc<tokio::sync::Semaphore>,
4653) -> std::result::Result<DispatchClaim, SkipReason> {
4654    let claim = queue
4655        .claim(&candidate.id)
4656        .map_err(|_| SkipReason::ClaimUnavailable)?;
4657    let task = match queue.get(&candidate.id) {
4658        Ok(t) if t.status.runnable() => t,
4659        Ok(_) => return Err(SkipReason::NoLongerRunnable),
4660        Err(e) => {
4661            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4662            return Err(SkipReason::RereadFailed);
4663        }
4664    };
4665    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4666        let mut held = task;
4667        hold.apply(&mut held);
4668        record(queue, &mut held);
4669        return Err(SkipReason::NoLongerRunnable);
4670    }
4671    let resume = land_resume_state(&task);
4672    if resume == LandResume::StillWaiting {
4673        return Err(SkipReason::WaitingOnLanding);
4674    }
4675    let priority = resume == LandResume::Ready;
4676    if !priority && cooling_down {
4677        return Err(SkipReason::CoolingDown);
4678    }
4679    // Never borrow an ordinary slot when the single urgent slot is busy.
4680    // Immediate tasks consume neither ordinary nor urgent permits.
4681    // Keep scanning other candidates when either pool has no free slot.
4682    let lane = permit_kind(priority, task.immediate, task.urgent);
4683    let permit = match lane {
4684        PermitKind::None | PermitKind::Immediate => None,
4685        PermitKind::Urgent => Some(
4686            Arc::clone(urgent)
4687                .try_acquire_owned()
4688                .map_err(|_| SkipReason::UrgentCapacity)?,
4689        ),
4690        PermitKind::Ordinary => Some(
4691            Arc::clone(ordinary)
4692                .try_acquire_owned()
4693                .map_err(|_| SkipReason::OrdinaryCapacity)?,
4694        ),
4695    };
4696    // Persist the dispatch order under the claim, before config discovery or
4697    // coordination waits can reorder concurrent starts.
4698    let stamp = Timestamp::now();
4699    let mut task = task;
4700    task.dispatched_at = Some(stamp);
4701    if let Err(e) = queue.modify(&task.id, |t| {
4702        t.dispatched_at = Some(stamp);
4703        true
4704    }) {
4705        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4706    }
4707    Ok(DispatchClaim {
4708        task,
4709        claim,
4710        lane,
4711        permit,
4712    })
4713}
4714
4715/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
4716/// teardown and cannot skip the teardown on an early return.
4717///
4718/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
4719/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
4720/// land approval that has since been answered is dispatched outside that
4721/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
4722/// the whole point of parking there is that it must not queue behind
4723/// whatever else the loop happens to be running, even at the default of one.
4724/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
4725/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
4726/// these exemptions is still subject to the interrupt gate below, urgent
4727/// included: a land-resume or urgent candidate is exactly as much "something
4728/// else running" as an ordinary one from the interrupt sequence's point of
4729/// view, and letting either slip through while a run is being parked, or
4730/// while the interrupt task itself has the floor, is precisely the second
4731/// run 75dd's own "at most one run, ever, at once" guarantee must never
4732/// allow - see [`Interrupt`]'s own doc.
4733#[derive(Serialize, Deserialize)]
4734struct ServiceWorker {
4735    opts: Opts,
4736    queue: PathBuf,
4737    worktrees_root: PathBuf,
4738    operation: String,
4739}
4740
4741fn load_conductor(home: &Path) -> Result<Conductor> {
4742    match std::fs::read(home.join("conductor-state.json")) {
4743        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4744        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4745        Err(error) => Err(error.into()),
4746    }
4747}
4748
4749fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4750    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4751        .into_iter()
4752        .map(|c| c.task)
4753        .collect();
4754    let stalled = stalled_tasks(queue, home, Timestamp::now());
4755    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4756    let finished = finished_tasks(queue)
4757        .into_iter()
4758        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4759        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4760        .filter(|t| !t.has_awaiting_landing_cause())
4761        .collect();
4762    let queued = queued_tasks(queue)
4763        .into_iter()
4764        .filter(|t| !live.contains(&t.id))
4765        .collect();
4766    (queued, stalled, finished)
4767}
4768
4769// Separate latest dispatch and worker receipts expose version handoff and skips
4770// without erasing the last completed scan or treating observations as authority.
4771fn retention_service_receipt(
4772    home: &Path,
4773    operation: &str,
4774    phase: &str,
4775    outcome: &str,
4776    detail: &str,
4777    cfg: Option<&Config>,
4778) {
4779    retention_service_receipt_with(
4780        home,
4781        operation,
4782        phase,
4783        outcome,
4784        detail,
4785        cfg,
4786        serde_json::Value::Null,
4787    );
4788}
4789
4790/// [`retention_service_receipt`] plus `extra`: an object whose fields (the
4791/// fold turn's per-outcome counts and cursor, a retention pass's failures) are
4792/// added to the same receipt file rather than to a store of their own.
4793fn retention_service_receipt_with(
4794    home: &Path,
4795    operation: &str,
4796    phase: &str,
4797    outcome: &str,
4798    detail: &str,
4799    cfg: Option<&Config>,
4800    extra: serde_json::Value,
4801) {
4802    if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4803        return;
4804    }
4805    let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4806        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4807        "operation": operation, "outcome": outcome, "detail": detail,
4808        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4809        "reclaim_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4810        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4811    if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4812        receipt.extend(extra);
4813    }
4814    if let Err(error) = crate::fold_evidence::atomic_write(
4815        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4816        &serde_json::to_vec(&receipt).expect("service receipt"),
4817    ) {
4818        tracing::warn!("retention service receipt failed: {error:#}");
4819    }
4820}
4821
4822/// What a retention pass reported, for the service receipt: the same report
4823/// `retention.json` holds, reduced to what says whether the pass ran. On a
4824/// platform without process containment this carries the refusal.
4825fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4826    let clip = |text: &String| text.chars().take(300).collect::<String>();
4827    serde_json::json!({"retention": {
4828        "checked_at": report.checked_at,
4829        "freed_bytes": report.freed_bytes,
4830        "retired": report.retired,
4831        "retained": report.retained.len(),
4832        "failure_count": report.failures.len(),
4833        "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4834    }})
4835}
4836
4837/// Why the finished-run folding turn exists, and what keeps it safe.
4838///
4839/// `housekeeping` (which folds finished runs through `clean::fold_due`) has
4840/// only ever been admitted on a fully idle machine: it was written as "the
4841/// janitor, called when a task just ended" (e2c10827, "the disk is quiet ...
4842/// folding worktrees and pruning a cache mid-build would race the very compile
4843/// the prune exists to keep"), and the idle gate survived when the loop was
4844/// split into services. Nothing in that reasoning is about folding: it is
4845/// about the shared cache prune, `fold_orphaned_worktrees` (a run that has no
4846/// `run.json` yet is indistinguishable from an orphan) and `worktree_prune`,
4847/// which stay idle-only. Folding a *finished* run is already done beside live
4848/// runs of the same repository by `Runner::fold_losers`, `magi fold` and the
4849/// phone's fold route, because `graph::fold_run_when` takes the run's owner lock
4850/// and execution lease, a per-worktree output lease and the repository
4851/// coordination lease itself, acts on the run record it reloads once it holds
4852/// them (a handover in between cannot be undone), and `clean::eligibility`
4853/// refuses anything a live claim holds. So a queue that is never empty must not
4854/// mean runs are never folded (issue 1275): this turn is admitted exactly where
4855/// housekeeping is not, in bounded passes (`clean::BUSY_FOLD_BOUNDS`).
4856const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4857
4858/// Idle housekeeping: no worker busy and nothing runnable.
4859fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4860    !busy && !runnable
4861}
4862
4863/// Exactly the machines [`housekeeping_eligible`] never reaches (see
4864/// [`FOLD_TURN_INTERVAL_SECS`] for why folding may run beside live work),
4865/// and only with a startup configuration that has `auto_fold` on (like the
4866/// cache and fetch services, an unreadable one means no service).
4867fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4868    !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4869}
4870
4871async fn start_service(
4872    home: &Path,
4873    opts: &Opts,
4874    queue: &Queue,
4875    worktrees_root: &Path,
4876    operation: &str,
4877    cfg: Option<&Config>,
4878    busy: bool,
4879) -> Result<()> {
4880    // Fetch policy is live configuration, unlike question recovery capacity.
4881    // Reload before both cadence and eligibility, including disabled -> enabled.
4882    let fetch_cfg = if operation == "fetch" {
4883        match prepare(&opts.repo, opts) {
4884            Ok(cfg) => Some(cfg),
4885            Err(error) => {
4886                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4887                return Ok(());
4888            }
4889        }
4890    } else {
4891        None
4892    };
4893    let cfg = fetch_cfg.as_ref().or(cfg);
4894    let ticks = home.join("service-ticks");
4895    std::fs::create_dir_all(&ticks)?;
4896    let receipt = ticks.join(format!("daemon-{operation}"));
4897    let last = std::fs::read(&receipt)
4898        .ok()
4899        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4900    let interval = match operation {
4901        "disk-pressure" => 30,
4902        "fold" => FOLD_TURN_INTERVAL_SECS,
4903        "chat-goals" | "decisions" => 60,
4904        "cache" => CACHE_CHECK_INTERVAL_SECS,
4905        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4906        _ => opts.poll.as_secs().max(1),
4907    };
4908    let now = Timestamp::now();
4909    if !cache_check_due(last, now, interval) {
4910        retention_service_receipt(
4911            home,
4912            operation,
4913            "dispatch",
4914            "skipped",
4915            "cadence not due",
4916            cfg,
4917        );
4918        return Ok(());
4919    }
4920    let key = format!("service:daemon-{operation}");
4921    let active = crate::worker::active(home)?;
4922    if active.iter().any(|job| job.key == key) {
4923        retention_service_receipt(
4924            home,
4925            operation,
4926            "dispatch",
4927            "skipped",
4928            "service worker already active",
4929            cfg,
4930        );
4931        return Ok(());
4932    }
4933    // Both fold the same runs; the run's owner lock already makes a collision
4934    // harmless, but one of them at a time keeps the receipts unambiguous.
4935    let sibling = match operation {
4936        "housekeeping" => Some("service:daemon-fold"),
4937        "fold" => Some("service:daemon-housekeeping"),
4938        _ => None,
4939    };
4940    if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4941        retention_service_receipt(
4942            home,
4943            operation,
4944            "dispatch",
4945            "skipped",
4946            "another finished-run folding service is active",
4947            cfg,
4948        );
4949        return Ok(());
4950    }
4951    let eligible = match operation {
4952        "conductor" => {
4953            let (queued, stalled, finished) = conductor_work(queue, home);
4954            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4955                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4956        }
4957        "maintenance" => {
4958            queue.list().iter().any(|task| {
4959                crate::triage::disk_wait_eligible(task)
4960                    && task
4961                        .disk_checked_at
4962                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4963            }) || Questions::at(home.join("questions"))
4964                .list_for_effects()
4965                .iter()
4966                .any(|q| {
4967                    q.chosen_action().is_some_and(|action| action.maintenance())
4968                        && !home
4969                            .join("choice-actions")
4970                            .join(format!("{}.json", q.id))
4971                            .exists()
4972                })
4973        }
4974        "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4975        "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4976        "cache" => {
4977            !busy
4978                && !runnable(queue).is_empty()
4979                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4980        }
4981        "disk-pressure" => busy,
4982        "fetch" => {
4983            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4984        }
4985        "decisions" => home.join("notifications/task-inquiries").is_dir(),
4986        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4987            .list()
4988            .iter()
4989            .any(|talk| {
4990                talk.status.open()
4991                    && talk.pending.is_empty()
4992                    && talk.pending_attachments.is_empty()
4993                    && talk.goals.iter().any(|goal| goal.active())
4994            }),
4995        _ => false,
4996    };
4997    if !eligible {
4998        retention_service_receipt(
4999            home,
5000            operation,
5001            "dispatch",
5002            "skipped",
5003            match operation {
5004                "housekeeping" => "active work or runnable task queue",
5005                "fold" if cfg.is_none() => "startup configuration unavailable",
5006                "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
5007                "fold" => "idle machine; housekeeping owns finished-run folding",
5008                _ => "no active work; idle housekeeping owns scan",
5009            },
5010            cfg,
5011        );
5012        return Ok(());
5013    }
5014    retention_service_receipt(
5015        home,
5016        operation,
5017        "dispatch",
5018        "launching",
5019        "eligible and cadence due",
5020        cfg,
5021    );
5022    let request = ServiceWorker {
5023        opts: opts.absolute()?,
5024        queue: std::path::absolute(queue.root())?,
5025        worktrees_root: std::path::absolute(worktrees_root)?,
5026        operation: operation.to_owned(),
5027    };
5028    if let Err(error) = launch_service(home, &key, request).await {
5029        retention_service_receipt(
5030            home,
5031            operation,
5032            "dispatch",
5033            "error",
5034            &format!("worker launch: {error:#}"),
5035            cfg,
5036        );
5037        tracing::warn!(operation, "could not launch daemon service: {error:#}");
5038    }
5039    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
5040    Ok(())
5041}
5042
5043/// Hand `request` to a detached `daemon-service` worker reservation.
5044///
5045/// Unit tests have no `magi` executable to pin and exec as a worker, so they
5046/// may run the very same [`run_service_worker`] inline instead (and nothing
5047/// else differs: admission, cadence and receipts above are the production path).
5048async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
5049    #[cfg(test)]
5050    if INLINE_SERVICES.with(std::cell::Cell::get) {
5051        return run_service_worker(home, serde_json::to_value(request)?).await;
5052    }
5053    crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
5054    Ok(())
5055}
5056
5057#[cfg(test)]
5058thread_local! {
5059    static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5060}
5061
5062/// One bounded pass of finished-run folding (`clean::fold_turn`) with its
5063/// per-outcome counts and cursor in the service receipt. It reserves no agent
5064/// seat and takes only the locks `graph::fold_run` takes for one run at a time.
5065async fn fold_service_turn(home: &Path, opts: &Opts) {
5066    let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
5067        retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
5068    };
5069    let cfg = match prepare(&opts.repo, opts) {
5070        Ok(cfg) => cfg,
5071        Err(error) => {
5072            worker(
5073                "error",
5074                &format!("configuration: {error:#}"),
5075                None,
5076                serde_json::Value::Null,
5077            );
5078            return;
5079        }
5080    };
5081    if !cfg.disk.auto_fold {
5082        worker(
5083            "skipped",
5084            "auto_fold disabled",
5085            Some(&cfg),
5086            serde_json::Value::Null,
5087        );
5088        return;
5089    }
5090    worker(
5091        "running",
5092        "finished-run fold turn",
5093        Some(&cfg),
5094        serde_json::Value::Null,
5095    );
5096    let turn = clean::fold_turn(
5097        &home.join("runs"),
5098        home,
5099        &cfg.disk,
5100        Timestamp::now(),
5101        clean::BUSY_FOLD_BOUNDS,
5102    )
5103    .await;
5104    if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5105        tracing::info!(
5106            folded = turn.folded,
5107            failed = turn.failed,
5108            unreadable = turn.unreadable,
5109            "housekeep: finished-run fold turn"
5110        );
5111    }
5112    worker(
5113        "completed",
5114        "finished-run fold turn",
5115        Some(&cfg),
5116        serde_json::json!({ "fold": turn }),
5117    );
5118}
5119
5120/// Finite maintenance jobs survive scheduler replacement without duplicating
5121/// agent calls or cancelling an operation between its effect and receipt.
5122pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5123    let request: ServiceWorker = serde_json::from_value(payload)?;
5124    let opts = &request.opts;
5125    let queue = Queue::at(request.queue);
5126    let questions = Questions::at(home.join("questions"));
5127    match request.operation.as_str() {
5128        "decisions" => crate::chat_control::retire_obsolete_decisions(&queue, home).await?,
5129        "chat-goals" => {
5130            let talks = crate::talk::Talks::at(home.join("talks"));
5131            crate::chat_goal_runtime::sweep(&talks, false).await;
5132        }
5133        "maintenance" => {
5134            apply_maintenance_choices(&queue, &questions, home).await;
5135            triage::monitor_disk_waits(
5136                &queue,
5137                &questions,
5138                opts.config.as_deref(),
5139                Timestamp::now(),
5140            );
5141        }
5142        "conductor" => {
5143            let path = home.join("conductor-state.json");
5144            let mut conductor = load_conductor(home)?;
5145            let (queued, stalled, finished) = conductor_work(&queue, home);
5146            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5147                && conductor.worth_a_look(&queue, &stalled, &finished)
5148            {
5149                let cfg = prepare(&opts.repo, opts)?;
5150                conductor
5151                    .maybe_run(
5152                        &cfg,
5153                        &opts.repo,
5154                        &queue,
5155                        &questions,
5156                        home,
5157                        &queued,
5158                        &stalled,
5159                        &finished,
5160                        opts.max_attempts,
5161                    )
5162                    .await;
5163                let temporary = path.with_extension("json.tmp");
5164                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5165                std::fs::rename(temporary, path)?;
5166            }
5167        }
5168        "fetch" => {
5169            let cfg = prepare(&opts.repo, opts)?;
5170            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5171                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5172                tracing::debug!("fetch origins: {outcome:?}");
5173            }
5174        }
5175        "cache" => {
5176            if task_jobs(home)?.is_empty() {
5177                let mut checked = None;
5178                maybe_prune_cache_between_runs(
5179                    &opts.repo,
5180                    opts,
5181                    home,
5182                    &Stop::new(),
5183                    &mut checked,
5184                    Timestamp::now(),
5185                )
5186                .await;
5187            }
5188        }
5189        "disk-pressure" => {
5190            if let Ok(cfg) = prepare(&opts.repo, opts) {
5191                retention_service_receipt(
5192                    home,
5193                    "disk-pressure",
5194                    "worker",
5195                    "running",
5196                    "retention sweep",
5197                    Some(&cfg),
5198                );
5199                let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5200                retention_service_receipt_with(
5201                    home,
5202                    "disk-pressure",
5203                    "worker",
5204                    "retention swept",
5205                    "retention sweep finished; cache cleanup follows",
5206                    Some(&cfg),
5207                    retention_summary(&report),
5208                );
5209                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5210                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5211                }
5212                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5213                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5214                }
5215                for current in current_work(home, Timestamp::now()) {
5216                    if let Ok(state) = RunState::load_under(&current.run, home)
5217                        && let Some(reason) = disk_gate(&state.repo, &state.config)
5218                    {
5219                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5220                            job.key.strip_prefix("task:") == Some(current.task.as_str())
5221                        }) {
5222                            request_task_park(
5223                                home,
5224                                &job,
5225                                crate::run::ParkCause::Interrupt {
5226                                    reason: reason.clone(),
5227                                },
5228                            )?;
5229                        }
5230                        notices::raise_in(
5231                            home,
5232                            Notice::warn(
5233                                "disk:pressure",
5234                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5235                            ),
5236                        );
5237                    }
5238                }
5239            } else {
5240                retention_service_receipt(
5241                    home,
5242                    "disk-pressure",
5243                    "worker",
5244                    "error",
5245                    "configuration could not be loaded",
5246                    None,
5247                );
5248            }
5249        }
5250        "fold" => fold_service_turn(home, opts).await,
5251        "housekeeping" => {
5252            if task_jobs(home)?.is_empty() {
5253                match prepare(&opts.repo, opts) {
5254                    Ok(cfg) => {
5255                        retention_service_receipt(
5256                            home,
5257                            "housekeeping",
5258                            "worker",
5259                            "running",
5260                            "retention sweep",
5261                            Some(&cfg),
5262                        );
5263                        let report =
5264                            crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5265                        retention_service_receipt_with(
5266                            home,
5267                            "housekeeping",
5268                            "worker",
5269                            "retention swept",
5270                            "retention sweep finished; janitor follows",
5271                            Some(&cfg),
5272                            retention_summary(&report),
5273                        );
5274                    }
5275                    Err(error) => retention_service_receipt(
5276                        home,
5277                        "housekeeping",
5278                        "worker",
5279                        "error",
5280                        &format!("configuration: {error:#}"),
5281                        None,
5282                    ),
5283                }
5284                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5285                resweep_superseded_attempts(&queue, home);
5286                triage_held(&queue, home, opts).await;
5287            } else {
5288                retention_service_receipt(
5289                    home,
5290                    "housekeeping",
5291                    "worker",
5292                    "skipped",
5293                    "task worker became active",
5294                    None,
5295                );
5296            }
5297        }
5298        operation => bail!("unknown daemon service {operation}"),
5299    }
5300    Ok(())
5301}
5302
5303/// Only a different request under the same key is a dispatch handoff race.
5304/// Our own unacknowledged reservation is a startup failure, not competing work:
5305/// stop dispatch without fencing it, so an already detached child may still run.
5306fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5307    let key = format!("task:{}", request.task);
5308    let payload = serde_json::to_value(request)?;
5309    if crate::worker::active(home)?
5310        .iter()
5311        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5312    {
5313        tracing::warn!(
5314            "task {} acquired a competing worker reservation: {error:#}",
5315            crate::run::short_of(&request.task)
5316        );
5317        return Ok(());
5318    }
5319    tracing::error!("task worker startup stopped dispatch: {error:#}");
5320    notices::raise_in(
5321        home,
5322        Notice::error(
5323            "loop:worker-startup",
5324            // Startup diagnostics may contain private child-process details;
5325            // keep them in the local error/log rather than the chat or notifier.
5326            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),
5327        ).link(Link::Task { id: request.task.clone() }),
5328    );
5329    Err(error).with_context(|| {
5330        format!(
5331            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5332            crate::run::short_of(&request.task)
5333        )
5334    })
5335}
5336
5337fn once_queue_service(job: &crate::worker::Job) -> bool {
5338    job.kind == "daemon-service"
5339        && matches!(
5340            job.key.as_str(),
5341            "service:daemon-housekeeping"
5342                | "service:daemon-conductor"
5343                | "service:daemon-maintenance"
5344                | "service:daemon-decisions"
5345        )
5346}
5347
5348async fn poll(
5349    opts: &Opts,
5350    queue: &Queue,
5351    status: &Arc<Mutex<Status>>,
5352    home: &Path,
5353    worktrees_root: &Path,
5354    stop: &Stop,
5355    limits: DispatchLimits,
5356) -> Result<()> {
5357    let mut attempted = Vec::new();
5358    let mut settling_once_services = false;
5359    let interrupt_path = home.join("scheduler-interrupt.json");
5360    let mut interrupt = match std::fs::read(&interrupt_path) {
5361        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5362        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5363        Err(error) => return Err(error.into()),
5364    };
5365    let mut previous = std::collections::BTreeSet::<String>::new();
5366    let mut previous_skips = DispatchSkips::new();
5367    while !stop.stopped() {
5368        let active = crate::worker::active(home)?;
5369        let settling_queue_service = opts.once && active.iter().any(once_queue_service);
5370        let jobs: Vec<_> = active
5371            .into_iter()
5372            .filter(|job| job.kind == "task")
5373            .collect();
5374        let requests: Vec<_> = jobs
5375            .iter()
5376            .map(|job| {
5377                serde_json::from_value::<TaskWorker>(job.payload.clone())
5378                    .with_context(|| format!("read live task worker {}", job.id))
5379            })
5380            .collect::<Result<_>>()?;
5381        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5382        let owned: std::collections::BTreeSet<_> = requests
5383            .iter()
5384            .filter(|r| !r.standalone)
5385            .map(|r| r.task.clone())
5386            .collect();
5387        let current: Vec<_> = requests
5388            .iter()
5389            .zip(&jobs)
5390            .filter(|(request, _)| !request.standalone)
5391            .map(|(request, job)| Current {
5392                worker: Some(job.id.clone()),
5393                task: request.task.clone(),
5394                run: queue
5395                    .get(&request.task)
5396                    .ok()
5397                    .and_then(|task| task.execution_runs().last().cloned())
5398                    .unwrap_or_default(),
5399            })
5400            .collect();
5401        {
5402            let mut snapshot = lock(status);
5403            snapshot.polls += 1;
5404            snapshot.completed += previous.difference(&owned).count();
5405            snapshot.current = current;
5406            snapshot.idle = owned.is_empty();
5407            snapshot.dispatch_wait = None;
5408        }
5409        previous = owned.clone();
5410        stop.busy.store(owned.len(), Ordering::SeqCst);
5411
5412        // Slots are reconstructed from durable reservations and OS-held worker
5413        // leases, not this scheduler's lifetime or mutable task urgency.
5414        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5415        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5416        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5417        let mut permits = Vec::new();
5418        sweep_stale_claims(queue, STALE_CLAIM);
5419        reclaim_orphaned_running(queue, opts.max_attempts, &live);
5420        reclaim_abandoned_runs(home, Timestamp::now());
5421        let questions = Questions::at(home.join("questions"));
5422
5423        // Deterministic: no model, run before the conductor sees anything so
5424        // its input reflects the queue's current, already-resolved state.
5425        crate::task_chat::sweep(
5426            queue,
5427            &crate::talk::Talks::at(home.join("talks")),
5428            &questions,
5429            home,
5430        );
5431        if let Err(error) = crate::task_inquiry::Outbox::at(home)
5432            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5433        {
5434            tracing::warn!("task inquiry delivery remains pending: {error:#}");
5435        }
5436        repair_choice_offers(&questions);
5437        resolve_blockers(queue, &questions);
5438        apply_task_choice_actions(queue, &questions, home);
5439        triage::apply_answers(queue, &questions);
5440        reconcile_task_questions(queue, &questions);
5441        let talks = crate::talk::Talks::at(home.join("talks"));
5442        crate::chat_notify::sweep(queue, &talks, home, opts.config.as_deref());
5443        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5444        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5445            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5446        }
5447        let mut turns = tokio::task::JoinSet::new();
5448        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5449        // start_turns dispatches detached turns; no paid work lives in this set.
5450        while turns.join_next().await.is_some() {}
5451
5452        crate::consult::start_services(
5453            home,
5454            &opts.repo,
5455            limits.recovery_cfg.as_ref(),
5456            opts.config.as_deref(),
5457        )
5458        .await?;
5459        for operation in [
5460            "conductor",
5461            "maintenance",
5462            "housekeeping",
5463            "disk-pressure",
5464            "fold",
5465            "cache",
5466            "fetch",
5467            "chat-goals",
5468            "decisions",
5469        ] {
5470            // Once an idle --once drain starts settling services, subsequent
5471            // scans only consume their effects. An expired cadence receipt
5472            // must not start another service and keep the drain alive.
5473            if settling_once_services {
5474                break;
5475            }
5476            if operation == "chat-goals" && stop.parking() {
5477                continue;
5478            }
5479            start_service(
5480                home,
5481                opts,
5482                queue,
5483                worktrees_root,
5484                operation,
5485                limits.recovery_cfg.as_ref(),
5486                !live.is_empty(),
5487            )
5488            .await?;
5489        }
5490        let latest = crate::worker::active(home)?;
5491        if latest.iter().any(|job| job.key == "service:daemon-cache")
5492            || latest
5493                .iter()
5494                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5495        {
5496            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5497            continue;
5498        }
5499        let candidates: Vec<Task> = runnable(queue)
5500            .into_iter()
5501            .filter(|task| !live.contains(&task.id))
5502            .filter(|task| !opts.once || !attempted.contains(&task.id))
5503            .collect();
5504        let in_flight: Vec<_> = owned.iter().cloned().collect();
5505        let prior_interrupt = std::mem::discriminant(&interrupt);
5506        interrupt = advance_interrupt_tick(
5507            limits.pause_for_interrupts,
5508            interrupt,
5509            &in_flight,
5510            &candidates,
5511        );
5512        // Same-variant transitions preserve their identities. Only an actual
5513        // transition needs a durable write, atomically before sending controls.
5514        if prior_interrupt != std::mem::discriminant(&interrupt) {
5515            let temporary = interrupt_path.with_extension("json.tmp");
5516            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5517            std::fs::rename(temporary, &interrupt_path)?;
5518        }
5519        if let Interrupt::Parking {
5520            parked,
5521            interrupt_task,
5522        } = &interrupt
5523        {
5524            for job in jobs.iter().filter(|job| {
5525                parked
5526                    .iter()
5527                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5528            }) {
5529                if crate::worker::control(home, &job.key)?.is_none() {
5530                    request_task_park(
5531                        home,
5532                        job,
5533                        crate::run::ParkCause::Interrupt {
5534                            reason: format!(
5535                                "task {} asked to run first",
5536                                crate::run::short_of(interrupt_task)
5537                            ),
5538                        },
5539                    )?;
5540                }
5541            }
5542        }
5543        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5544        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5545        let mut skips = interrupt_skips(&candidate_ids, &candidates);
5546        // Stable-partition immediate candidates ahead of non-immediate ones
5547        // for this poll scan only; shared `dispatch_order` stays unchanged so
5548        // upgrade-resume and ordinary priority ordering are preserved.
5549        let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5550            candidates.into_iter().partition(|task| task.immediate);
5551        immediate_candidates.extend(other_candidates);
5552        let candidates = immediate_candidates;
5553        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5554        let mut known_jobs: std::collections::BTreeSet<String> =
5555            jobs.iter().map(|job| job.id.clone()).collect();
5556        let mut started = false;
5557        let mut resync = false;
5558        for candidate in candidates {
5559            if stop.stopped() {
5560                break;
5561            }
5562            let DispatchClaim {
5563                task,
5564                claim,
5565                lane,
5566                permit,
5567            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5568                Ok(claim) => claim,
5569                Err(reason) => {
5570                    skips.insert((candidate.id, reason));
5571                    continue;
5572                }
5573            };
5574            if crate::worker::active(home)?
5575                .iter()
5576                .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5577            {
5578                drop(claim);
5579                resync = true;
5580                break;
5581            }
5582            let request = TaskWorker {
5583                opts: opts.absolute()?,
5584                queue: std::path::absolute(queue.root())?,
5585                task: task.id.clone(),
5586                lane,
5587                standalone: false,
5588            };
5589            // Keep the claim until spawn acknowledges the worker's durable
5590            // reservation. The worker then claims and re-reads before attempt.
5591            let job = match crate::worker::spawn(
5592                home,
5593                "task",
5594                &format!("task:{}", task.id),
5595                serde_json::to_value(&request)?,
5596            )
5597            .await
5598            {
5599                Ok(job) => job,
5600                Err(error) => {
5601                    task_worker_spawn_error(home, &request, error)?;
5602                    drop(claim);
5603                    resync = true;
5604                    break;
5605                }
5606            };
5607            known_jobs.insert(job.id);
5608            drop(claim);
5609            permits.extend(permit);
5610            attempted.push(task.id);
5611            started = true;
5612            // Interrupt transitions depend on the exact in-flight set (in
5613            // particular the transition from zero to one worker). Re-scan
5614            // before admitting another task, as for ordinary dispatch.
5615            if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5616                break;
5617            }
5618        }
5619        if !resync && !stop.stopped() {
5620            let per_task_skips: std::collections::BTreeMap<String, String> = skips
5621                .iter()
5622                .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5623                .collect();
5624            {
5625                let mut snapshot = lock(status);
5626                snapshot.dispatch_skips = per_task_skips;
5627                if !started {
5628                    snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5629                }
5630            }
5631            if changed_dispatch_skips(&mut previous_skips, skips) {
5632                if previous_skips.is_empty() {
5633                    tracing::info!("dispatch skips cleared");
5634                }
5635                for (task, reason) in &previous_skips {
5636                    tracing::info!(
5637                        task,
5638                        reason = reason.key(),
5639                        "task {} skipped: {}",
5640                        crate::run::short_of(task),
5641                        reason.describe()
5642                    );
5643                }
5644            }
5645        }
5646        if started || resync {
5647            continue;
5648        }
5649        if owned.is_empty() && opts.once {
5650            let first_settlement = !settling_once_services;
5651            settling_once_services = true;
5652            // A service may release its claim after the dispatch scan but
5653            // before the final liveness check. Scan again without launching
5654            // new periodic services even if it has already finished.
5655            if crate::worker::active(home)?.iter().any(once_queue_service) {
5656                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5657                continue;
5658            }
5659            if first_settlement || settling_queue_service {
5660                continue;
5661            }
5662            break;
5663        }
5664        stop.idle(if live.is_empty() {
5665            opts.poll
5666        } else {
5667            RECHECK_WHILE_BUSY.min(opts.poll)
5668        })
5669        .await;
5670    }
5671    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
5672    // every queue claim and Runner driver lease through outcome settlement.
5673    stop.busy.store(0, Ordering::SeqCst);
5674    {
5675        let mut snapshot = lock(status);
5676        snapshot.dispatch_wait = None;
5677        snapshot.dispatch_skips.clear();
5678    }
5679    Ok(())
5680}
5681
5682/// A maintenance pass may briefly own the same record while a worker starts.
5683/// Wait without blocking the executor or charging an agent attempt, then read
5684/// ownership again under the acquired lock. Other I/O failures still fail closed.
5685async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5686    let busy = |error: &anyhow::Error| {
5687        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5688            error.kind() == std::io::ErrorKind::WouldBlock
5689                || cfg!(windows) && error.raw_os_error() == Some(33)
5690        })
5691    };
5692    match crate::pr_head::owner_lock(home, id) {
5693        Ok(lock) => return Ok(lock),
5694        Err(error) if busy(&error) => {}
5695        Err(error) => return Err(error),
5696    }
5697    let wait = RunState::load_under(id, home)?
5698        .config
5699        .graph
5700        .timeout_resource_wait;
5701    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5702}
5703
5704fn run_directory_present(dir: &Path) -> Result<bool> {
5705    match std::fs::symlink_metadata(dir) {
5706        Ok(_) => Ok(true),
5707        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
5708        Err(error) => {
5709            Err(error).with_context(|| format!("inspect run directory {}", dir.display()))
5710        }
5711    }
5712}
5713
5714/// Historical successors do not revoke a still-resumable public owner. Scan
5715/// under the same lock as publication/driver claims, and fail closed on unknown
5716/// history before spending another attempt.
5717pub(crate) async fn public_resume_owner(
5718    home: &Path,
5719    runs: &[String],
5720    repo: &Path,
5721) -> Result<Option<RunState>> {
5722    let mut owner = None;
5723    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5724        let dir = home.join("runs").join(id);
5725        if !run_directory_present(&dir)? {
5726            tracing::info!(run = id, path = %dir.display(), "skipping missing run directory in public ownership scan");
5727            continue;
5728        }
5729        let _lock = resume_owner_lock(home, id).await?;
5730        let state = RunState::load_under(id, home)?;
5731        if state.released()
5732            || state.retired_to.is_some()
5733            || state.pr_taken_over_by.is_some()
5734            || !crate::handover::landing_checkpoint(&state)
5735        {
5736            continue;
5737        }
5738        anyhow::ensure!(
5739            crate::git::toplevel(&state.repo).await?.canonicalize()?
5740                == crate::git::toplevel(repo).await?.canonicalize()?,
5741            "public owner repository differs; inspect run lineage"
5742        );
5743        anyhow::ensure!(
5744            owner.is_none(),
5745            "multiple retained public owners; inspect run lineage"
5746        );
5747        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5748            anyhow::bail!(reason.diagnostic(&state));
5749        }
5750        let claimed = is_working_on_other(home, id, Timestamp::now())?;
5751        anyhow::ensure!(
5752            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5753            "public owner's driver is live or unknown; wait before retrying"
5754        );
5755        owner = Some(state);
5756    }
5757    Ok(owner)
5758}
5759
5760/// Run one claimed task to a terminal status and record the outcome.
5761///
5762/// Every transition is flushed to the queue as it happens, so the state on disk
5763/// is what actually occurred rather than what this process still intends to
5764/// write.
5765async fn attempt(
5766    opts: &Opts,
5767    queue: &Queue,
5768    status: &Arc<Mutex<Status>>,
5769    stop: &Stop,
5770    interrupt_pause: crate::graph::Pause,
5771    task: &mut Task,
5772) -> Vec<QuotaLoss> {
5773    if let Some(request) = task.sync_only.clone() {
5774        Box::pin(attempt_sync_only(
5775            queue,
5776            status,
5777            stop,
5778            interrupt_pause,
5779            task,
5780            request,
5781        ))
5782        .await;
5783        return Vec::new();
5784    }
5785    let repo = repo_for(task, &opts.repo);
5786    tracing::info!(
5787        "task {} — {} (repo {})",
5788        task.short(),
5789        task.title,
5790        repo.display()
5791    );
5792
5793    let home = crate::run::home();
5794    let public_owner = match public_resume_owner(&home, &task.runs, &repo).await {
5795        Ok(owner) => owner,
5796        Err(e) => {
5797            task.hold_machine(Some(format!(
5798                "Cannot verify existing public owner: {e:#}; no attempt started."
5799            )));
5800            record(queue, task);
5801            return Vec::new();
5802        }
5803    };
5804    let resume_runs = public_owner
5805        .as_ref()
5806        .map(|s| vec![s.id.clone()])
5807        .unwrap_or_else(|| task.execution_runs().to_vec());
5808
5809    // A stop spends no agent resources and uses the saved landing owner.
5810    // Current roster edits, missing attachments or a failed config fetch must
5811    // never turn it into a new implementation, or prevent a PR from closing.
5812    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5813        && previous
5814            .merge_decision
5815            .as_ref()
5816            .is_some_and(|decision| !decision.closed)
5817        && previous.status != RunStatus::Landing
5818        && !crate::merge_decision::resumable_hold(&previous)
5819    {
5820        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)));
5821        record(queue, task);
5822        return Vec::new();
5823    }
5824    let stop_owner = resume_runs
5825        .last()
5826        .and_then(|id| RunState::load(id).ok())
5827        .filter(|state| {
5828            crate::merge_decision::resumable_hold(state)
5829                || state.status == RunStatus::Landing
5830                    && state.land_approval.as_ref().is_some_and(|binding| {
5831                        Questions::open()
5832                            .get_for_effects(&binding.question)
5833                            .is_ok_and(|q| {
5834                                q.run == state.id
5835                                    && q.resolution()
5836                                        .as_deref()
5837                                        .is_some_and(crate::merge_decision::stops)
5838                            })
5839                    })
5840        });
5841    if let Some(owner) = stop_owner {
5842        let mut runner = match Runner::resume(&owner.id) {
5843            Ok(runner) => runner,
5844            Err(e) => {
5845                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5846                record(queue, task);
5847                return Vec::new();
5848            }
5849        };
5850        runner.on_pause(stop.pause());
5851        runner.watch_interrupt(interrupt_pause);
5852        let quota_before = runner.state.quota.clone();
5853        let before_start = task.clone();
5854        task.start(owner.id.clone());
5855        if let Err(error) = queue.put(task) {
5856            *task = before_start;
5857            let error = runner.fail_startup("task-start", error);
5858            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5859                task.record_startup_failure(failure.clone());
5860            }
5861            task.hold_manual(Some(format!(
5862                "Could not persist task start; no agents dispatched: {error:#}"
5863            )));
5864            record(queue, task);
5865            return Vec::new();
5866        }
5867        lock(status).current.push(Current {
5868            worker: None,
5869            task: task.id.clone(),
5870            run: owner.id,
5871        });
5872        runner.state.carry_dispatched_resumes(task);
5873        runner.state.next_pass_task_entry = true;
5874        let result = runner.execute().await;
5875        return finish_attempt(
5876            opts.max_attempts,
5877            queue,
5878            task,
5879            &runner.state,
5880            &quota_before,
5881            result,
5882        );
5883    }
5884
5885    if let Some(owner) = &public_owner
5886        && (task.fresh_start || !may_resume_run(owner, task))
5887    {
5888        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. For a closed unmerged PR with a cancelled approval and selected replacement, use magi task recover-pr {} --retire-closed-run {} --cancelled-decision <inquiry-id>. No attempt started.", owner.id, task.id, owner.id)));
5889        record(queue, task);
5890        return Vec::new();
5891    }
5892
5893    if let Some(state) = task
5894        .execution_runs()
5895        .last()
5896        .and_then(|id| RunState::load(id).ok())
5897        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5898    {
5899        task.hold_machine(Some(reason));
5900        record(queue, task);
5901        return Vec::new();
5902    }
5903
5904    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5905        && !task.fresh_start
5906        && task.pr_recovery.is_none()
5907    {
5908        // A pinned infrastructure resume continues the saved reservation;
5909        // it does not authorize another base-sync interval.
5910        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5911            && task.review_branch.is_none()
5912            && task.assignment_accepts(&held)
5913            && compatible_run_instruction(&held, task)
5914            && task
5915                .resume_override
5916                .as_ref()
5917                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5918        // Exhaustion authorization still takes the owner lock and execution
5919        // lease and rechecks liveness, retained HEAD and ownership.
5920        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5921        {
5922            true
5923        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5924            let home = queue.root().parent().expect("queue has a home");
5925            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5926                Ok(()) => true,
5927                Err(error) => {
5928                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5929                    false
5930                }
5931            }
5932        } else {
5933            false
5934        };
5935        if !authorized {
5936            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())));
5937            // Retain the existing stop identity when an old release reached the queue.
5938            task.base_sync_notice(&held);
5939            task.resume_override = None;
5940            record(queue, task);
5941            return Vec::new();
5942        }
5943    }
5944    if !task.fresh_start && task.pr_recovery.is_none() {
5945        let home = queue.root().parent().expect("queue has a home");
5946        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5947            crate::land_sync_recovery::dispatch_check(queue, home, task).await
5948        {
5949            task.hold_machine(Some(reason));
5950            task.land_sync_notice(state.as_ref());
5951            task.resume_override = None;
5952            record(queue, task);
5953            return Vec::new();
5954        }
5955    }
5956    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5957        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5958            hold.apply(task);
5959            record(queue, task);
5960            return Vec::new();
5961        }
5962        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5963            run,
5964            stop_id,
5965            generation,
5966            approval_at,
5967        }) => Some((run, stop_id, generation, approval_at)),
5968        None => None,
5969    };
5970    let unfinished = (!task.fresh_start)
5971        .then(|| unfinished_run(&resume_runs, task.short()))
5972        .flatten()
5973        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5974    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5975    if task.repair_grants.last().is_some_and(|receipt| {
5976        task.execution_runs().last() == Some(&receipt.request.run)
5977            && task.operator_decided_at == receipt.decision
5978            && previous
5979                .as_ref()
5980                .is_none_or(|run| run.id != receipt.request.run)
5981    }) {
5982        task.hold_unrequested_retry(Some(
5983            "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(),
5984        ));
5985        record(queue, task);
5986        return Vec::new();
5987    }
5988    if let Some(id) = &task.disk_resume_run
5989        && unfinished.as_ref() != Some(id)
5990    {
5991        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()));
5992        record(queue, task);
5993        return Vec::new();
5994    }
5995
5996    if !task.fresh_start
5997        && task.pr_recovery.is_none()
5998        && task.review_branch.is_none()
5999        && task.resume_override.is_none()
6000        && previous
6001            .as_ref()
6002            .is_some_and(|run| run.retired_to.is_some())
6003        && unfinished.is_none()
6004    {
6005        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()));
6006        record(queue, task);
6007        return Vec::new();
6008    }
6009
6010    let saved_recovery = previous.as_ref().filter(|run| {
6011        task.replacement.is_none()
6012            && task.pr_recovery.as_ref().is_some_and(|selected| {
6013                selected
6014                    .check_retained_task(task, &crate::run::home())
6015                    .is_ok()
6016                    && selected_starter(selected, Some(run), unfinished.as_deref())
6017                        == Starter::Resume(run.id.clone())
6018            })
6019    });
6020
6021    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
6022    // failure here is the network's or the operator's, not the task's: hold
6023    // without spending an attempt, never fall back to a possibly stale copy.
6024    let explicit = match &task.overrides {
6025        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6026        Some(_) => opts.config.as_deref(),
6027        None => opts.config.as_deref(),
6028    };
6029    let (mut config, layers) = if let Some(run) = saved_recovery {
6030        // A matching resume owns its resolved configuration and evidence;
6031        // current layers and inherited overrides only configure new work.
6032        let mut saved = run.clone();
6033        if let Err(e) = saved.configure_recovery_resume() {
6034            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
6035            record(queue, task);
6036            return Vec::new();
6037        }
6038        (saved.config, Vec::new())
6039    } else {
6040        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
6041            Ok(loaded) => loaded,
6042            Err(e) => {
6043                let reason = format!("[config] {e:#}");
6044                record_config_failure(task, &e);
6045                task.last_error = Some(reason.clone());
6046                task.hold_machine(Some(reason));
6047                record(queue, task);
6048                return Vec::new();
6049            }
6050        };
6051        if let Err(e) = apply_options(&mut config, opts, task) {
6052            task.hold_manual(Some(format!(
6053                "[config] {e:#}; correct the merge override before releasing the task"
6054            )));
6055            record(queue, task);
6056            return Vec::new();
6057        }
6058        if let Some(selected) = &task.pr_recovery
6059            && let Err(e) = selected.configure(&mut config)
6060        {
6061            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
6062            record(queue, task);
6063            return Vec::new();
6064        }
6065        (config, layers)
6066    };
6067    let config_evidence = crate::pr_recovery::ConfigEvidence {
6068        layers,
6069        overrides: task.overrides.clone(),
6070        daemon_merge: task
6071            .overrides
6072            .as_ref()
6073            .is_none_or(|o| o.inherit_daemon_options)
6074            .then(|| opts.merge.clone())
6075            .flatten(),
6076    };
6077    apply_task_implementers(&mut config, task);
6078    if let Some(replacement) = &task.replacement {
6079        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
6080            old.liveness(false) == Liveness::Dead
6081                && old.merge_decision.as_ref().is_some_and(|d| {
6082                    d.closed
6083                        && d.question == replacement.question
6084                        && d.replacement_run.as_ref().is_none_or(|run| {
6085                            task.execution_runs().last() == Some(run)
6086                                && RunState::load(run).is_ok_and(|current| {
6087                                    current.replaces.as_ref().is_some_and(|pin| {
6088                                        pin.question == replacement.question
6089                                            && pin.agent == replacement.agent
6090                                    })
6091                                })
6092                        })
6093                })
6094        });
6095        if !safe {
6096            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()));
6097            record(queue, task);
6098            return Vec::new();
6099        }
6100        match config.agent(&replacement.agent) {
6101            Ok(agent) if crate::agent::installed(agent) => {}
6102            _ => {
6103                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)));
6104                record(queue, task);
6105                return Vec::new();
6106            }
6107        }
6108        config.graph.implementers = 1;
6109        config.graph.land_approval = true;
6110        config.merge.mode = MergeMode::Pr;
6111        config.graph.selected_implementer = Some(replacement.agent.clone());
6112    }
6113    let p = phrases(&config.graph.language);
6114    let start_failed = p.could_not_start;
6115    // Resolve once for both admission and settlement. The inputs are the
6116    // task's explicit sources (never prose), plus an explicit review source's
6117    // current head; review-only runs may rebase later, and neither fact can
6118    // refund a failed automatic generation.
6119    if let Ok(base) =
6120        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6121            .await
6122        && let Ok(head) =
6123            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6124    {
6125        let mut inputs = crate::queue::recovery_inputs(&task.sources);
6126        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6127            let source = crate::git::rev_parse(&repo, branch)
6128                .await
6129                .unwrap_or_default();
6130            inputs.push_str(&format!(";review:{branch}:{source}"));
6131        }
6132        if let Some(reason) = task
6133            .recovery_exhausted(
6134                &head,
6135                &inputs,
6136                task.attempt_limit
6137                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6138            )
6139            .filter(|_| {
6140                !task.repair_grants.last().is_some_and(|receipt| {
6141                    RunState::load(&receipt.request.run)
6142                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6143                })
6144            })
6145        {
6146            task.hold_recovery_budget(
6147                reason,
6148                crate::queue::RecoveryAdmission { base: head, inputs },
6149            );
6150            record(queue, task);
6151            return Vec::new();
6152        }
6153        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6154    }
6155
6156    // A resumable run of this task is carried on, never re-competed. The
6157    // candidates are built and paid for, and a fresh competition races a
6158    // second implementation against them.
6159    //
6160    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
6161    // started 3cbf on the same task a moment later, duplicating two and a
6162    // half hours of agent work. Then b25f stalled on a judge that timed out
6163    // and one that answered with no JSON - `quota: 0`, so nothing the machine
6164    // was to blame for - and 4043 started **one second** later, buying three
6165    // fresh implementations to reach the same panel. `RunStatus::resumable`
6166    // rather than `!done()` is what catches the second case: a stall is
6167    // terminal, and its cheap recovery re-asks only the absent seats.
6168    //
6169    // A load failure is warned about rather than silently read as "not
6170    // resumable": the alternative is exactly what let a schema mismatch on
6171    // run `eba2` fall through to a full re-competition with nobody told why.
6172    // `crate::conduct` is what actually offers a better answer than
6173    // `Runner::start` here (see `Recovery::Review`), once this task's next
6174    // failure shows it up as `held`/`failed` with the run state unreadable.
6175    // Keep a retained review selection intact until disk admission succeeds.
6176    let consume_review = !previous
6177        .as_ref()
6178        .is_some_and(|state| crate::repair_budget::pending(task, state));
6179    let review_branch = consume_review
6180        .then(|| review_branch_for(task, previous.as_ref()))
6181        .flatten();
6182    let branch_exists = match review_branch {
6183        Some(branch) => crate::git::branch_exists(&repo, branch)
6184            .await
6185            .unwrap_or(false),
6186        None => false,
6187    };
6188    // An explicit `magi review <branch>` is reviewed whatever happens to the
6189    // branch unless an explicit implementer change requires fresh work. An
6190    // unfinished run of the same task still wins, so a retry resumes.
6191    let proposed = review_retry_starter(
6192        task,
6193        previous.as_ref(),
6194        review_branch,
6195        branch_exists,
6196        unfinished.as_deref(),
6197    );
6198    let retry_selected = task.replacement.is_some()
6199        && task.resumption.is_some()
6200        && !task.fresh_start
6201        && previous.as_ref().is_some_and(|run| {
6202            run.replaces.is_some()
6203                && ((run.status == RunStatus::Failed && run.viable().is_empty())
6204                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
6205        });
6206    let stop_pin = task
6207        .resume_override
6208        .as_ref()
6209        .filter(|pin| {
6210            Questions::open()
6211                .get_for_effects(&pin.question_id)
6212                .is_ok_and(|q| {
6213                    q.node == land::APPROVAL_NODE
6214                        && q.resolution()
6215                            .as_deref()
6216                            .is_some_and(crate::merge_decision::stops)
6217                })
6218        })
6219        .and_then(|pin| pin.pinned_run.clone());
6220    let granted_run = task.repair_grants.last().and_then(|receipt| {
6221        let state = RunState::load(&receipt.request.run).ok()?;
6222        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6223    });
6224    let starter = if let Some(run) = granted_run {
6225        Starter::Resume(run)
6226    } else if let Some(owner) = &public_owner {
6227        Starter::Resume(owner.id.clone())
6228    } else if let Some(run) = stop_pin {
6229        // Stop actions resume their exact owner even after seat-count edits;
6230        // they must never fall through to implementation or a takeover.
6231        Starter::Resume(run)
6232    } else if retry_selected {
6233        Starter::Resume(previous.as_ref().unwrap().id.clone())
6234    } else if let Some(selected) = &task.pr_recovery {
6235        if selected
6236            .check_retained_task(task, &crate::run::home())
6237            .is_ok()
6238        {
6239            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6240        } else {
6241            Starter::Review(selected.branch.clone())
6242        }
6243    } else {
6244        starter_with_implementers(task, previous.as_ref(), proposed)
6245    };
6246    // A retained execution still writes to its saved output volume. A newer
6247    // repository policy only selects the volume for a fresh run.
6248    let disk_reason = match &starter {
6249        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6250            || {
6251                RunState::load(id)
6252                    .ok()
6253                    .and_then(|run| disk_gate(&run.repo, &run.config))
6254            },
6255            |run| disk_gate(&run.repo, &run.config),
6256        ),
6257        _ => disk_gate(&repo, &config),
6258    };
6259    if let Some(reason) = disk_reason {
6260        task.notice_cause("disk-space", None, None);
6261        task.last_error = Some(reason.clone());
6262        let disk_checked_at = task.disk_checked_at;
6263        task.hold_machine(Some(reason.clone()));
6264        if matches!(starter, Starter::Resume(_)) {
6265            task.mark_disk_capacity();
6266        } else {
6267            task.mark_startup_disk_capacity();
6268        }
6269        task.disk_checked_at = disk_checked_at;
6270        record(queue, task);
6271        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6272        notices::raise(
6273            Notice::warn(
6274                &format!("disk:{}", repo.display()),
6275                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6276            )
6277            .link(Link::Task {
6278                id: task.id.clone(),
6279            }),
6280        );
6281        return Vec::new();
6282    }
6283    let review_branch = if consume_review {
6284        let valid = review_branch.is_some();
6285        task.review_instruction = None;
6286        task.review_branch.take().filter(|_| valid)
6287    } else {
6288        None
6289    };
6290    // An explicit resume pin must never degrade into a new competition or
6291    // takeover, including when its run stops being eligible after the answer.
6292    if let Some(pin) = &task.resume_override
6293        && let Some(run) = &pin.pinned_run
6294        && starter != Starter::Resume(run.clone())
6295    {
6296        let run = run.clone();
6297        task.notice_cause("resume-owner", Some(&run), None);
6298        task.hold_machine(Some(format!(
6299            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6300            task.id
6301        )));
6302        record(queue, task);
6303        return Vec::new();
6304    }
6305    // Automatic disk recovery resumes its retained run or stops: a changed
6306    // seat count or review branch must not turn it into a new competition.
6307    // No attempt is spent here.
6308    if let Some(run) = &task.disk_resume_run
6309        && starter != Starter::Resume(run.clone())
6310    {
6311        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()));
6312        record(queue, task);
6313        return Vec::new();
6314    }
6315    if task.replacement.is_some()
6316        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6317        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6318    {
6319        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()));
6320        record(queue, task);
6321        return Vec::new();
6322    }
6323    if let Some((ref run, ..)) = head_e2e_approval
6324        && starter != Starter::Resume(run.clone())
6325    {
6326        task.hold_machine(Some(format!(
6327            "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."
6328        )));
6329        record(queue, task);
6330        return Vec::new();
6331    }
6332    if let Some(reason) =
6333        retained_attempt_hold(task, &starter, config.disk.retained_attempt_limit, |id| {
6334            load_retained_attempt(&home, id)
6335        })
6336    {
6337        // The review choice was consumed above. Preserve it across this hold
6338        // so a later release cannot silently become a fresh implementation.
6339        if let Starter::Review(branch) = &starter {
6340            task.review_branch = Some(branch.clone());
6341        }
6342        task.hold_unrequested_retry(Some(reason));
6343        record(queue, task);
6344        return Vec::new();
6345    }
6346    // Absolute paths of the files the task was filed with, re-read from the
6347    // task now so a file attached while it was held reaches a resumed run
6348    // too. A stored name whose file has gone is an error before any agent is
6349    // paid for, never a silent omission the implementer cannot notice.
6350    let attachments = match task_attachments(queue, task) {
6351        Ok(a) => a,
6352        Err(e) => {
6353            task.attempts += 1;
6354            task.fail_startup_target(
6355                "startup-attachments",
6356                e.name.clone(),
6357                format!("{start_failed}{e:#}"),
6358                opts.max_attempts,
6359            );
6360            record(queue, task);
6361            return Vec::new();
6362        }
6363    };
6364    let startup_pause = stop.pause();
6365    let startup_interrupt = interrupt_pause.clone();
6366    let wait = crate::repo_lock::WaitPolicy::new(
6367        Duration::from_secs(config.graph.timeout_resource_wait),
6368        move || startup_pause.parked() || startup_interrupt.parked(),
6369    );
6370    // Startup includes review takeover and recovery. Do not embed its large
6371    // future in both the wait scope and the surrounding attempt stack frame.
6372    let started = wait.scope(Box::pin(async { match &starter {
6373        Starter::Review(_) if task.pr_recovery.is_some() => {
6374            let selected = task.pr_recovery.clone().expect("selected recovery");
6375            match selected.check_retained_task(task, &crate::run::home()) {
6376                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6377                    .await
6378                    .map(|mut r| {
6379                        r.state.attachments = attachments.clone();
6380                        r
6381                    }),
6382                Err(e) => Err(e),
6383            }
6384        }
6385        Starter::Review(branch) => {
6386            tracing::info!(
6387                "task {} reopens `{branch}` as a review-only pass",
6388                task.short()
6389            );
6390            // Every earlier attempt is superseded by the one being minted
6391            // now, so a branch one of them still holds may be taken over.
6392            let takeover = crate::handover::Takeover {
6393                earlier: task.earlier_attempts().to_vec(),
6394                home: crate::run::home(),
6395                choice: take_divergence_answer(branch, &config.merge.remote, task),
6396                task_instruction: Some(instruction_for(task)),
6397            };
6398            Runner::review_taking_over(
6399                &repo,
6400                branch,
6401                config,
6402                Some(takeover),
6403                crate::run::Origin::queue(&task.id),
6404            )
6405            .await
6406        }
6407        Starter::Resume(id) => {
6408            tracing::info!("resuming run {id} rather than competing again");
6409            Runner::resume(id).and_then(|mut r| {
6410                if retry_selected {
6411                    // The explicit queue release retries this same pinned
6412                    // implementation, preserving the attempt and worktrees.
6413                    for candidate in &mut r.state.candidates {
6414                        candidate.failed = None;
6415                        candidate.empty = false;
6416                        candidate.commits = 0;
6417                    }
6418                    r.state.status = RunStatus::Implementing;
6419                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6420                }
6421                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6422                    r.state.sources = task.sources.clone();
6423                }
6424                if r.state.prep_failure.is_some() {
6425                    let approval = task
6426                        .resumption
6427                        .as_ref()
6428                        .context("preparation retry requires an explicit task release")?;
6429                    r.retry_preparation(approval.at)?;
6430                }
6431                if let Some(instruction) =
6432                    prepare_instruction(&starter, Some(&r.state.instruction), task)
6433                {
6434                    r.state.instruction = instruction;
6435                }
6436                r.state.attachments = attachments.clone();
6437                if task.replacement.is_some() {
6438                    r.state.config.merge.mode = MergeMode::Pr;
6439                    r.state.config.graph.land_approval = true;
6440                }
6441                // Replacements publish a new PR and ask again. Selected PR
6442                // recoveries keep their saved disposition; ordinary runs can
6443                // retain the task's merge override.
6444                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6445                    .overrides
6446                    .as_ref()
6447                    .and_then(|o| o.merge.as_deref())
6448                    .and_then(|m| merge_mode(m).ok())
6449                {
6450                    r.state.config.merge.mode = mode;
6451                }
6452                Ok(r)
6453            })
6454        }
6455        Starter::Start => {
6456            if let Some(branch) = &review_branch {
6457                tracing::warn!(
6458                    "conductor chose review for task {} but branch `{branch}` no longer \
6459                     exists; requeuing as a fresh competition instead",
6460                    task.short()
6461                );
6462            }
6463            let instruction = prepare_instruction(&starter, None, task)
6464                .unwrap_or_else(|| task.instruction.clone());
6465            Runner::start_naming(
6466                &repo,
6467                instruction,
6468                &task.title,
6469                config,
6470                crate::run::Origin::queue(&task.id),
6471            )
6472            .await
6473            .map(|mut r| {
6474                r.state.attachments = attachments.clone();
6475                r.state.sources = task.sources.clone();
6476                r
6477            })
6478        }
6479    }})).await;
6480    if let Err(error) = &started
6481        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6482    {
6483        task.record_startup_failure(failure.clone());
6484    }
6485    let mut runner = match started {
6486        Ok(r) => r,
6487        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6488            let detail = format!("{e:#}");
6489            task.last_error = Some(detail.clone());
6490            if e.is::<crate::build_target::AdmissionDiskWait>()
6491                && let Starter::Review(branch) = &starter
6492                && review_branch.is_some()
6493            {
6494                task.review_branch = Some(branch.clone());
6495                task.review_instruction = Some(task.instruction.clone());
6496            }
6497            if stop.parking() || interrupt_pause.parked() {
6498                let attempts = task.attempts;
6499                task.park(e.to_string());
6500                // Startup has not spent an attempt to refund.
6501                task.attempts = attempts;
6502            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6503                let disk_checked_at = task.disk_checked_at;
6504                task.hold_machine(Some(detail));
6505                task.mark_startup_disk_capacity();
6506                task.disk_checked_at = disk_checked_at;
6507            } else {
6508                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6509            }
6510            record(queue, task);
6511            return Vec::new();
6512        }
6513        // A branch an earlier attempt still holds and magi will not release
6514        // by itself is the operator's call, not a failed attempt: hold the
6515        // task with the reason, spend nothing, and say so on the bell.
6516        Err(e) if task.pr_recovery.is_some() => {
6517            task.startup_notice_cause("startup-public-head");
6518            task.attempts += 1;
6519            task.last_error = Some(format!("{start_failed}{e:#}"));
6520            task.hold_unrequested_retry(Some(format!(
6521                "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."
6522            )));
6523            record(queue, task);
6524            return Vec::new();
6525        }
6526        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6527            let detail = match e.downcast_ref::<crate::handover::Refused>() {
6528                Some(r) => (p.handover_refused)(r),
6529                None => format!("{e:#}"),
6530            };
6531            task.startup_notice_cause("startup-handover");
6532            let reason = format!("{start_failed}{detail}");
6533            task.last_error = Some(reason.clone());
6534            // Consumed above by `take`; keep it so the released task retries
6535            // as a review of this same branch.
6536            let branch = match &starter {
6537                Starter::Review(branch) => Some(branch.clone()),
6538                _ => None,
6539            };
6540            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
6541            // one page; the guidance rides in the reason, fixed per state so a
6542            // re-put never changes the wording and relights it.
6543            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6544            record(queue, task);
6545            tracing::warn!(
6546                "holding {} for a branch it cannot take over: {e:#}",
6547                task.short()
6548            );
6549            return Vec::new();
6550        }
6551        // A branch that differs between here and the remote in ways magi
6552        // cannot prove are the same change is a decision for the owner, not a
6553        // failed attempt: ask with both sides laid out, spend no attempt, and
6554        // let the answer requeue the task.
6555        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6556            let d = e
6557                .downcast_ref::<crate::reconcile::Diverged>()
6558                .expect("checked by the guard");
6559            let mut q = ask::Question::new(
6560                task.id.clone(),
6561                crate::reconcile::NODE.to_owned(),
6562                crate::reconcile::SEAT.to_owned(),
6563                d.summary(),
6564                d.detail(),
6565                d.choices(),
6566            );
6567            match Questions::open().put(&mut q) {
6568                Ok(()) => {
6569                    task.last_error = Some(format!("{e:#}"));
6570                    // Consumed above by `take`; the answer has to reach a review
6571                    // of this same branch, so keep pointing the task at it.
6572                    task.review_branch = Some(d.branch.clone());
6573                    task.review_instruction = Some(task.instruction.clone());
6574                    task.block(vec![q.id.clone()], Some(d.summary()));
6575                }
6576                Err(put) => {
6577                    tracing::warn!("could not file the divergence question: {put:#}");
6578                    task.attempts += 1;
6579                    task.fail_startup(
6580                        "startup-question-store",
6581                        format!("{start_failed}{e:#}"),
6582                        opts.max_attempts,
6583                    );
6584                }
6585            }
6586            record(queue, task);
6587            return Vec::new();
6588        }
6589        Err(e) => {
6590            // The answer was stale and nothing was applied: keep pointing at
6591            // the branch so the next attempt asks again against its new tips.
6592            // Nothing went wrong with the task, so no attempt is spent: a
6593            // budget one short of its limit must not hold it instead of
6594            // letting the question be asked again.
6595            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6596                && let Starter::Review(branch) = &starter
6597            {
6598                task.review_branch = Some(branch.clone());
6599                task.review_instruction = Some(task.instruction.clone());
6600                task.last_error = Some(format!("{start_failed}{e:#}"));
6601                task.status = crate::queue::TaskStatus::Failed;
6602                record(queue, task);
6603                return Vec::new();
6604            }
6605            task.attempts += 1;
6606            task.last_error = Some(format!("{start_failed}{e:#}"));
6607            task.startup_notice_cause("startup-source");
6608            task.hold_unrequested_retry(Some(format!(
6609                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6610            )));
6611            record(queue, task);
6612            return Vec::new();
6613        }
6614    };
6615    if !matches!(starter, Starter::Resume(_))
6616        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6617    {
6618        runner
6619            .state
6620            .event("build-cache", format!("{mode} selected by {source}"));
6621    }
6622    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6623        runner.state.recovery_config = Some(config_evidence);
6624    }
6625    if let Some(replacement) = &task.replacement {
6626        if matches!(starter, Starter::Start) {
6627            runner.state.instruction.push_str(&format!(
6628                "\n\n# Replacement review context\n{}",
6629                replacement.context
6630            ));
6631        }
6632        runner.state.replaces = Some(replacement.clone());
6633        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6634        if let Ok(mut old) = RunState::load(&replacement.run)
6635            && let Some(d) = &mut old.merge_decision
6636        {
6637            d.replacement_run = Some(runner.state.id.clone());
6638            old.event(
6639                "replacement",
6640                format!(
6641                    "replacement run {} owns the next attempt; old PR remains closed",
6642                    runner.state.id
6643                ),
6644            );
6645            if let Err(e) = old.save() {
6646                let error = runner.fail_startup("replacement-history", e);
6647                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6648                    task.record_startup_failure(failure.clone());
6649                }
6650                task.hold_manual(Some(format!(
6651                    "Could not link replacement history: {error:#}; no agents dispatched"
6652                )));
6653                record(queue, task);
6654                return Vec::new();
6655            }
6656        }
6657    }
6658    runner.state.task_instruction = Some(task.instruction.clone());
6659    runner.state.task_instruction_rev = Some(task.instruction_rev);
6660    // The follow-up depth is fixed now, while the task certainly exists:
6661    // deleting it later must not reset the cap (`crate::followup`).
6662    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6663    if runner.state.origin_chat.is_none() {
6664        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6665    }
6666    // A stop that means "park" reaches the graph through this handle.
6667    runner.on_pause(stop.pause());
6668    // `poll`'s interrupt scheduler reaches this one run - and no other -
6669    // through this handle. See `Pause`'s own doc for why these are never
6670    // the same one.
6671    runner.watch_interrupt(interrupt_pause);
6672
6673    // `start` has minted the run, so the task can now point at it. Persisting
6674    // `Running` before `execute` is what makes a crash mid-run legible.
6675    let run = runner.state.id.clone();
6676    let before_start = task.clone();
6677    task.start(run.clone());
6678    if let Err(error) = queue.put(task) {
6679        *task = before_start;
6680        let error = runner.fail_startup("task-start", error);
6681        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6682            task.record_startup_failure(failure.clone());
6683        }
6684        task.hold_manual(Some(format!(
6685            "Could not persist task start; no agents dispatched: {error:#}"
6686        )));
6687        record(queue, task);
6688        return Vec::new();
6689    }
6690    if task.status != TaskStatus::Running {
6691        // Queue::put kept a newer hold or continuation instead of this start.
6692        return Vec::new();
6693    }
6694    lock(status).current.push(Current {
6695        worker: None,
6696        task: task.id.clone(),
6697        run,
6698    });
6699
6700    // `RunState::quota` is the run's whole history across every resume, so
6701    // only what this execution added may arm the cooldown or earn a refund.
6702    let quota_before = runner.state.quota.clone();
6703    runner.state.carry_dispatched_resumes(task);
6704    runner.state.entry_resumption_generation =
6705        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6706    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6707        && runner.state.id == run
6708    {
6709        crate::head_e2e_stop::record_consumed_approval(
6710            &mut runner.state,
6711            &task.id,
6712            &stop_id,
6713            generation,
6714            approval_at,
6715        );
6716    }
6717    runner.state.next_pass_task_entry = true;
6718    let result = runner.execute().await;
6719    finish_attempt(
6720        opts.max_attempts,
6721        queue,
6722        task,
6723        &runner.state,
6724        &quota_before,
6725        result,
6726    )
6727}
6728
6729async fn attempt_sync_only(
6730    queue: &Queue,
6731    status: &Arc<Mutex<Status>>,
6732    stop: &Stop,
6733    interrupt: crate::graph::Pause,
6734    task: &mut Task,
6735    request: crate::base_sync_only::Request,
6736) {
6737    let result = async {
6738        anyhow::ensure!(
6739            task.status == TaskStatus::Queued
6740                && task.execution_runs().last() == Some(&request.run)
6741                && task.resume_override.as_ref().is_some_and(
6742                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6743                ),
6744            "sync-base-only request no longer owns the exact queued run"
6745        );
6746        let mut runner = Runner::resume(&request.run)?;
6747        anyhow::ensure!(
6748            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6749                .await?
6750                .is_none(),
6751            "the task still has a public execution owner"
6752        );
6753        anyhow::ensure!(
6754            !stop.parking() && !interrupt.parked(),
6755            "paused before base synchronization"
6756        );
6757        let original = task.clone();
6758        task.start(request.run.clone());
6759        task.attempts = original.attempts;
6760        if let Err(error) = queue.put(task) {
6761            *task = original;
6762            return Err(error);
6763        }
6764        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6765            return Ok(());
6766        }
6767        lock(status).current.push(Current {
6768            worker: None,
6769            task: task.id.clone(),
6770            run: request.run.clone(),
6771        });
6772        runner.on_pause(stop.pause());
6773        runner.watch_interrupt(interrupt);
6774        runner.execute_sync_only(request.clone()).await
6775    }
6776    .await;
6777    if task.sync_only.as_ref() == Some(&request) {
6778        let saved = RunState::load(&request.run).ok();
6779        let detail = result.err().map(|error| {
6780            format!("Base synchronization only: {error:#}; verification was not allowed")
6781        });
6782        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6783        record(queue, task);
6784    }
6785}
6786
6787/// Settle `task` after its run executed: the verdict, the diagnosis, the
6788/// supersession of earlier attempts and the save. Shared by the loop and by
6789/// `magi run --resume`, so an attempt is counted one way wherever it ran.
6790/// Returns the quota losses this execution added to the run.
6791pub fn finish_attempt(
6792    max_attempts: usize,
6793    queue: &Queue,
6794    task: &mut Task,
6795    state: &RunState,
6796    quota_before: &[QuotaLoss],
6797    result: Result<()>,
6798) -> Vec<QuotaLoss> {
6799    let detail = match result {
6800        Ok(()) => describe(state),
6801        Err(e) => format!("{e:#}"),
6802    };
6803    let fresh = losses_this_attempt(quota_before, &state.quota);
6804    let verdict = Verdict {
6805        status: state.status,
6806        // A run that opened a pull request handed its work over, whatever the
6807        // gate then decided about merging it.
6808        left_pr: state.pr.is_some(),
6809        // Only a rate limit earns the task its attempt back - and only one
6810        // suffered now: a refund justified by a previous session's loss is
6811        // the same mistake as re-arming the cooldown from it. A stalled run
6812        // resumed without hitting quota again therefore spends its attempt,
6813        // like any other failure of the task's own.
6814        quota_hit: !fresh.is_empty(),
6815        // A run that parked was asked to stop; that is not a failure and must
6816        // not spend an attempt, or replacing the binary a few times would
6817        // exhaust a task's budget without an agent ever misbehaving.
6818        parked: state.parked,
6819        // A quota loss that left nothing viable is the same machine fact as a
6820        // `Stalled` quota loss; see `settle`'s doc table.
6821        no_viable_candidates: state.viable().is_empty(),
6822    };
6823    if let Some(replacement) = &state.replaces
6824        && let Some(pr) = &state.pr
6825        && let Ok(mut old) = RunState::load(&replacement.run)
6826        && let Some(d) = &mut old.merge_decision
6827    {
6828        d.replacement_pr = Some(pr.url.clone());
6829        let _ = old.save();
6830    }
6831    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6832    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6833        task.hold_unrequested_retry(Some(format!(
6834            "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.",
6835            task.short()
6836        )));
6837    }
6838    if task.status == TaskStatus::Done {
6839        supersede_prior_runs(task, &crate::run::home());
6840    }
6841    record(queue, task);
6842    tracing::info!(
6843        "task {} is {} after run {} ({})",
6844        task.short(),
6845        task.status.as_str(),
6846        state.short(),
6847        label(state.status)
6848    );
6849    fresh
6850}
6851
6852/// A task a hand-started run leaves runnable (failed with attempts to spare,
6853/// or requeued) is **held**: nobody asked for a retry, and a loop starting
6854/// later must not spend agent calls on it. `magi task release` retries.
6855pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6856    // Parked work (including legacy Failed records with a parked run) is a
6857    // checkpoint or owner handoff, not an unrequested retry.
6858    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6859        && !awaiting_resume_with(task, RunState::load)
6860        // A run parked on the owner's word about a withheld PR title/body
6861        // resumes via `land_resume_state`, including review-only tasks that
6862        // `awaiting_resume_with` does not consider.
6863        && withheld_text_wait(task).is_none()
6864        && !(task.fresh_start && task.replacement.is_some())
6865    {
6866        let why = task.last_error.clone().map_or_else(
6867            || "the run did not finish".to_owned(),
6868            |e| format!("the run did not finish: {e}"),
6869        );
6870        task.hold_unrequested_retry(Some(format!(
6871            "{why}. It was started by hand, so it is not retried \
6872             automatically; `magi task release` retries it."
6873        )));
6874        record(queue, task);
6875    }
6876}
6877
6878/// Whether an attempt at a task whose newest run is `run` would resume that
6879/// run rather than start a fresh competition. `magi run --resume` hands a run
6880/// to a live loop only when this holds.
6881#[must_use]
6882pub fn loop_would_resume(run: &str) -> bool {
6883    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6884}
6885
6886/// A loop in another process that is alive right now: a fresh heartbeat in
6887/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
6888/// carries the pid it published (`None` inside when it published none - a
6889/// fresh heartbeat is still evidence of a live loop).
6890///
6891/// The one judgement of "is somebody else serving this queue", shared by the
6892/// web UI's refusal to start a second loop and by `magi run` / `magi review`
6893/// deciding whether to hand a task to the loop. A claim file proves nothing
6894/// here: whether a claim succeeds says nothing about whether its owner lives.
6895#[must_use]
6896pub fn foreign_loop(
6897    reading: Option<&Reading>,
6898    now: Timestamp,
6899    own_pid: u32,
6900) -> Option<Option<u32>> {
6901    let reading = reading.filter(|r| r.running(now))?;
6902    match reading.pid {
6903        Some(pid) if pid == own_pid => None,
6904        pid => Some(pid),
6905    }
6906}
6907
6908fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6909    reading.worker_protocol != Some(1)
6910        && (foreign_loop(Some(reading), now, own_pid).is_some()
6911            || reading
6912                .pid
6913                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6914}
6915
6916/// Low-level claimed-task execution shared by the detached standalone worker
6917/// and focused lifecycle fixtures. The caller must retain the queue claim for
6918/// this entire call. CLI callers transfer ownership through
6919/// [`run_detached_claimed`] instead of executing inside their own runtime.
6920///
6921/// The one deliberate difference from the loop: a task the attempt leaves
6922/// runnable (failed with attempts to spare, or requeued) is **held** instead.
6923/// Nobody asked for a retry, and a daemon starting later must not spend agent
6924/// calls re-running a hand-started task behind the operator's back;
6925/// `magi task release` is the explicit retry.
6926pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6927    run_claimed_until(opts, queue, task, &Stop::new()).await;
6928}
6929
6930async fn run_claimed_until(
6931    opts: &Opts,
6932    queue: &Queue,
6933    task: &mut Task,
6934    stop: &Stop,
6935) -> Vec<QuotaLoss> {
6936    let status = Arc::new(Mutex::new(Status::new()));
6937    // An attempt embeds startup and graph futures. Keep it off the standalone
6938    // caller's stack, on both the initial execution and withheld-text resume.
6939    let mut quota = Box::pin(attempt(
6940        opts,
6941        queue,
6942        &status,
6943        stop,
6944        crate::graph::Pause::new(),
6945        task,
6946    ))
6947    .await;
6948    // A run parked on the owner's word about a withheld PR title/body has no
6949    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
6950    // here with the claim still held, and resume once the question is settled
6951    // (answered, or abandoned at its deadline -> the neutral text).
6952    // A rejected reply files one more question (the gate asks at most twice),
6953    // so after a resume the run may be waiting again: keep going, with a fresh
6954    // limit for the new question. `resumes` bounds it even if a resume parks
6955    // without asking anything new.
6956    let mut resumes = 0;
6957    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6958        let Some(timeout) = withheld_text_wait(task) else {
6959            break;
6960        };
6961        eprintln!(
6962            "waiting for the owner's answer on a withheld pull request text \
6963             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6964        );
6965        // The deadline abandons the question itself; the extra margin only
6966        // covers an abandon that could not be saved.
6967        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6968        let ready = loop {
6969            match land_resume_state(task) {
6970                LandResume::StillWaiting
6971                    if !stop.parking() && std::time::Instant::now() < limit =>
6972                {
6973                    tokio::time::sleep(WITHHELD_POLL).await;
6974                }
6975                LandResume::Ready => break true,
6976                _ => break false,
6977            }
6978        };
6979        if !ready || stop.parking() {
6980            break;
6981        }
6982        resumes += 1;
6983        quota.extend(
6984            Box::pin(attempt(
6985                opts,
6986                queue,
6987                &status,
6988                stop,
6989                crate::graph::Pause::new(),
6990                task,
6991            ))
6992            .await,
6993        );
6994    }
6995    hold_if_runnable(queue, task);
6996    quota
6997}
6998
6999/// Resumes an in-process run makes for withheld-text questions: the gate asks
7000/// at most twice, plus one for a resume that asks nothing new.
7001const MAX_WITHHELD_RESUMES: u32 = 3;
7002
7003/// How often an in-process run rechecks its withheld-text question.
7004const WITHHELD_POLL: Duration = Duration::from_secs(15);
7005
7006/// The `answer_timeout` (seconds) of the task's last run when that run is
7007/// parked on an unresolved withheld-text question; `None` otherwise.
7008fn withheld_text_wait(task: &Task) -> Option<u64> {
7009    let id = task.execution_runs().last()?;
7010    let s = RunState::load(id).ok()?;
7011    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
7012        .then_some(s.config.graph.answer_timeout)
7013}
7014
7015/// The quota losses `after` holds that `before` did not: what one execution
7016/// suffered, as opposed to the run's history.
7017///
7018/// Compared by value rather than by length or position because
7019/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
7020/// the vector can shrink and shift under a resume. A retried seat that hits
7021/// quota again is a `push` with a new `at`, so it shows up as new here.
7022/// Crash recovery uses the recorded pass start as its boundary when available;
7023/// legacy records without passes retain their original history-based policy.
7024fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
7025    after
7026        .iter()
7027        .filter(|q| !before.contains(q))
7028        .cloned()
7029        .collect()
7030}
7031
7032/// When the loop-wide quota cooldown should end, given this attempt's losses;
7033/// `None` when there were none. Reset-hint parsing and the cap live here.
7034fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
7035    let quota: Vec<_> = quota
7036        .iter()
7037        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
7038        .collect();
7039    if quota.is_empty() {
7040        return None;
7041    }
7042    let with_hint = quota.iter().find(|q| q.reset.is_some());
7043    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
7044    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
7045    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
7046    Some(
7047        now.checked_add(jiff::SignedDuration::from_secs(secs))
7048            .unwrap_or(Timestamp::MAX),
7049    )
7050}
7051
7052/// An explicit task count must agree with a run before any resume.
7053fn implementers_match(task: &Task, state: &RunState) -> bool {
7054    task.replacement.as_ref().map_or_else(
7055        || {
7056            task.implementers()
7057                .is_none_or(|n| n == state.config.graph.implementers)
7058        },
7059        |replacement| {
7060            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
7061                && state.config.graph.implementers == 1
7062        },
7063    )
7064}
7065
7066/// Never resume or take over candidate work built for a different seat count.
7067fn starter_with_implementers(
7068    task: &Task,
7069    previous: Option<&RunState>,
7070    proposed: Starter,
7071) -> Starter {
7072    if previous.is_some_and(|s| !implementers_match(task, s)) {
7073        task.review_of
7074            .as_ref()
7075            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
7076    } else {
7077        proposed
7078    }
7079}
7080
7081/// Apply this task's explicit count to the new attempt, without changing defaults.
7082fn apply_task_implementers(config: &mut Config, task: &Task) {
7083    if let Some(n) = task.implementers() {
7084        config.graph.implementers = n;
7085    }
7086}
7087
7088/// [`prepare`] for one task: its own `--config` and command-line overrides
7089/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
7090/// over the loop's, so handing a hand-started task to a daemon changes nothing
7091/// about what it does.
7092#[cfg(test)]
7093fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
7094    let explicit = match &task.overrides {
7095        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
7096        _ => opts.config.as_deref(),
7097    };
7098    let (mut config, _) = Config::discover(repo, explicit)?;
7099    apply_options(&mut config, opts, task)?;
7100    Ok(config)
7101}
7102
7103fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
7104    if task
7105        .overrides
7106        .as_ref()
7107        .is_none_or(|o| o.inherit_daemon_options)
7108        && let Some(mode) = opts.merge.as_deref()
7109    {
7110        config.merge.mode = merge_mode(mode)?;
7111    }
7112    if let Some(o) = &task.overrides {
7113        o.apply(config);
7114    }
7115    if let Some((mode, _)) = task.build_cache_override(config) {
7116        config.verify.build_cache = mode;
7117    }
7118    Ok(())
7119}
7120
7121/// Load the config for a task's repository, with the merge override applied.
7122fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7123    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7124    if let Some(mode) = &opts.merge {
7125        config.merge.mode = merge_mode(mode)?;
7126    }
7127    Ok(config)
7128}
7129
7130/// Prune the shared build cache at a between-runs boundary. The detached cache
7131/// service checks authoritative task jobs first; dispatch waits for that finite
7132/// service, so scheduler replacement cannot turn a compile into idle cleanup.
7133/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
7134async fn maybe_prune_cache_between_runs(
7135    repo: &Path,
7136    opts: &Opts,
7137    home: &Path,
7138    stop: &Stop,
7139    last_checked: &mut Option<Timestamp>,
7140    now: Timestamp,
7141) {
7142    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7143        return;
7144    }
7145    *last_checked = Some(now);
7146    let cfg = match prepare(repo, opts) {
7147        Ok(cfg) => cfg,
7148        Err(e) => {
7149            tracing::warn!("cache check: no config: {e:#}");
7150            return;
7151        }
7152    };
7153    match clean::prune_cache_if_over_limit(&cfg, home) {
7154        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7155            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7156            pruned.files,
7157            pruned.freed
7158        ),
7159        Ok(_) => {}
7160        Err(e) => {
7161            tracing::warn!("housekeep: prune cache: {e:#}");
7162            notices::raise_in(
7163                home,
7164                Notice::warn(
7165                    "housekeep:cache",
7166                    format!(
7167                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7168                        e.to_string()
7169                            .lines()
7170                            .next()
7171                            .unwrap_or("unknown cleanup error")
7172                    ),
7173                ),
7174            );
7175        }
7176    }
7177}
7178
7179/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
7180/// now, given when it last did (if ever). Pure, so the cadence is asserted
7181/// directly rather than by waiting out real minutes in a test.
7182fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7183    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7184}
7185
7186/// The disk janitor, with its housekeeping logged rather than fatal.
7187///
7188/// Called only at the loop's idle points, for the reason the caller documents:
7189/// a prune racing a live compile would delete files mid-build. The config is
7190/// re-read on every call because the repository that just ran may not be the
7191/// daemon's own default, and the cache directory is a repository fact.
7192///
7193/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
7194/// and [`crate::run::default_worktree_root`] read here, for the same reason
7195/// [`drive`] takes its queue and status file rather than resolving them: a
7196/// test driving the loop must not reach through to the operator's real home
7197/// or worktree bay just because the janitor runs on every idle tick.
7198/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
7199/// to get wrong silently - a test's `home` was already isolated, but nothing
7200/// exercised the parameter next to it, so a real worktree bay stayed wired in
7201/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
7202/// it for real, every test in this file that drives the loop at all started
7203/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
7204async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7205    let cfg = match prepare(repo, opts) {
7206        Ok(cfg) => cfg,
7207        Err(e) => {
7208            tracing::warn!("housekeep: no config: {e:#}");
7209            return;
7210        }
7211    };
7212    // A run's own worktree lives under `config.graph.worktree_root` when the
7213    // repository sets one - the same precedence `RunState::worktree_root`
7214    // uses - and `worktrees_root` only stands in for the *default* an
7215    // unconfigured repository resolves to (see this function's own
7216    // parameter, or the test fixture wiring one to a fake path). Housekeeping
7217    // that always swept the default regardless of this override would never
7218    // see, and so never reclaim, a single worktree for a repository that
7219    // relocated them elsewhere.
7220    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7221    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7222    // Reported whenever there is anything to say, not only when `folded > 0`:
7223    // the incident this exists to prevent was 90 of 93 runs skipped and 0
7224    // folded, on every single pass, for months - a report gated on `folded`
7225    // would have stayed silent through every one of them.
7226    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7227        let mut extra = Vec::new();
7228        if out.unreadable > 0 {
7229            extra.push(format!("{} unreadable", out.unreadable));
7230        }
7231        if out.orphaned_worktrees > 0 {
7232            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7233        }
7234        let detail = if extra.is_empty() {
7235            String::new()
7236        } else {
7237            format!(" ({})", extra.join(", "))
7238        };
7239        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7240    }
7241    if out.external_merges_recorded > 0 {
7242        tracing::info!(
7243            "housekeep: recorded {} run(s) as merged externally",
7244            out.external_merges_recorded
7245        );
7246    }
7247    if out.stale_pr_states_repaired > 0 {
7248        tracing::info!(
7249            "housekeep: updated {} run record(s) from the current pull request state",
7250            out.stale_pr_states_repaired
7251        );
7252    }
7253    if out.cache_files > 0 {
7254        tracing::info!(
7255            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7256            out.cache_files,
7257            out.cache_freed
7258        );
7259    }
7260    if out.questions_abandoned > 0 {
7261        tracing::info!(
7262            "housekeep: abandoned {} question(s) left open by a finished run",
7263            out.questions_abandoned
7264        );
7265    }
7266}
7267
7268/// Run [`triage::run_once`] and log whatever it did, the same "only when
7269/// there is something to say" rule [`janitor`] follows for its own report.
7270///
7271/// Called at the same idle points as [`janitor`] - once per full poll
7272/// interval, never mid-attempt - for the same reason: it is not liveness
7273/// critical, and a task's own `hold_reason` string is the one thing this
7274/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
7275/// tick for no benefit.
7276async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7277    let questions = Questions::at(home.join("questions"));
7278    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7279    if report.is_empty() {
7280        return;
7281    }
7282    if !report.quarantined.is_empty() {
7283        tracing::info!(
7284            "triage: held {} blocked task(s) whose blocked-on task or \
7285             question no longer exists: {}",
7286            report.quarantined.len(),
7287            report.quarantined.join(", ")
7288        );
7289    }
7290    if !report.resumed.is_empty() {
7291        tracing::info!(
7292            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7293            report.resumed.len(),
7294            report.resumed.join(", ")
7295        );
7296    }
7297    if !report.asked.is_empty() {
7298        tracing::info!(
7299            "triage: asked about {} held task(s): {}",
7300            report.asked.len(),
7301            report.asked.join(", ")
7302        );
7303    }
7304    if !report.answered.is_empty() {
7305        tracing::info!(
7306            "triage: applied {} operator answer(s): {}",
7307            report.answered.len(),
7308            report.answered.join(", ")
7309        );
7310    }
7311}
7312
7313/// The free-space gate: what stands between this task and a new run, if
7314/// anything. `Some(reason)` holds the task; `None` lets it start.
7315///
7316/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
7317/// the operator opted out. A measurement failure is a gate, not a pass: both
7318/// sides of "cannot tell" are served by not starting.
7319pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7320    disk_gate_at(repo, config, crate::run::home)
7321}
7322
7323pub(crate) fn disk_gate_at(
7324    repo: &Path,
7325    config: &Config,
7326    home: impl FnOnce() -> PathBuf,
7327) -> Option<String> {
7328    let measure = if crate::build_target::isolated(config) {
7329        crate::disk::managed_free_bytes
7330    } else {
7331        crate::disk::free_bytes
7332    };
7333    disk_gate_with(repo, config, home, measure)
7334}
7335
7336/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
7337/// test can assert the exact wiring `attempt` runs - config's threshold in,
7338/// task-holding reason out - without asking the real machine's disk anything.
7339fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7340    repo: &Path,
7341    config: &Config,
7342    home: impl FnOnce() -> PathBuf,
7343    free_bytes: F,
7344) -> Option<String> {
7345    let min = config.disk.min_free_bytes;
7346    if min == 0 {
7347        return None;
7348    }
7349    let output = match config.verify.build_cache {
7350        BuildCache::Shared => config.cache_dir(),
7351        BuildCache::Isolated => Some(home()),
7352    };
7353    let default_worktree_root;
7354    let worktree_root = match config.graph.worktree_root.as_deref() {
7355        Some(root) => root,
7356        None => {
7357            default_worktree_root = crate::run::default_worktree_root();
7358            &default_worktree_root
7359        }
7360    };
7361    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7362        .into_iter()
7363        .flatten()
7364    {
7365        let probe = if path == repo {
7366            path
7367        } else {
7368            path.ancestors().find(|p| p.exists()).unwrap_or(path)
7369        };
7370        let reason = match free_bytes(probe) {
7371            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7372            Err(e) => Some(crate::disk::unmeasured_in(
7373                probe,
7374                &e,
7375                &config.graph.language,
7376            )),
7377        };
7378        if reason.is_some() {
7379            return reason;
7380        }
7381    }
7382    None
7383}
7384
7385/// How long to wait before offering another task when a run lost a seat to a
7386/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
7387/// could read, or carried nothing at all. Long enough that a quota outage
7388/// cannot burn through a whole backlog in the few seconds each doomed attempt
7389/// takes to fail; short enough that a quota which clears early is not left
7390/// idle for the fallback's sake.
7391const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7392
7393/// Longest a parsed reset hint may push the wait out to. The hint comes from
7394/// the CLI's own words, not a contract, so a parsing slip that lands a day
7395/// away must not leave the loop asleep for a day.
7396const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7397
7398/// How long [`poll`] should wait before offering the next task, after a run
7399/// lost at least one seat to a rate limit.
7400///
7401/// Pure and separate from the loop so the policy can be exercised without a
7402/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
7403/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
7404/// nothing to parse, or the parsed time has already passed; `cap` bounds how
7405/// far a parsed hint is trusted to push the wait out.
7406fn quota_wait(
7407    reset_at: Option<Timestamp>,
7408    now: Timestamp,
7409    fallback: Duration,
7410    cap: Duration,
7411) -> Duration {
7412    match reset_at {
7413        Some(at) if at > now => {
7414            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7415            Duration::from_secs(secs).min(cap)
7416        }
7417        _ => fallback,
7418    }
7419}
7420
7421/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
7422///
7423/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
7424/// explains why parsing it exactly "would be a bug factory" — so this only
7425/// recognises the shapes actually observed in the wild, and returns `None`
7426/// for anything else rather than guess at a format nobody has seen.
7427///
7428/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
7429/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
7430/// said it, not from whenever this loop happens to read it: anchoring on `now`
7431/// would push the reset later on every read and would read an already-elapsed
7432/// reset as still in the future. (A long hint is still clamped by
7433/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
7434fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7435    parse_reset_hint_zoned(text, now)
7436        .or_else(|| parse_reset_hint_dated(text))
7437        .or_else(|| parse_reset_hint_relative(text, recorded))
7438}
7439
7440/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
7441/// optional but at least one required, in that order. A bare number or any
7442/// unknown unit is refused.
7443fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7444    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7445    let mut rest = rest.trim();
7446    if rest.is_empty() {
7447        return None;
7448    }
7449    let mut total: i64 = 0;
7450    let mut matched = false;
7451    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7452        if let Some((digits, tail)) = rest.split_once(unit)
7453            && !digits.is_empty()
7454            && digits.bytes().all(|b| b.is_ascii_digit())
7455        {
7456            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7457            rest = tail;
7458            matched = true;
7459        }
7460    }
7461    if !rest.is_empty() || !matched {
7462        return None;
7463    }
7464    recorded
7465        .checked_add(jiff::SignedDuration::from_secs(total))
7466        .ok()
7467}
7468
7469/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
7470/// case-insensitive) into a 24-hour hour and minute. Shared by every
7471/// reset-hint shape below.
7472fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7473    let clock = clock.trim().to_lowercase();
7474    let (digits, pm) = clock
7475        .strip_suffix("am")
7476        .map(|d| (d, false))
7477        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7478    let (h, m) = digits.trim().split_once(':')?;
7479    let mut hour: i8 = h.trim().parse().ok()?;
7480    let minute: i8 = m.trim().parse().ok()?;
7481    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7482        return None;
7483    }
7484    if pm && hour != 12 {
7485        hour += 12;
7486    } else if !pm && hour == 12 {
7487        hour = 0;
7488    }
7489    Some((hour, minute))
7490}
7491
7492/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
7493/// and a zone, never a date. A clock reading already past today is read as
7494/// tomorrow's: a CLI naming a same-day reset that has already gone by means
7495/// the window rolled over while nothing was watching.
7496fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7497    let open = text.find('(')?;
7498    let close = text.rfind(')')?;
7499    if close <= open {
7500        return None;
7501    }
7502    let zone = text[open + 1..close].trim();
7503    let (hour, minute) = parse_12h_clock(&text[..open])?;
7504    let tz = jiff::tz::TimeZone::get(zone).ok()?;
7505    let candidate = now
7506        .to_zoned(tz)
7507        .with()
7508        .hour(hour)
7509        .minute(minute)
7510        .second(0)
7511        .millisecond(0)
7512        .microsecond(0)
7513        .nanosecond(0)
7514        .build()
7515        .ok()?;
7516    let mut at = candidate.timestamp();
7517    if at <= now {
7518        at += jiff::SignedDuration::from_hours(24);
7519    }
7520    Some(at)
7521}
7522
7523/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
7524/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
7525/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
7526/// "already past today" correction to make: the year already disambiguates
7527/// it. Scanned as a five-word window so it can be pulled out of the middle
7528/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
7529/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
7530/// any other timestamp with no zone attached.
7531fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7532    let words: Vec<&str> = text.split_whitespace().collect();
7533    if words.len() < 5 {
7534        return None;
7535    }
7536    (0..=words.len() - 5)
7537        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7538}
7539
7540/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
7541/// parenthesis right after the window is refused rather than ignored — it
7542/// reads as an explicit zone annotation on a shape that otherwise carries
7543/// none, and guessing UTC anyway would be exactly the silent misread this
7544/// module's parsing otherwise avoids.
7545fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7546    if trailing.is_some_and(|next| next.starts_with('(')) {
7547        return None;
7548    }
7549    let month = month_number(window[0])?;
7550    let day_token = window[1].strip_suffix(',')?.to_lowercase();
7551    let day_digits = ["st", "nd", "rd", "th"]
7552        .iter()
7553        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7554    let day: i8 = day_digits.parse().ok()?;
7555    let year_token = window[2];
7556    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7557        return None;
7558    }
7559    let year: i16 = year_token.parse().ok()?;
7560    // The am/pm word carries the sentence's own trailing punctuation, e.g.
7561    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
7562    // reusing the same 12-hour clock reader the bracketed shape uses.
7563    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7564    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7565    let date = jiff::civil::Date::new(year, month, day).ok()?;
7566    let candidate = date
7567        .at(hour, minute, 0, 0)
7568        .to_zoned(jiff::tz::TimeZone::UTC)
7569        .ok()?;
7570    Some(candidate.timestamp())
7571}
7572
7573/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
7574/// case-insensitively, into a 1-based month number.
7575fn month_number(name: &str) -> Option<i8> {
7576    const NAMES: [&str; 12] = [
7577        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7578    ];
7579    let lower = name.to_lowercase();
7580    NAMES
7581        .iter()
7582        .position(|n| *n == lower.as_str())
7583        .map(|i| i as i8 + 1)
7584}
7585
7586/// Test probe for the shared resume policy's review-budget exclusion.
7587#[cfg(test)]
7588fn exhausted_review_budget(state: &RunState) -> bool {
7589    // A run whose task-head publication failed has nothing left to review:
7590    // resuming it only retries the publication, so it is never "exhausted".
7591    !crate::handover::can_resume(state)
7592        && state.status == RunStatus::Blocked
7593        && !state.released()
7594        && state.retired_to.is_none()
7595}
7596
7597/// This task's *most recent* run, if resuming it would actually make
7598/// progress. `short` is only for the warning's own message.
7599///
7600/// Only ever `runs.last()` — never a search back through older history.
7601/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
7602/// mint, oldest first, and every entry before the last one was already
7603/// superseded at the moment it was minted: the daemon only ever starts a new
7604/// run when the previous one was not worth resuming (unresumable, exhausted,
7605/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
7606/// opens a fresh review-only run alongside an older, already-failed
7607/// competition. Searching further back would let an old run that merely
7608/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
7609/// behind, say — get resumed instead of the fresh competition
7610/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
7611/// nothing asked to revisit.
7612///
7613/// Two runs paid for the "prefer resuming over restarting" half of this
7614/// lesson, which is why this still checks `runs.last()` rather than always
7615/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
7616/// task a moment later, duplicating two and a half hours of agent work. Then
7617/// b25f stalled on a judge that timed out and one that answered with no JSON
7618/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
7619/// **one second** later, buying three fresh implementations to reach the
7620/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
7621/// the second case: a stall is terminal, and its cheap recovery re-asks only
7622/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
7623/// that is technically `resumable()` but provably cannot progress must not
7624/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
7625/// no-op instead of the fresh competition it promises.
7626///
7627/// A load failure is warned about rather than silently read as "not
7628/// resumable": the alternative is exactly what let a schema mismatch on run
7629/// `eba2` fall through to a full re-competition with nobody told why.
7630/// `crate::conduct` is what actually offers a better answer than
7631/// `Runner::start` here (see `Recovery::Review`), once this task's next
7632/// failure shows it up as `held`/`failed` with the run state unreadable.
7633fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7634    unfinished_run_with(runs, short, RunState::load)
7635}
7636
7637/// [`unfinished_run`] with an injected state reader. Tests provide their
7638/// fixtures directly rather than touching the process-global run home.
7639pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7640where
7641    F: FnMut(&str) -> Result<RunState>,
7642{
7643    let mut id = runs.last()?.clone();
7644    let mut visited = std::collections::BTreeSet::new();
7645    let mut repo = None;
7646    loop {
7647        if !runs.contains(&id) || !visited.insert(id.clone()) {
7648            tracing::warn!("invalid or cyclic recovery authority for task {short}");
7649            return None;
7650        }
7651        let state = match load(&id) {
7652            Ok(state) if state.id == id => state,
7653            Ok(_) => return None,
7654            Err(e) => {
7655                tracing::warn!("could not read run {id} for task {short}: {e:#}");
7656                return None;
7657            }
7658        };
7659        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7660            return None;
7661        }
7662        repo = Some(state.repo.clone());
7663        if let Some(authority) = state.retired_to {
7664            id = authority;
7665            continue;
7666        }
7667        return (crate::handover::can_resume(&state)
7668            && state.liveness(false) != crate::run::Liveness::Live)
7669            .then_some(id);
7670    }
7671}
7672
7673/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
7674/// that [`attempt`] will resume it on its own?
7675///
7676/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
7677/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
7678/// injected reader like its sibling. An unreadable run is not awaiting
7679/// anything: it keeps going to the conductor as before.
7680fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7681where
7682    F: FnOnce(&str) -> Result<RunState>,
7683{
7684    // `Failed` stays: a record an older build wrote for a parked run.
7685    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7686        || task.fresh_start
7687        || task.review_branch.is_some()
7688    {
7689        return false;
7690    }
7691    let Some(id) = task.execution_runs().last() else {
7692        return false;
7693    };
7694    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7695}
7696
7697/// Which of the three ways [`attempt`] can mint or continue a run this task
7698/// should use.
7699#[derive(Debug, Clone, PartialEq, Eq)]
7700enum Starter {
7701    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
7702    /// and that still exists.
7703    Review(String),
7704    /// `crate::graph::Runner::resume` on an unfinished run of this task.
7705    Resume(String),
7706    /// `crate::graph::Runner::start`: a fresh competition.
7707    Start,
7708}
7709
7710fn load_retained_attempt(home: &Path, id: &str) -> Result<Option<RunState>> {
7711    match RunState::load_under(id, home) {
7712        Ok(state) => Ok(Some(state)),
7713        Err(error)
7714            if error
7715                .downcast_ref::<std::io::Error>()
7716                .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
7717                && !run_directory_present(&home.join("runs").join(id))? =>
7718        {
7719            Ok(None)
7720        }
7721        Err(error) => Err(error),
7722    }
7723}
7724
7725/// A second bound independent of inputs and the resettable failure counter.
7726/// Count execution and failed-startup recovery records once per run. Startup
7727/// failures can retain unrecorded preparation assets without an execution pass.
7728/// Unknown history is not evidence that a new set of worktrees is affordable.
7729fn retained_attempt_hold(
7730    task: &Task,
7731    starter: &Starter,
7732    limit: usize,
7733    mut load: impl FnMut(&str) -> Result<Option<RunState>>,
7734) -> Option<String> {
7735    if limit == 0 || matches!(starter, Starter::Resume(_)) {
7736        return None;
7737    }
7738    let mut retained = 0;
7739    for id in task
7740        .runs
7741        .iter()
7742        .chain(task.startup_failures.iter().map(|failure| &failure.run))
7743        .collect::<std::collections::BTreeSet<_>>()
7744    {
7745        let state = match load(id) {
7746            Ok(Some(state)) if state.id == *id => state,
7747            Ok(None)
7748                if !task
7749                    .startup_failures
7750                    .iter()
7751                    .any(|failure| failure.run == *id) =>
7752            {
7753                continue;
7754            }
7755            _ => {
7756                return Some(format!(
7757                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7758                ));
7759            }
7760        };
7761        if state.retired_to.is_some() || state.released() {
7762            continue;
7763        }
7764        // Neither a completed status nor an empty candidate array proves that
7765        // all recovery sources (including unrecorded preparation) were retired.
7766        retained += 1;
7767    }
7768    (retained >= limit).then(|| format!(
7769        "[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."
7770    ))
7771}
7772
7773/// A selected public implementation overrides every historical candidate and pin.
7774fn selected_starter(
7775    selected: &crate::pr_recovery::Selection,
7776    previous: Option<&RunState>,
7777    unfinished: Option<&str>,
7778) -> Starter {
7779    if let Some(id) = unfinished
7780        && previous.is_some_and(|r| {
7781            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7782        })
7783    {
7784        Starter::Resume(id.to_owned())
7785    } else {
7786        Starter::Review(selected.branch.clone())
7787    }
7788}
7789
7790/// The owner's answer to this branch's divergence question, consumed from the
7791/// task so a later, different divergence asks again. The runner applies it
7792/// (see `Runner::review_taking_over`), after the earlier worktree is released.
7793fn take_divergence_answer(
7794    branch: &str,
7795    remote: &str,
7796    task: &mut Task,
7797) -> Option<crate::reconcile::Choice> {
7798    let summary = crate::reconcile::summary_for(branch, remote);
7799    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7800        (a.question == summary)
7801            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7802            .flatten()
7803            .map(|c| (i, c))
7804    })?;
7805    task.answers.remove(idx);
7806    Some(choice)
7807}
7808
7809/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
7810/// this attempt should use. Pure, and separate from [`attempt`], so the
7811/// routing itself is assertable without spawning a real graph or a git
7812/// process: `attempt`'s own `crate::git::branch_exists` call has already
7813/// happened by the time this is called.
7814///
7815/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
7816/// whose branch is gone falls all the way through to [`Starter::Start`], not
7817/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
7818/// old (likely `Blocked`) run in the first place, and a branch that vanished
7819/// out from under that choice is not evidence resuming it would fare better.
7820fn choose_starter(
7821    review_branch: Option<&str>,
7822    branch_exists: bool,
7823    unfinished: Option<&str>,
7824) -> Starter {
7825    match review_branch {
7826        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7827        Some(_) => Starter::Start,
7828        None => match unfinished {
7829            Some(id) => Starter::Resume(id.to_owned()),
7830            None => Starter::Start,
7831        },
7832    }
7833}
7834
7835/// Reuse a compatible latest review owner instead of taking its checked-out
7836/// branch into a new run. Different branches and changed criteria still use
7837/// the ordinary review/takeover policy.
7838fn review_retry_starter(
7839    task: &Task,
7840    previous: Option<&RunState>,
7841    branch: Option<&str>,
7842    exists: bool,
7843    unfinished: Option<&str>,
7844) -> Starter {
7845    if let Some(run) = previous
7846        && unfinished == Some(run.id.as_str())
7847        && run.reviewed_commits.is_some()
7848        && branch.is_some_and(|branch| {
7849            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7850        })
7851        && may_resume_run(run, task)
7852    {
7853        return Starter::Resume(run.id.clone());
7854    }
7855    match (branch, unfinished, &task.review_of) {
7856        (None, None, Some(branch)) => Starter::Review(branch.clone()),
7857        _ => choose_starter(branch, exists, unfinished),
7858    }
7859}
7860
7861/// A retained review is valid only while its authored criteria still match.
7862fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7863    task.review_branch
7864        .as_deref()
7865        .filter(|&branch| match &task.review_instruction {
7866            Some(authored) => *authored == task.instruction,
7867            // Legacy retained branches must agree with their prior run; only an
7868            // explicitly pinned review can proceed without recoverable provenance.
7869            None => previous.map_or_else(
7870                || task.review_of.as_deref() == Some(branch),
7871                |run| compatible_run_instruction(run, task),
7872            ),
7873        })
7874}
7875
7876/// A current explicit pin can select an otherwise incompatible run. Edits
7877/// and subsequent approvals invalidate pins selected for earlier criteria.
7878fn may_resume_run(run: &RunState, task: &Task) -> bool {
7879    if !task.assignment_accepts(run) {
7880        return false;
7881    }
7882    task.resume_override
7883        .as_ref()
7884        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7885        || compatible_run_instruction(run, task)
7886}
7887
7888/// Review scaffolding is execution context, not evidence of an operator edit.
7889pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7890    if run.task_instruction_rev.unwrap_or(0) != task.instruction_rev {
7891        return false;
7892    }
7893    if let Some(authored) = &run.task_instruction {
7894        return compatible_instruction(authored, task);
7895    }
7896    if compatible_instruction(&run.instruction, task) {
7897        return true;
7898    }
7899    // Recognize only the existing generated review shapes on legacy runs.
7900    // Ordinary authored text with a similar heading is left intact.
7901    if run.reviewed_commits.is_some() {
7902        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7903            return strip_answers_block(authored, task).trim() == task.instruction.trim();
7904        }
7905        if let Some(branch) = &task.review_of {
7906            let canonical = format!(
7907                "Review the branch `{branch}` (review-only: no implementation, no judging)."
7908            );
7909            let generated = format!(
7910                "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"
7911            );
7912            return task.instruction == canonical && run.instruction.starts_with(&generated);
7913        }
7914    }
7915    false
7916}
7917
7918/// Compare authored instructions, excluding answer blocks appended by the daemon.
7919pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7920    strip_answers_block(old, task) == task.instruction
7921}
7922
7923/// Which repository a task runs in. A task that names none — the normal case
7924/// for one filed from a phone — runs in the daemon's own default.
7925fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7926    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7927        return fallback.to_path_buf();
7928    }
7929    task.repo.clone()
7930}
7931
7932/// The header [`append_answers`] appends operator answers under. Shared with
7933/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
7934/// rather than grown a new block on every resume.
7935const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7936
7937/// Render the first `count` answers in the block appended to an instruction.
7938fn answers_block(task: &Task, count: usize) -> String {
7939    let mut s = ANSWERS_HEADER.to_owned();
7940    for a in &task.answers[..count] {
7941        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7942    }
7943    s
7944}
7945
7946/// Render the approval independently of transient task state, so historical
7947/// suffixes remain recognizable after another explicit release.
7948fn resumption_block(r: &crate::queue::Resumption) -> String {
7949    format!(
7950        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7951         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7952        r.generation, r.at, r.instruction, r.answers_through,
7953    )
7954}
7955
7956/// Append audit answers and the latest explicit approval to the instruction.
7957fn append_answers(base: &str, task: &Task) -> String {
7958    let mut s = base.to_owned();
7959    if !task.answers.is_empty() {
7960        s.push_str(&answers_block(task, task.answers.len()));
7961    }
7962    if let Some(r) = &task.resumption {
7963        s.push_str(&resumption_block(r));
7964    }
7965    s
7966}
7967
7968/// Drop the prior answer block only when it is exactly the suffix this task
7969/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
7970/// the task author is ordinary instruction text, not a block to remove.
7971fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7972    let mut instruction = instruction;
7973    for approval in task
7974        .resumption
7975        .iter()
7976        .chain(task.resumption_history.iter().rev())
7977    {
7978        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7979            instruction = base;
7980            break;
7981        }
7982    }
7983    for count in (1..=task.answers.len()).rev() {
7984        let block = answers_block(task, count);
7985        if let Some(base) = instruction.strip_suffix(&block) {
7986            return base;
7987        }
7988    }
7989    instruction
7990}
7991
7992/// The instruction handed to `Runner::start`: the task's own text, plus any
7993/// operator answers `crate::conduct` collected for it (see
7994/// [`Task::answers`]), so a decision the operator actually made reaches the
7995/// implementers rather than only clearing the block that was waiting on it.
7996///
7997/// Appended rather than merged into [`Task::instruction`] itself, so the
7998/// task's own record stays exactly what its author wrote.
7999fn instruction_for(task: &Task) -> String {
8000    append_answers(&task.instruction, task)
8001}
8002
8003/// The instruction a resumed run should carry on with: whatever it already
8004/// had, refreshed with the task's *current* operator answers.
8005///
8006/// A resumable run's own `RunState::instruction` predates any answer
8007/// `crate::conduct` collects after the run parks, so resuming it unchanged —
8008/// the behaviour before this function existed — silently drops the very
8009/// decision the operator made to unblock it. Re-stripping any block this
8010/// function appended on an earlier resume before re-appending the current
8011/// list (rather than blindly appending again) is what keeps a task resumed
8012/// three times over three answered questions from carrying the same answer
8013/// three times.
8014fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
8015    append_answers(strip_answers_block(old_instruction, task), task)
8016}
8017
8018/// Preserve the producer's verified boundary and target, independent of prose.
8019fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
8020    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
8021    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
8022    if let Some(cause) = task.hold_notice_cause.as_mut() {
8023        cause.target = failure.map(|f| f.target.clone());
8024    }
8025}
8026
8027#[derive(Debug, thiserror::Error)]
8028#[error("attachment `{name}` is recorded on the task but {path} is missing")]
8029struct MissingAttachment {
8030    name: String,
8031    path: PathBuf,
8032}
8033
8034/// The task's attachments as absolute paths, each checked to still exist.
8035fn task_attachments(
8036    queue: &Queue,
8037    task: &Task,
8038) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
8039    let paths = queue.attachment_paths(task);
8040    for (name, path) in task.attachments.iter().zip(&paths) {
8041        if !path.is_file() {
8042            return Err(MissingAttachment {
8043                name: name.clone(),
8044                path: path.clone(),
8045            });
8046        }
8047    }
8048    Ok(paths)
8049}
8050
8051/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
8052/// answers before handing it to `Runner` — the actual boundary between
8053/// [`choose_starter`]'s routing and the graph, factored out so it is
8054/// assertable without a real repository, git branch, or agent CLI.
8055///
8056/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
8057/// instruction from the reviewed branch's own commit log because there is no
8058/// task statement to speak of for hand-written work, and splicing operator
8059/// answers into that text would contradict the very message it sends
8060/// reviewers ("there is no task statement").
8061fn prepare_instruction(
8062    starter: &Starter,
8063    old_instruction: Option<&str>,
8064    task: &Task,
8065) -> Option<String> {
8066    match starter {
8067        Starter::Start => Some(instruction_for(task)),
8068        Starter::Resume(_) => Some(resumed_instruction(
8069            old_instruction.expect("a resumed run always has a prior instruction"),
8070            task,
8071        )),
8072        Starter::Review(_) => None,
8073    }
8074}
8075
8076/// Persist a transition. A queue write failure is logged rather than fatal: the
8077/// run already happened, and taking the daemon down would only add a lost
8078/// backlog to a full disk.
8079fn record(queue: &Queue, task: &mut Task) {
8080    if let Err(e) = queue.put(task) {
8081        tracing::error!("could not record task {}: {e:#}", task.short());
8082        let notice = Notice::error(
8083            "loop:record",
8084            format!(
8085                "Task {} state could not be saved: {}. Check the disk.",
8086                task.id,
8087                e.to_string().lines().next().unwrap_or("unknown save error")
8088            ),
8089        )
8090        .link(Link::Task {
8091            id: task.id.clone(),
8092        });
8093        // The queue lives at `<home>/queue`, so its parent is the home.
8094        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
8095            Some(home) => notices::raise_in(home, notice),
8096            None => notices::raise(notice),
8097        }
8098    }
8099}
8100
8101/// Every runnable task, in the order the loop should try them.
8102///
8103/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
8104/// tail exists so that a claim somebody else holds costs the loop the next
8105/// candidate rather than a whole poll interval of idleness.
8106fn runnable(queue: &Queue) -> Vec<Task> {
8107    let mut tasks: Vec<Task> = queue
8108        .list()
8109        .into_iter()
8110        .filter(|t| t.status.runnable())
8111        .collect();
8112    tasks.sort_unstable_by(crate::queue::dispatch_order);
8113    tasks
8114}
8115
8116/// Why a run ended where it did, in one line, for [`Task::last_error`].
8117///
8118/// A stalled run names the seats the quota took out: "out of quota" is not
8119/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
8120/// agent to replace or which plan to top up.
8121///
8122/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
8123/// purpose: unlike `label`'s other callers (an internal log line, an
8124/// already-a-bug fallback message), this string becomes `Task::last_error`
8125/// verbatim, which the phone renders in the same alarm-styled box an
8126/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
8127/// `.err` styling. A bare `verified_noop` there would read exactly like the
8128/// failure this whole feature exists to tell apart from one.
8129fn describe(state: &RunState) -> String {
8130    let p = phrases(&state.config.graph.language);
8131    let mut detail = if state.status == RunStatus::Stalled {
8132        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
8133        seats.sort_unstable();
8134        seats.dedup();
8135        if seats.is_empty() {
8136            p.quorum_lost.to_owned()
8137        } else {
8138            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
8139        }
8140    } else {
8141        format!("{}{}", p.run_ended, state.status.display_label())
8142    };
8143    if let Some(cause) = state.verification_blocking_cause() {
8144        detail.push_str(&format!(" ({cause})"));
8145    } else if let Some(last) = state.events.last() {
8146        // The review loop's "never answered" stop is the one event worth
8147        // translating; it is recognised from structured state, not by
8148        // matching the English event text (which stays as recorded).
8149        let unanswered = state
8150            .reviews
8151            .last()
8152            .filter(|r| {
8153                state.status == RunStatus::Blocked
8154                    && last.node == "review"
8155                    && r.incomplete()
8156                    && r.blocking == 0
8157                    && r.round == state.config.graph.review_rounds
8158                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8159            })
8160            .map(|r| (r.expected - r.answered, r.round));
8161        match unanswered {
8162            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8163                detail.push_str(&format!(
8164                    " ({}: {})",
8165                    last.node,
8166                    (p.reviewers_never_answered)(missing, rounds)
8167                ));
8168            }
8169            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8170        }
8171    }
8172    detail.push_str(&format!(" [run {}]", state.id));
8173    detail
8174}
8175
8176/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
8177///
8178/// The task file lives in the backlog indefinitely; a diagnostic is an
8179/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
8180/// stay small regardless of how much a gate command or a candidate printed.
8181const DIAGNOSTIC_MAX: usize = 4_000;
8182
8183/// Tail kept from a single failing command's output inside a diagnostic.
8184/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
8185/// pointer for a human deciding whether to go read the full artifact by hand,
8186/// not a replacement for reading it.
8187const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8188
8189/// Assemble a bounded diagnostic excerpt from a held task's own run, so
8190/// `magi task show` says more than the one-line reason in [`describe`].
8191///
8192/// The one-liner answers "where did the run stop"; this answers "what would a
8193/// human have found opening `artifacts/` by hand" — the point of the whole
8194/// feature is the case that one-liner actively misleads on: a run held as "no
8195/// candidate produced a change" can mean the implementer actually finished
8196/// the task (opened a PR, merged it, tagged a release) and only left a clean
8197/// local worktree behind, which reads as "nothing happened" unless someone
8198/// goes and reads what the agent actually said. `None` when the run carries
8199/// none of the three shapes this recognises — an ordinary run held for
8200/// something not diagnosable from `RunState` alone still explains itself
8201/// through `Task::last_error`.
8202pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8203    diagnostic(state)
8204}
8205
8206fn diagnostic(state: &RunState) -> Option<String> {
8207    let mut parts: Vec<String> = Vec::new();
8208
8209    if let Some(e2e) = &state.head_e2e
8210        && !e2e.passed
8211    {
8212        for o in e2e
8213            .outcomes
8214            .iter()
8215            .filter(|o| !o.ok() && !o.resource_blocked)
8216        {
8217            parts.push(format!(
8218                "head_e2e `{}` failed on {} ({}):\n{}",
8219                o.command,
8220                e2e.head.chars().take(7).collect::<String>(),
8221                notices::exit_status(o.code),
8222                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8223            ));
8224        }
8225    }
8226
8227    // Gate failure: which check(s), and the tail of what each printed.
8228    for o in state.gate.iter().filter(|o| !o.ok()) {
8229        parts.push(format!(
8230            "gate `{}` failed ({}):\n{}",
8231            o.command,
8232            notices::exit_status(o.code),
8233            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8234        ));
8235    }
8236
8237    // The land loop gave up because the fixer declined while checks were
8238    // still red: the message already names them (see `land::run`).
8239    if let Some(last) = state
8240        .events
8241        .iter()
8242        .rev()
8243        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8244    {
8245        parts.push(last.message.clone());
8246    }
8247
8248    // No viable candidate: every implementer's own final word, sanitized the
8249    // same way a judge would have read it, so a run that actually finished
8250    // the job does not read as an unexplained failure. A verified no-op is
8251    // called out ahead of its own summary and apart from an ordinary
8252    // failure's `why` — this is the one candidate shape whose diagnostic a
8253    // human is expected to actually judge, not just skim.
8254    if state.viable().is_empty() {
8255        for c in &state.candidates {
8256            if c.has_valid_verified_noop()
8257                && let Some(evidence) = c.verified_noop_display()
8258            {
8259                parts.push(format!(
8260                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8261                    c.label
8262                ));
8263            } else if !c.summary.trim().is_empty() {
8264                if let Some(why) = &c.failed {
8265                    parts.push(format!(
8266                        "candidate {} ({why}): {}",
8267                        c.label,
8268                        c.summary.trim()
8269                    ));
8270                } else {
8271                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8272                }
8273            } else if let Some(why) = &c.failed {
8274                parts.push(format!("candidate {}: {why}", c.label));
8275            }
8276        }
8277    }
8278
8279    if parts.is_empty() {
8280        return None;
8281    }
8282    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
8283    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
8284    // back slightly over. Leave it enough room to always land under the
8285    // limit.
8286    Some(crate::run::tail(
8287        &parts.join("\n\n"),
8288        DIAGNOSTIC_MAX.saturating_sub(100),
8289    ))
8290}
8291
8292/// Stable lower-case name for a run status, for an internal log line and the
8293/// "graph stopped without reaching a terminal status" bug message in
8294/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
8295/// doc for why that one reads [`RunStatus::display_label`] instead. One
8296/// definition of a status's name, on the type that owns it: this table used
8297/// to live here as a second copy, and a status renamed in one place would
8298/// have gone on reading correctly in the other.
8299fn label(status: RunStatus) -> &'static str {
8300    status.as_str()
8301}
8302
8303/// Parse a merge mode override.
8304pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8305    match mode {
8306        "none" => Ok(MergeMode::None),
8307        "local" => Ok(MergeMode::Local),
8308        "pr" => Ok(MergeMode::Pr),
8309        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8310    }
8311}
8312
8313/// Take the status lock, recovering from a poisoned one.
8314///
8315/// A panic elsewhere must not silently stop the heartbeat: the status is plain
8316/// data, and the worst a poisoned lock can hold is a stale timestamp.
8317fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8318    mutex
8319        .lock()
8320        .unwrap_or_else(std::sync::PoisonError::into_inner)
8321}
8322
8323#[cfg(test)]
8324mod tests {
8325    use super::*;
8326    use crate::queue::{Source, TaskStatus};
8327    use crate::run::{Candidate, CommandOutcome};
8328    use pretty_assertions::assert_eq;
8329
8330    fn task() -> Task {
8331        Task::new(
8332            "add retries".to_owned(),
8333            "add retries".to_owned(),
8334            PathBuf::from("/repo"),
8335            Source::Human,
8336        )
8337    }
8338
8339    #[test]
8340    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8341        let skips = DispatchSkips::from([
8342            ("a".into(), SkipReason::CoolingDown),
8343            ("b".into(), SkipReason::WaitingOnLanding),
8344            ("c".into(), SkipReason::WaitingOnLanding),
8345            ("d".into(), SkipReason::OrdinaryCapacity),
8346        ]);
8347        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8348        assert_eq!(wait.runnable, 4);
8349        assert_eq!(
8350            wait.reasons
8351                .iter()
8352                .map(|r| (r.reason.as_str(), r.count))
8353                .collect::<Vec<_>>(),
8354            [
8355                ("waiting_on_landing", 2),
8356                ("cooling_down", 1),
8357                ("ordinary_capacity", 1)
8358            ]
8359        );
8360        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8361        assert!(
8362            aggregate_dispatch_wait(2, &DispatchSkips::new())
8363                .unwrap()
8364                .reasons
8365                .is_empty()
8366        );
8367    }
8368
8369    #[test]
8370    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8371        let before = vec!["a".into(), "b".into(), "c".into()];
8372        let allowed = vec![task_with_id("b")];
8373        let skips = interrupt_skips(&before, &allowed);
8374        assert_eq!(
8375            skips,
8376            DispatchSkips::from([
8377                ("a".into(), SkipReason::InterruptGate),
8378                ("c".into(), SkipReason::InterruptGate),
8379            ])
8380        );
8381        let mut previous = DispatchSkips::new();
8382        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8383        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8384        assert!(!changed_dispatch_skips(&mut previous, skips));
8385        assert!(changed_dispatch_skips(
8386            &mut previous,
8387            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8388        ));
8389        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8390    }
8391
8392    #[test]
8393    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8394        let mut value = serde_json::to_value(Status::new()).unwrap();
8395        value.as_object_mut().unwrap().remove("dispatch_wait");
8396        assert!(
8397            serde_json::from_value::<Status>(value.clone())
8398                .unwrap()
8399                .dispatch_wait
8400                .is_none()
8401        );
8402        assert!(
8403            serde_json::from_value::<Reading>(value.clone())
8404                .unwrap()
8405                .dispatch_wait
8406                .is_none()
8407        );
8408        value["dispatch_wait"] = serde_json::json!({
8409            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8410        });
8411        let reading = serde_json::from_value::<Reading>(value).unwrap();
8412        assert_eq!(
8413            reading.dispatch_wait.unwrap().reasons[0].reason,
8414            "future_reason"
8415        );
8416    }
8417
8418    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8419        let job = crate::worker::Job {
8420            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8421            sequence: 1,
8422            kind: "task".into(),
8423            key: format!("task:{}", request.task),
8424            payload: serde_json::to_value(request).unwrap(),
8425            generation: "a".repeat(64),
8426            version: None,
8427            status: crate::worker::Status::Starting,
8428            result: None,
8429            pid: None,
8430            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8431            finished_at: None,
8432        };
8433        let dir = home.join("workers/jobs").join(&job.id);
8434        std::fs::create_dir_all(&dir).unwrap();
8435        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8436        job
8437    }
8438
8439    #[test]
8440    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8441        let home = tempfile::tempdir().unwrap();
8442        let request = TaskWorker {
8443            opts: Opts::default(),
8444            queue: home.path().join("queue"),
8445            task: "startup".into(),
8446            lane: PermitKind::Ordinary,
8447            standalone: false,
8448        };
8449        let job = starting_task_reservation(home.path(), &request);
8450        let error = task_worker_spawn_error(
8451            home.path(),
8452            &request,
8453            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8454        )
8455        .expect_err("our own reservation must not turn a failed spawn into a resync");
8456        let active = crate::worker::active(home.path()).unwrap();
8457        assert_eq!(active.len(), 1);
8458        assert_eq!(active[0].id, job.id);
8459        assert_eq!(active[0].status, crate::worker::Status::Starting);
8460        assert!(
8461            crate::worker::control(home.path(), &job.key)
8462                .unwrap()
8463                .is_none()
8464        );
8465        let notices = notices::Notices::at(home.path().join("notifications")).list();
8466        assert_eq!(notices.len(), 1);
8467        assert_eq!(notices[0].key, "loop:worker-startup");
8468        assert!(!notices[0].message.contains("private-error-detail"));
8469        assert!(notices[0].message.contains(&request.task));
8470        assert!(
8471            notices[0]
8472                .message
8473                .contains("could not be started or acknowledged")
8474        );
8475        assert!(notices[0].message.contains("worker.log"));
8476        assert_eq!(
8477            notices[0].link,
8478            Some(Link::Task {
8479                id: request.task.clone()
8480            })
8481        );
8482        assert!(format!("{error:#}").contains("private-error-detail"));
8483    }
8484
8485    #[test]
8486    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8487        let home = tempfile::tempdir().unwrap();
8488        let mut request = TaskWorker {
8489            opts: Opts::default(),
8490            queue: home.path().join("queue"),
8491            task: "handoff".into(),
8492            lane: PermitKind::Ordinary,
8493            standalone: true,
8494        };
8495        let job = starting_task_reservation(home.path(), &request);
8496        request.standalone = false;
8497        task_worker_spawn_error(
8498            home.path(),
8499            &request,
8500            anyhow::anyhow!("operation key is already reserved for a different request"),
8501        )
8502        .expect("a different standalone request is the handoff race, not our startup failure");
8503        let active = crate::worker::active(home.path()).unwrap();
8504        assert_eq!(active.len(), 1);
8505        assert_eq!(active[0].id, job.id);
8506        assert_eq!(active[0].payload, job.payload);
8507        assert!(
8508            notices::Notices::at(home.path().join("notifications"))
8509                .list()
8510                .is_empty()
8511        );
8512    }
8513
8514    #[test]
8515    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8516        let home = tempfile::tempdir().unwrap();
8517        let queue = Queue::at(home.path().join("queue"));
8518        let mut task = task();
8519        task.runs = vec!["previous".into()];
8520        queue.put(&mut task).unwrap();
8521        let request = TaskWorker {
8522            opts: Opts::default(),
8523            queue: home.path().join("queue"),
8524            task: task.id.clone(),
8525            lane: PermitKind::Ordinary,
8526            standalone: false,
8527        };
8528        let job = starting_task_reservation(home.path(), &request);
8529        let claims = current_work(home.path(), Timestamp::now());
8530        assert_eq!(claims.len(), 1);
8531        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8532        assert_eq!(claims[0].run, "previous");
8533        assert!(other_claims_run(&claims, "previous", None));
8534        // Only after confirming the executing caller may admission ignore
8535        // this exact projection. Cleanup continues to observe it as live.
8536        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8537        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8538    }
8539
8540    #[test]
8541    fn admission_excludes_only_the_callers_exact_reservation() {
8542        let own = Current {
8543            worker: Some("own".into()),
8544            task: "same-task".into(),
8545            run: "previous".into(),
8546        };
8547        assert!(!other_claims_run(
8548            std::slice::from_ref(&own),
8549            "previous",
8550            Some("own")
8551        ));
8552        assert!(other_claims_run(
8553            std::slice::from_ref(&own),
8554            "previous",
8555            None
8556        ));
8557        for worker in [None, Some("other".into())] {
8558            let other = Current {
8559                worker,
8560                ..own.clone()
8561            };
8562            assert!(other_claims_run(
8563                &[own.clone(), other],
8564                "previous",
8565                Some("own")
8566            ));
8567        }
8568        let legacy: Current =
8569            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8570        assert!(other_claims_run(&[legacy], "previous", Some("own")));
8571    }
8572
8573    #[test]
8574    fn os_leased_task_worker_survives_wall_clock_advance() {
8575        let home = tempfile::tempdir().unwrap();
8576        let queue = Queue::at(home.path().join("queue"));
8577        let mut task = task();
8578        let run = "20260903-100000-abcd";
8579        task.start(run.into());
8580        queue.put(&mut task).unwrap();
8581        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8582        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8583        assert!(
8584            current_work(home.path(), future)
8585                .iter()
8586                .any(
8587                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8588                        && claim.run == run
8589                )
8590        );
8591        worker.release_lease();
8592        assert!(worker.dir.join("job.json").is_file());
8593        assert!(!is_working_on(home.path(), run, future));
8594        let dir = worker.dir.clone();
8595        drop(worker);
8596        assert!(!dir.exists());
8597    }
8598
8599    #[test]
8600    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8601        let mut task = task();
8602        let mut run = run_state(RunStatus::Reviewing);
8603        run.task_instruction = Some(task.instruction.clone());
8604        run.reviewed_commits = Some(vec!["committed-fix".into()]);
8605        let branch = "magi/test/B";
8606        run.candidates.push(crate::run::Candidate {
8607            branch: branch.into(),
8608            ..candidate('B', "preserved work", false, None)
8609        });
8610        task.runs = vec![run.id.clone()];
8611        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8612        assert_eq!(
8613            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8614            Starter::Resume(run.id.clone())
8615        );
8616        assert!(matches!(
8617            review_retry_starter(
8618                &task,
8619                Some(&run),
8620                Some("different"),
8621                true,
8622                unfinished.as_deref()
8623            ),
8624            Starter::Review(_)
8625        ));
8626        assert_eq!(
8627            review_retry_starter(
8628                &task,
8629                Some(&run),
8630                Some(branch),
8631                false,
8632                unfinished.as_deref()
8633            ),
8634            Starter::Start
8635        );
8636        task.instruction.push_str(" changed criteria");
8637        assert!(matches!(
8638            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8639            Starter::Review(_)
8640        ));
8641        assert!(matches!(
8642            review_retry_starter(&task, Some(&run), Some(branch), true, None),
8643            Starter::Review(_)
8644        ));
8645    }
8646
8647    #[test]
8648    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8649        let dir = tempfile::tempdir().unwrap();
8650        let queue = Queue::at(dir.path().join("queue"));
8651        let mut task = task();
8652        task.status = TaskStatus::Running;
8653        task.attempts = 1;
8654        queue.put(&mut task).unwrap();
8655        let live = std::collections::BTreeSet::from([task.id.clone()]);
8656        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8657        drop(queue.claim(&task.id).unwrap());
8658        let saved = queue.get(&task.id).unwrap();
8659        assert_eq!(saved.status, TaskStatus::Running);
8660        assert_eq!(saved.attempts, 1);
8661        assert!(saved.last_error.is_none());
8662    }
8663
8664    #[test]
8665    fn standalone_workers_do_not_consume_scheduler_lanes() {
8666        let request = |task: &str, lane, standalone| TaskWorker {
8667            opts: Opts::default(),
8668            queue: PathBuf::from("/queue"),
8669            task: task.to_owned(),
8670            lane,
8671            standalone,
8672        };
8673        let mut jobs = vec![
8674            request("ordinary", PermitKind::Ordinary, false),
8675            request("standalone-urgent", PermitKind::Urgent, true),
8676            request("standalone-ordinary", PermitKind::Ordinary, true),
8677            request("decision", PermitKind::None, false),
8678        ];
8679        assert_eq!(available_slots(&jobs, 2), (1, 1));
8680        jobs.push(request("urgent", PermitKind::Urgent, false));
8681        assert_eq!(available_slots(&jobs, 2), (1, 0));
8682        assert_eq!(available_slots(&jobs, 0), (0, 0));
8683    }
8684
8685    #[test]
8686    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8687        let now = Timestamp::now();
8688        let mut reading = Reading {
8689            pid: Some(std::process::id()),
8690            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8691            ..Reading::default()
8692        };
8693        assert!(!reading.running(now));
8694        assert!(legacy_scheduler_running(&reading, now, 0));
8695        reading.worker_protocol = Some(1);
8696        assert!(!legacy_scheduler_running(&reading, now, 0));
8697    }
8698
8699    #[test]
8700    fn selected_public_head_overrides_historical_resume_and_pin() {
8701        let mut t = task();
8702        let mut old = run_state(RunStatus::Blocked);
8703        let selection = crate::pr_recovery::Selection {
8704            url: "url".into(),
8705            branch: format!("magi/task-{}", t.id),
8706            head: "a".repeat(40),
8707            source_head: None,
8708            source_run: None,
8709            source_proof: None,
8710            disposition: Some(crate::pr_recovery::Disposition::Review),
8711            instruction: t.instruction.clone(),
8712            approved_at: Timestamp::now(),
8713        };
8714        t.resume_override = Some(crate::queue::OperatorResume {
8715            pinned_run: Some(old.id.clone()),
8716            question_id: "choice".into(),
8717            at: Timestamp::now(),
8718            conductor_rehold: None,
8719            forced: false,
8720        });
8721        assert_eq!(
8722            selected_starter(&selection, Some(&old), Some(&old.id)),
8723            Starter::Review(selection.branch.clone())
8724        );
8725        old.pr_recovery = Some(selection.clone());
8726        assert_eq!(
8727            selected_starter(&selection, Some(&old), Some(&old.id)),
8728            Starter::Review(selection.branch.clone())
8729        );
8730        old.reviewed_commits = Some(vec!["implementation".into()]);
8731        assert_eq!(
8732            selected_starter(&selection, Some(&old), Some(&old.id)),
8733            Starter::Resume(old.id.clone())
8734        );
8735        let mut changed = selection.clone();
8736        changed.head = "b".repeat(40);
8737        assert_eq!(
8738            selected_starter(&changed, Some(&old), Some(&old.id)),
8739            Starter::Review(changed.branch)
8740        );
8741    }
8742
8743    #[test]
8744    fn candidate_transplant_failure_is_one_actionable_hold() {
8745        let dir = tempfile::tempdir().unwrap();
8746        let q = Queue::at(dir.path().join("queue"));
8747        let mut t = task();
8748        let mut state = run_state(RunStatus::Blocked);
8749        state.event("prep", "cannot apply referenced commit: conflict");
8750        state.prep_failure = Some("conflict".into());
8751        t.start(state.id.clone());
8752        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8753        assert_eq!(t.attempts, 1);
8754        assert_eq!(t.status, TaskStatus::Held);
8755        assert!(t.operator_held());
8756        assert!(!t.status.runnable());
8757        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8758        let first = t.chat_notice_key().unwrap();
8759        t.chat_notices.push(first.clone());
8760        t.release_operator("test", None);
8761        state.id = "another-unprepared-run".into();
8762        t.start(state.id.clone());
8763        finish_attempt(
8764            3,
8765            &q,
8766            &mut t,
8767            &state,
8768            &[],
8769            Err(anyhow::anyhow!("still conflicts")),
8770        );
8771        assert_eq!(
8772            t.chat_notice_key().as_ref(),
8773            Some(&first),
8774            "no work happened"
8775        );
8776        t.release_operator("test", None);
8777        state.prep_failure = None;
8778        state.status = RunStatus::Failed;
8779        state.begin_pass();
8780        t.start(state.id.clone());
8781        finish_attempt(
8782            1,
8783            &q,
8784            &mut t,
8785            &state,
8786            &[],
8787            Err(anyhow::anyhow!("new gate failure")),
8788        );
8789        let failure = t.chat_notice_key().unwrap();
8790        assert_ne!(failure, first, "approved recovery reached a real failure");
8791        t.release_operator("test", None);
8792        state.begin_pass();
8793        t.start(state.id.clone());
8794        finish_attempt(
8795            1,
8796            &q,
8797            &mut t,
8798            &state,
8799            &[],
8800            Err(anyhow::anyhow!("new failure on resume")),
8801        );
8802        assert_ne!(
8803            t.chat_notice_key().as_ref(),
8804            Some(&failure),
8805            "a new settled pass"
8806        );
8807    }
8808
8809    #[test]
8810    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8811        for source in ["cli", "web"] {
8812            let mut t = task();
8813            let mut run = run_state(RunStatus::Blocked);
8814            run.instruction = "Run A original criteria".into();
8815            run.task_instruction = Some(run.instruction.clone());
8816            t.start(run.id.clone());
8817            t.release_operator("choice", Some("resume-question"));
8818            t.resume_override = Some(crate::queue::OperatorResume {
8819                question_id: "resume-question".into(),
8820                at: Timestamp::now(),
8821                conductor_rehold: None,
8822                forced: true,
8823                pinned_run: Some(run.id.clone()),
8824            });
8825            t.hold_machine(Some("not enough free space to start a run".into()));
8826            let mut unchanged = t.clone();
8827            unchanged
8828                .edit("title changed".into(), unchanged.instruction.clone())
8829                .unwrap();
8830            unchanged.release_operator(source, None);
8831            assert_eq!(
8832                unchanged
8833                    .resume_override
8834                    .as_ref()
8835                    .unwrap()
8836                    .pinned_run
8837                    .as_deref(),
8838                Some(run.id.as_str())
8839            );
8840            assert!(!compatible_run_instruction(&run, &unchanged));
8841            assert!(may_resume_run(&run, &unchanged));
8842
8843            t.edit(
8844                "approved recovery".into(),
8845                "Reuse measured PR head B; fix Clippy; review".into(),
8846            )
8847            .unwrap();
8848            assert!(t.resume_override.is_none());
8849            t.release_operator(source, None);
8850            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8851            assert!(reloaded.resume_override.is_none());
8852            assert!(!may_resume_run(&run, &reloaded));
8853            let unfinished =
8854                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8855                    .filter(|_| may_resume_run(&run, &reloaded));
8856            assert_eq!(
8857                choose_starter(None, false, unfinished.as_deref()),
8858                Starter::Start
8859            );
8860            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8861            assert_eq!(
8862                reloaded.resumption_history[0].question_id.as_deref(),
8863                Some("resume-question")
8864            );
8865
8866            // A revision already persisted with the old approval/pin is also
8867            // invalidated when the new operator release is recorded.
8868            unchanged.instruction = "Reuse measured PR head B".into();
8869            unchanged.hold_machine(Some("disk hold".into()));
8870            unchanged.release_operator(source, None);
8871            assert!(unchanged.resume_override.is_none());
8872            assert!(!may_resume_run(&run, &unchanged));
8873        }
8874    }
8875
8876    #[test]
8877    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8878        let mut t = task();
8879        let mut run = run_state(RunStatus::Blocked);
8880        t.review_of = Some("approved-head".into());
8881        t.instruction =
8882            "Review the branch `approved-head` (review-only: no implementation, no judging)."
8883                .into();
8884        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();
8885        run.reviewed_commits = Some(vec!["Commit log".into()]);
8886        t.start(run.id.clone());
8887        t.hold_machine(Some("interrupted review".into()));
8888        t.release_operator("cli", None);
8889        assert!(
8890            compatible_run_instruction(&run, &t),
8891            "legacy explicit review remains resumable"
8892        );
8893        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8894            .filter(|_| compatible_run_instruction(&run, &t));
8895        assert_eq!(
8896            choose_starter(None, false, unfinished.as_deref()),
8897            Starter::Resume(run.id.clone())
8898        );
8899        run.task_instruction = Some(t.instruction.clone());
8900        assert!(compatible_run_instruction(&run, &t));
8901        let reloaded: RunState =
8902            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8903        assert!(compatible_run_instruction(&reloaded, &t));
8904        t.edit(
8905            "new approved head".into(),
8906            "Reuse measured PR head B".into(),
8907        )
8908        .unwrap();
8909        assert!(!compatible_run_instruction(&run, &t));
8910
8911        // Legacy recovery reviews retain the task criteria ahead of the log.
8912        t.review_of = None;
8913        t.instruction = "Fix Clippy on approved head".into();
8914        run.task_instruction = None;
8915        run.task_instruction_rev = Some(t.instruction_rev);
8916        run.instruction = format!(
8917            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8918            t.instruction
8919        );
8920        assert!(compatible_run_instruction(&run, &t));
8921        t.instruction.push('\n');
8922        assert!(
8923            compatible_run_instruction(&run, &t),
8924            "legacy generated review trimmed the original criteria"
8925        );
8926        t.hold_for_handover(Some("approved-head".into()), "refused".into());
8927        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8928        t.edit("new plan".into(), "Reuse measured PR head B".into())
8929            .unwrap();
8930        assert!(review_branch_for(&t, Some(&run)).is_none());
8931        assert!(!compatible_run_instruction(&run, &t));
8932        t.review_branch = Some("approved-head".into());
8933        t.review_instruction = None;
8934        assert!(
8935            review_branch_for(&t, Some(&run)).is_none(),
8936            "legacy retained candidate cannot replace a revised approved head"
8937        );
8938    }
8939
8940    #[test]
8941    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8942        let home = crate::run::test_home();
8943        crate::run::pin_test_home();
8944        let dir = tempfile::tempdir().unwrap();
8945        let queue = Queue::at(dir.path().join("queue"));
8946        for resume in [true, false] {
8947            let state = run_state(RunStatus::Blocked);
8948            let mut t = task();
8949            t.start(state.id.clone());
8950            let action = if resume {
8951                ask::ChoiceAction::Resume {
8952                    run: state.id.clone(),
8953                }
8954            } else {
8955                ask::ChoiceAction::Requeue
8956            };
8957            let mut q = action_question(&state.id, action);
8958            q.status = ask::QuestionStatus::Open;
8959            q.answer = None;
8960            q.answered_at = None;
8961            t.fail("run stopped with a question", 3);
8962            hold_if_runnable(&queue, &mut t);
8963            assert!(t.operator_decided_at.is_none());
8964            assert!(t.operator_held());
8965            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8966            let expected = if resume {
8967                ActionDecision::Resume(state.id.clone())
8968            } else {
8969                ActionDecision::Requeue
8970            };
8971            assert_eq!(
8972                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8973                expected
8974            );
8975            t.hold_manual(Some("later explicit hold".into()));
8976            assert_eq!(
8977                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8978                ActionDecision::Stale
8979            );
8980        }
8981    }
8982
8983    #[test]
8984    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8985        let mut t = task();
8986        t.answers.push(crate::queue::AnsweredQuestion {
8987            question: "Inspect the remote?".into(),
8988            answer: "Inspect then wait".into(),
8989        });
8990        let old = instruction_for(&t);
8991        assert!(compatible_instruction(&old, &t));
8992        t.instruction = "Reuse approved PR head and review".into();
8993        t.release_operator("cli", None);
8994        assert!(!compatible_instruction(&old, &t));
8995        let approved = instruction_for(&t);
8996        assert!(approved.contains("waiting premises are superseded"));
8997        assert!(compatible_instruction(&approved, &t));
8998        assert_eq!(resumed_instruction(&approved, &t), approved);
8999        t.release_operator("web", None);
9000        assert!(compatible_instruction(&approved, &t));
9001        assert_eq!(t.resumption_history.len(), 1);
9002        t.start("run".into());
9003        assert!(instruction_for(&t).contains("Explicit operator resumption"));
9004    }
9005
9006    /// A run that stopped on an infrastructure wait asked no agent anything:
9007    /// the task is held by the machine under a `[resource]` reason (resumable,
9008    /// re-checked by triage), and the attempt it started is given back.
9009    #[test]
9010    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
9011        let mut state = RunState::new(
9012            PathBuf::from("/repo"),
9013            "main".into(),
9014            "base".into(),
9015            "task".into(),
9016            Config::default(),
9017        );
9018        state.status = RunStatus::Landing;
9019        state.parked = true;
9020        state.pr_pushed_head = Some("head".into());
9021        state.land_unrelated = Some(
9022            serde_json::from_value(serde_json::json!({
9023                "head": "head", "question": "ci-question",
9024                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
9025            }))
9026            .unwrap(),
9027        );
9028        let mut t = task();
9029        t.start(state.id.clone());
9030        let verdict = Verdict {
9031            status: RunStatus::Landing,
9032            left_pr: true,
9033            quota_hit: false,
9034            parked: true,
9035            no_viable_candidates: false,
9036        };
9037        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
9038        assert_eq!(t.attempts, 0);
9039        assert_eq!(t.status, TaskStatus::Held);
9040        assert!(!t.operator_held());
9041        assert!(
9042            t.hold_reason
9043                .as_deref()
9044                .unwrap()
9045                .starts_with("[ci-unrelated]")
9046        );
9047        // A second settlement must not refund an earlier task attempt.
9048        t.attempts = 1;
9049        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
9050        assert_eq!(t.attempts, 1);
9051        assert_eq!(t.passes.len(), 1);
9052        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9053        state.pr_pushed_head = Some("new-head".into());
9054        state.parked = false;
9055        state.status = RunStatus::Blocked;
9056        let stale = Verdict {
9057            status: RunStatus::Blocked,
9058            parked: false,
9059            ..verdict
9060        };
9061        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
9062        assert_eq!(t.attempts, 1);
9063        // A new execution pass can refund its own newly charged attempt.
9064        state.begin_pass();
9065        state.begin_pass();
9066        state.status = RunStatus::Landing;
9067        state.parked = true;
9068        state.pr_pushed_head = Some("head".into());
9069        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
9070        assert_eq!(t.attempts, 0);
9071        assert_eq!(t.passes.len(), 2);
9072    }
9073
9074    #[test]
9075    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
9076        let mut state = run_state(RunStatus::Failed);
9077        state
9078            .quota
9079            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
9080        state.begin_pass();
9081        let mut t = task();
9082        t.start(state.id.clone());
9083        reclaim(&mut t, Some(state), 2, "en");
9084        assert_eq!(t.attempts, 1);
9085    }
9086
9087    #[test]
9088    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
9089        let mut state = run_state(RunStatus::Blocked);
9090        let losses: Vec<_> = ["alpha", "beta"]
9091            .into_iter()
9092            .enumerate()
9093            .map(|(i, agent)| {
9094                QuotaLoss::from_report(
9095                    format!("advisor-{i}"),
9096                    "advise",
9097                    Some(&crate::agent::Quota {
9098                        cause: crate::agent::QuotaCause::Authentication,
9099                        agent: agent.to_owned(),
9100                        reset: None,
9101                    }),
9102                )
9103            })
9104            .collect();
9105        crate::graph::block_machine_outage(&mut state, "advise", &losses);
9106        state.quota = losses;
9107        let mut t = task();
9108        t.start(state.id.clone());
9109        let verdict = Verdict {
9110            status: state.status,
9111            left_pr: false,
9112            quota_hit: true,
9113            parked: false,
9114            no_viable_candidates: true,
9115        };
9116        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
9117        assert_eq!(t.attempts, 0);
9118        assert_eq!(t.status, TaskStatus::Held);
9119        assert!(!t.operator_held());
9120        let reason = t.hold_reason.as_deref().unwrap();
9121        assert!(reason.starts_with("[authentication]"));
9122        assert!(
9123            reason.contains("alpha")
9124                && reason.contains("beta")
9125                && reason.contains("re-authenticate")
9126        );
9127        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
9128        // Orphan recovery uses the same settlement and cannot spend an attempt.
9129        let mut orphan = task();
9130        orphan.start(state.id.clone());
9131        reclaim(&mut orphan, Some(state), 2, "en");
9132        assert_eq!(orphan.attempts, 0);
9133        assert_eq!(orphan.status, TaskStatus::Held);
9134    }
9135
9136    #[test]
9137    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
9138        let mut state = RunState::new(
9139            PathBuf::from("/repo"),
9140            "main".to_owned(),
9141            "abc1234".to_owned(),
9142            "task".to_owned(),
9143            Config::default(),
9144        );
9145        state.status = RunStatus::Blocked;
9146        state.resource_block = Some(crate::run::ResourceBlock {
9147            cause: crate::run::ResourceBlockCause::Other,
9148            node: "graft".to_owned(),
9149            kind: "shared build cache".to_owned(),
9150            detail: "timed out".to_owned(),
9151            at: jiff::Timestamp::now(),
9152        });
9153        let mut t = task();
9154        t.start("20260902-000000-aaaa".to_owned());
9155        assert_eq!(t.attempts, 1);
9156        let verdict = Verdict {
9157            status: RunStatus::Blocked,
9158            left_pr: false,
9159            quota_hit: false,
9160            parked: false,
9161            no_viable_candidates: false,
9162        };
9163        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9164        assert_eq!(t.status, TaskStatus::Held);
9165        assert_eq!(t.attempts, 0, "the attempt is refunded");
9166        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9167        assert!(
9168            !t.operator_held(),
9169            "a machine hold, released without a human"
9170        );
9171
9172        let mut selected = task();
9173        selected.start("20260902-000000-cccc".into());
9174        selected.replacement = Some(crate::merge_decision::Replacement {
9175            question: "fixture".into(),
9176            run: "earlier".into(),
9177            pr: "https://example.invalid/pr/1".into(),
9178            agent: "selected".into(),
9179            context: "fixture".into(),
9180        });
9181        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9182        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9183        assert_eq!(selected.attempts, 0);
9184        assert!(
9185            !selected.operator_held(),
9186            "a selected agent also retains a machine resource hold"
9187        );
9188        assert!(
9189            selected
9190                .hold_reason
9191                .as_deref()
9192                .unwrap()
9193                .starts_with("[resource] ")
9194        );
9195
9196        // A park request outranks it: still the operator's doing.
9197        let mut p = task();
9198        p.start("20260902-000000-bbbb".to_owned());
9199        settle_and_diagnose(
9200            &mut p,
9201            Verdict {
9202                parked: true,
9203                ..verdict
9204            },
9205            "parked",
9206            2,
9207            &state,
9208        );
9209        assert_eq!(p.status, TaskStatus::Parked);
9210        assert_eq!(
9211            p.attempts, 0,
9212            "parking refunds once rather than also settling the resource hold"
9213        );
9214    }
9215
9216    #[test]
9217    fn record_failure_notice_links_the_task() {
9218        let dir = tempfile::tempdir().unwrap();
9219        // A regular file where the queue directory should be makes every
9220        // `put` fail, on every platform and whoever runs the test.
9221        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9222        let queue = Queue::at(dir.path().join("queue"));
9223        let mut t = interrupt_task("rec-fail-1");
9224        record(&queue, &mut t);
9225
9226        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9227        assert_eq!(found.len(), 1);
9228        assert_eq!(found[0].key, "loop:record");
9229        assert_eq!(
9230            found[0].link,
9231            Some(Link::Task {
9232                id: "rec-fail-1".to_owned()
9233            })
9234        );
9235    }
9236
9237    /// A runnable task marked to interrupt, with an id fixed for assertions
9238    /// rather than the random one [`Task::new`] mints.
9239    fn interrupt_task(id: &str) -> Task {
9240        let mut t = task();
9241        t.id = id.to_owned();
9242        t.interrupt = true;
9243        t
9244    }
9245
9246    /// An ordinary runnable task with an id fixed for assertions.
9247    fn task_with_id(id: &str) -> Task {
9248        let mut t = task();
9249        t.id = id.to_owned();
9250        t
9251    }
9252
9253    /// A runnable task marked `--urgent`, with an id fixed for assertions.
9254    fn urgent_task(id: &str) -> Task {
9255        let mut t = task();
9256        t.id = id.to_owned();
9257        t.urgent = true;
9258        t
9259    }
9260
9261    #[test]
9262    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9263        let dir = tempfile::tempdir().unwrap();
9264        let queue = Queue::at(dir.path().join("queue"));
9265        let mut parked = task_with_id("parked");
9266        parked.start("run".into());
9267        parked.park("upgrade");
9268        parked.record_pass_at(
9269            "run",
9270            0,
9271            Some(Timestamp::now()),
9272            1,
9273            Some(crate::run::ParkCause::Upgrade {
9274                from: "old".into(),
9275                to: None,
9276            }),
9277        );
9278        let mut fresh = task_with_id("fresh");
9279        fresh.priority = 100;
9280        let mut urgent_task = urgent_task("urgent");
9281        for t in [&mut parked, &mut fresh, &mut urgent_task] {
9282            queue.put(t).unwrap();
9283        }
9284        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9285        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9286        let candidates = runnable(&queue);
9287        assert_eq!(candidates[0].id, parked.id);
9288        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9289        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9290        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9291        drop(first);
9292        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9293        let next = runnable(&queue)
9294            .into_iter()
9295            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9296            .unwrap();
9297        assert_eq!(next.task.id, fresh.id);
9298        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9299        drop(claimed_elsewhere);
9300        drop(next);
9301        assert!(matches!(
9302            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9303            Err(SkipReason::CoolingDown)
9304        ));
9305    }
9306
9307    #[test]
9308    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9309        let dir = tempfile::tempdir().unwrap();
9310        let queue = Queue::at(dir.path().join("queue"));
9311        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9312        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9313        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9314        let mut first = task();
9315        queue.put(&mut first).unwrap();
9316        let stale_plain = queue.get(&first.id).unwrap();
9317        first.set_urgent(true).unwrap();
9318        queue.put(&mut first).unwrap();
9319        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9320        let mut second = urgent_task("second");
9321        queue.put(&mut second).unwrap();
9322        assert!(matches!(
9323            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9324            Err(SkipReason::UrgentCapacity)
9325        ));
9326        drop(queue.claim(&second.id).unwrap());
9327        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9328        drop(dispatched);
9329        let stale_urgent = queue.get(&first.id).unwrap();
9330        first.set_urgent(false).unwrap();
9331        queue.put(&mut first).unwrap();
9332        assert!(matches!(
9333            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9334            Err(SkipReason::OrdinaryCapacity)
9335        ));
9336        assert_eq!(urgent.available_permits(), 1);
9337        drop(queue.claim(&first.id).unwrap());
9338        drop(occupied);
9339    }
9340
9341    #[test]
9342    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9343        let dir = tempfile::tempdir().unwrap();
9344        let queue = Queue::at(dir.path().join("queue"));
9345        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9346        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9347        let mut t = task();
9348        queue.put(&mut t).unwrap();
9349        for enabled in [true, false] {
9350            let stale = queue.get(&t.id).unwrap();
9351            t.set_urgent(enabled).unwrap();
9352            queue.put(&mut t).unwrap();
9353            assert_ne!(stale.urgent, enabled);
9354            let DispatchClaim {
9355                task: fresh,
9356                claim,
9357                lane,
9358                permit,
9359            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9360            assert_eq!(fresh.urgent, enabled);
9361            assert_eq!(
9362                lane,
9363                if enabled {
9364                    PermitKind::Urgent
9365                } else {
9366                    PermitKind::Ordinary
9367                }
9368            );
9369            assert_eq!(ordinary.available_permits(), usize::from(enabled));
9370            assert_eq!(urgent.available_permits(), usize::from(!enabled));
9371            assert!(queue.claim(&t.id).is_err());
9372            assert_eq!(fresh.attempts, stale.attempts);
9373            drop((claim, permit));
9374            assert_eq!(ordinary.available_permits(), 1);
9375            assert_eq!(urgent.available_permits(), 1);
9376        }
9377        t.set_urgent(true).unwrap();
9378        queue.put(&mut t).unwrap();
9379        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9380        assert!(matches!(
9381            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9382            Err(SkipReason::UrgentCapacity)
9383        ));
9384        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9385        drop(queue.claim(&t.id).unwrap());
9386        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9387        drop(occupied);
9388        assert!(matches!(
9389            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9390            Err(SkipReason::CoolingDown)
9391        ));
9392        drop(queue.claim(&t.id).unwrap());
9393        let held = queue.claim(&t.id).unwrap();
9394        assert!(matches!(
9395            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9396            Err(SkipReason::ClaimUnavailable)
9397        ));
9398        drop(held);
9399        t.status = TaskStatus::Held;
9400        queue.put(&mut t).unwrap();
9401        assert!(matches!(
9402            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9403            Err(SkipReason::NoLongerRunnable)
9404        ));
9405        drop(queue.claim(&t.id).unwrap());
9406        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9407        assert!(matches!(
9408            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9409            Err(SkipReason::RereadFailed)
9410        ));
9411        drop(queue.claim(&t.id).unwrap());
9412        assert_eq!(urgent.available_permits(), 1);
9413    }
9414
9415    /// The land-resume exemption wins outright, whether or not the candidate
9416    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
9417    /// queue behind anything" guarantee cannot be weaker just because the
9418    /// same task was also filed with `--urgent`.
9419    #[test]
9420    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9421        assert_eq!(permit_kind(true, false, false), PermitKind::None);
9422        assert_eq!(permit_kind(true, false, true), PermitKind::None);
9423        assert_eq!(permit_kind(true, true, false), PermitKind::None);
9424        assert_eq!(permit_kind(true, true, true), PermitKind::None);
9425    }
9426
9427    /// The one property this whole feature exists for: `--urgent` draws from
9428    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
9429    /// ordinary candidate draws from the ordinary pool exactly as before,
9430    /// untouched by the urgent slot's existence.
9431    #[test]
9432    fn permit_kind_separates_urgent_from_ordinary() {
9433        assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9434        assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9435        assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9436        assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9437    }
9438
9439    #[test]
9440    fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9441        let request = |task: &str, lane, standalone| TaskWorker {
9442            opts: Opts::default(),
9443            queue: PathBuf::from("/queue"),
9444            task: task.to_owned(),
9445            lane,
9446            standalone,
9447        };
9448        let jobs = vec![
9449            request("ordinary", PermitKind::Ordinary, false),
9450            request("urgent", PermitKind::Urgent, false),
9451            request("immediate-1", PermitKind::Immediate, false),
9452            request("immediate-2", PermitKind::Immediate, false),
9453            request("decision", PermitKind::None, false),
9454        ];
9455        assert_eq!(available_slots(&jobs, 1), (0, 0));
9456        assert_eq!(available_slots(&jobs, 2), (1, 0));
9457        let immediate_only = vec![
9458            request("immediate-1", PermitKind::Immediate, false),
9459            request("immediate-2", PermitKind::Immediate, false),
9460        ];
9461        assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9462    }
9463
9464    #[test]
9465    fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9466        let dir = tempfile::tempdir().unwrap();
9467        let queue = Queue::at(dir.path().join("queue"));
9468        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9469        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9470        let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9471        let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9472
9473        // Both ordinary and urgent lanes are saturated.
9474        let mut imm1 = task_with_id("imm-1");
9475        imm1.immediate = true;
9476        let mut imm2 = task_with_id("imm-2");
9477        imm2.immediate = true;
9478        imm2.urgent = true;
9479        queue.put(&mut imm1).unwrap();
9480        queue.put(&mut imm2).unwrap();
9481
9482        // Stale non-immediate listing still picks up saved immediate under claim.
9483        let mut stale = imm1.clone();
9484        stale.immediate = false;
9485        let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9486        assert_eq!(claim1.lane, PermitKind::Immediate);
9487        assert!(claim1.permit.is_none());
9488
9489        // Multiple immediate tasks can claim simultaneously without touching semaphores.
9490        let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9491        assert_eq!(claim2.lane, PermitKind::Immediate);
9492        assert!(claim2.permit.is_none());
9493        assert_eq!(ordinary.available_permits(), 0);
9494        assert_eq!(urgent.available_permits(), 0);
9495
9496        // Duplicate claim on an already-claimed immediate task is refused.
9497        assert_eq!(
9498            claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9499            Some(SkipReason::ClaimUnavailable)
9500        );
9501        drop((claim1, claim2));
9502
9503        // Cooldown still blocks immediate tasks.
9504        assert_eq!(
9505            claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9506            Some(SkipReason::CoolingDown)
9507        );
9508
9509        // Clearing immediate while urgent remains true reverts to urgent lane.
9510        imm2.set_immediate(false).unwrap();
9511        queue.put(&mut imm2).unwrap();
9512        assert_eq!(
9513            claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9514            Some(SkipReason::UrgentCapacity)
9515        );
9516
9517        // Interrupt gate still withholds immediate candidates.
9518        let interrupt = Interrupt::Parking {
9519            parked: vec!["in-flight".into()],
9520            interrupt_task: "other".into(),
9521        };
9522        assert!(
9523            interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9524            "an active interrupt sequence must withhold immediate tasks too"
9525        );
9526    }
9527
9528    #[test]
9529    fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9530        let dir = tempfile::tempdir().unwrap();
9531        let home = dir.path();
9532        let queue = Queue::at(home.join("queue"));
9533        let now = Timestamp::now();
9534
9535        let mut imm = task_with_id("imm-ready");
9536        imm.immediate = true;
9537        queue.put(&mut imm).unwrap();
9538
9539        // No scheduler running -> waiting, never "next poll".
9540        let snap = AdmissionSnapshot::capture(home, now);
9541        let adm = snap.evaluate(&imm, &queue, None, home);
9542        assert_eq!(adm.mode, "immediate");
9543        assert_eq!(adm.state, "waiting");
9544        assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9545
9546        // Live scheduler + saturated ordinary/urgent workers + stale capacity skip -> next poll!
9547        let mut status = Status::new();
9548        status.updated_at = now;
9549        status
9550            .dispatch_skips
9551            .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9552        write_status_to(&home.join("daemon.json"), &status).unwrap();
9553
9554        let mut ord = task_with_id("ord-running");
9555        ord.status = TaskStatus::Running;
9556        queue.put(&mut ord).unwrap();
9557        let ord_req = TaskWorker {
9558            opts: Opts::default(),
9559            queue: queue.root().to_path_buf(),
9560            task: ord.id.clone(),
9561            lane: PermitKind::Ordinary,
9562            standalone: false,
9563        };
9564        let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9565            home,
9566            &format!("task:{}", ord.id),
9567            serde_json::to_value(&ord_req).unwrap(),
9568        )
9569        .unwrap();
9570
9571        let mut urg = task_with_id("urg-running");
9572        urg.urgent = true;
9573        urg.status = TaskStatus::Running;
9574        queue.put(&mut urg).unwrap();
9575        let urg_req = TaskWorker {
9576            opts: Opts::default(),
9577            queue: queue.root().to_path_buf(),
9578            task: urg.id.clone(),
9579            lane: PermitKind::Urgent,
9580            standalone: false,
9581        };
9582        let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9583            home,
9584            &format!("task:{}", urg.id),
9585            serde_json::to_value(&urg_req).unwrap(),
9586        )
9587        .unwrap();
9588
9589        let snap = AdmissionSnapshot::capture(home, now);
9590        let adm = snap.evaluate(&imm, &queue, None, home);
9591        assert_eq!(adm.state, "next_poll");
9592        assert_eq!(adm.label, "Immediate: next poll");
9593        assert_eq!(adm.reservation_lane, None);
9594
9595        // Running worker reports its actual persisted reservation lane.
9596        let ord_adm = snap.evaluate(&ord, &queue, None, home);
9597        assert_eq!(ord_adm.state, "running");
9598        assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9599        assert_eq!(ord_adm.label, "Running (ordinary lane)");
9600
9601        // Held (manual + disk) and Blocked (dependency) report concrete blockers.
9602        let mut held = task_with_id("imm-held");
9603        held.immediate = true;
9604        held.hold_manual(Some("awaiting signoff".into()));
9605        queue.put(&mut held).unwrap();
9606        let held_adm = snap.evaluate(&held, &queue, None, home);
9607        assert_eq!(held_adm.state, "waiting");
9608        assert_eq!(
9609            held_adm.label,
9610            "Immediate: waiting — held (awaiting signoff)"
9611        );
9612
9613        let mut disk_held = task_with_id("imm-disk");
9614        disk_held.immediate = true;
9615        disk_held.hold_machine(Some("only 1 GiB free".into()));
9616        disk_held.mark_startup_disk_capacity();
9617        queue.put(&mut disk_held).unwrap();
9618        let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9619        assert_eq!(disk_adm.state, "waiting");
9620        assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9621
9622        let mut blocked = task_with_id("imm-blocked");
9623        blocked.immediate = true;
9624        blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9625        queue.put(&mut blocked).unwrap();
9626        let questions = Questions::at(home.join("questions"));
9627        let inv = crate::blockers::Inventory::load(&queue, &questions);
9628        let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9629        assert_eq!(blocked_adm.state, "waiting");
9630        assert!(
9631            blocked_adm
9632                .label
9633                .starts_with("Immediate: waiting — waiting on dependencies"),
9634            "{blocked_adm:?}"
9635        );
9636
9637        // Existing claim blocks immediate.
9638        let _claim = queue.claim(&imm.id).unwrap();
9639        let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9640        assert_eq!(claimed_adm.state, "waiting");
9641        assert_eq!(
9642            claimed_adm.label,
9643            "Immediate: waiting — claimed by another process"
9644        );
9645        drop(_claim);
9646
9647        // Quota cooldown blocks immediate.
9648        let until = now + jiff::SignedDuration::from_secs(120);
9649        std::fs::write(
9650            home.join("task-quota-cooldown.json"),
9651            serde_json::to_vec(&until).unwrap(),
9652        )
9653        .unwrap();
9654        let cool_snap = AdmissionSnapshot::capture(home, now);
9655        let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9656        assert_eq!(cool_adm.state, "waiting");
9657        assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9658        std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9659
9660        // Corrupt interrupt file is reported as unknown, never "next poll".
9661        std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9662        let bad_snap = AdmissionSnapshot::capture(home, now);
9663        let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9664        assert_eq!(bad_adm.state, "unknown");
9665        assert_ne!(bad_adm.label, "Immediate: next poll");
9666    }
9667
9668    /// The exact wiring `attempt` runs before minting anything: a config's
9669    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
9670    /// Free space is injected rather than asked of the real disk - the point
9671    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
9672    /// is deterministic on every machine this test runs on, never dependent
9673    /// on how full the CI runner's own disk happens to be.
9674    #[test]
9675    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9676        let cfg = Config::default();
9677        let repo = Path::new("/any/repo/path");
9678
9679        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9680            .expect("must hold below the threshold");
9681        assert!(reason.contains("1024"), "{reason}");
9682        assert!(
9683            reason.contains(&cfg.disk.min_free_bytes.to_string()),
9684            "{reason}"
9685        );
9686
9687        assert_eq!(
9688            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9689            None,
9690            "exactly at the floor is open"
9691        );
9692        assert_eq!(
9693            disk_gate_with(
9694                repo,
9695                &cfg,
9696                PathBuf::new,
9697                |_| Ok(cfg.disk.min_free_bytes + 1)
9698            ),
9699            None,
9700            "comfortably above the floor is open"
9701        );
9702    }
9703
9704    /// The collection threshold is not an admission floor: free space just
9705    /// above `min_free_bytes` but far below `reclaim_free_bytes` opens the gate
9706    /// with no hold, whatever the threshold is.
9707    #[test]
9708    fn disk_gate_ignores_the_collection_threshold() {
9709        let mut cfg = Config::default();
9710        cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9711        let repo = Path::new("/any/repo/path");
9712        assert_eq!(
9713            disk_gate_with(
9714                repo,
9715                &cfg,
9716                PathBuf::new,
9717                |_| Ok(cfg.disk.min_free_bytes + 1)
9718            ),
9719            None
9720        );
9721        assert!(
9722            disk_gate_with(
9723                repo,
9724                &cfg,
9725                PathBuf::new,
9726                |_| Ok(cfg.disk.min_free_bytes - 1)
9727            )
9728            .is_some(),
9729            "below the admission floor still holds"
9730        );
9731    }
9732
9733    #[test]
9734    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9735        let dir = tempfile::tempdir().unwrap();
9736        let repo = dir.path().join("repo");
9737        let cache = dir.path().join("cache");
9738        let worktrees = dir.path().join("worktrees");
9739        for path in [&repo, &cache, &worktrees] {
9740            std::fs::create_dir(path).unwrap();
9741        }
9742        let mut cfg = Config::default();
9743        cfg.graph.worktree_root = Some(worktrees.clone());
9744        cfg.verify.gate = vec![format!(
9745            "CARGO_TARGET_DIR='{}' cargo build",
9746            cache.display()
9747        )];
9748        for blocked in [&cache, &worktrees] {
9749            for unmeasured in [false, true] {
9750                assert!(
9751                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9752                        if path == blocked {
9753                            if unmeasured {
9754                                Err(anyhow::anyhow!("measurement failed"))
9755                            } else {
9756                                Ok(0)
9757                            }
9758                        } else {
9759                            Ok(u64::MAX)
9760                        }
9761                    })
9762                    .is_some(),
9763                    "a blocked secondary output volume must close admission"
9764                );
9765            }
9766        }
9767        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9768    }
9769
9770    #[test]
9771    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9772        let dir = tempfile::tempdir().unwrap();
9773        let repo = dir.path().join("repo");
9774        let cache = dir.path().join("cache");
9775        let home_parent = dir.path().join("run-volume");
9776        let home = home_parent.join("new-home");
9777        for path in [&repo, &cache, &home_parent] {
9778            std::fs::create_dir(path).unwrap();
9779        }
9780        let mut cfg = Config::default();
9781        cfg.graph.worktree_root = Some(repo.clone());
9782        cfg.verify.gate = vec![format!(
9783            "CARGO_TARGET_DIR='{}' cargo build",
9784            cache.display()
9785        )];
9786        cfg.verify.build_cache = BuildCache::Isolated;
9787        let denied = |blocked: &Path| {
9788            disk_gate_with(
9789                &repo,
9790                &cfg,
9791                || home.clone(),
9792                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9793            )
9794            .is_some()
9795        };
9796        assert!(!denied(&cache));
9797        assert!(denied(&home_parent));
9798    }
9799
9800    #[test]
9801    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9802        let mut cfg = Config::default();
9803        cfg.disk.min_free_bytes = 0;
9804        let repo = Path::new("/any/repo/path");
9805        assert_eq!(
9806            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9807            None,
9808            "a zero floor never measures at all"
9809        );
9810    }
9811
9812    #[test]
9813    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9814        let cfg = Config::default();
9815        let repo = Path::new("/any/repo/path");
9816        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9817            Err(anyhow::anyhow!("no df on this box"))
9818        })
9819        .expect("a measurement failure must close the gate, not open it");
9820        assert!(reason.contains("could not measure"), "{reason}");
9821    }
9822
9823    #[test]
9824    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9825        let ordinary = task();
9826        let next = advance_interrupt(
9827            Interrupt::Idle,
9828            std::slice::from_ref(&ordinary.id),
9829            std::slice::from_ref(&ordinary),
9830        );
9831        assert_eq!(next, Interrupt::Idle);
9832    }
9833
9834    #[test]
9835    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9836        // Nothing to interrupt - this is just an ordinary candidate, and the
9837        // loop's normal dispatch will pick it up like any other.
9838        let marked = interrupt_task("marked");
9839        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9840        assert_eq!(next, Interrupt::Idle);
9841    }
9842
9843    #[test]
9844    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9845        let marked = interrupt_task("marked");
9846        let next = advance_interrupt(
9847            Interrupt::Idle,
9848            &["running".to_owned()],
9849            std::slice::from_ref(&marked),
9850        );
9851        assert_eq!(
9852            next,
9853            Interrupt::Parking {
9854                parked: vec!["running".to_owned()],
9855                interrupt_task: "marked".to_owned(),
9856            }
9857        );
9858    }
9859
9860    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
9861    /// one run can be in flight when a task becomes runnable and marked.
9862    /// Parking all of them would mean `Resuming` later has more than one id
9863    /// to release back to ordinary dispatch, which cannot be made safe
9864    /// against that same setting's own extra concurrency slots letting two
9865    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
9866    /// The simplification the task's own constraints ask for: do not begin
9867    /// a sequence at all until the herd settles back to exactly one.
9868    #[test]
9869    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9870        let marked = interrupt_task("marked");
9871
9872        let two = advance_interrupt(
9873            Interrupt::Idle,
9874            &["a".to_owned(), "b".to_owned()],
9875            std::slice::from_ref(&marked),
9876        );
9877        assert_eq!(two, Interrupt::Idle);
9878
9879        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9880        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9881    }
9882
9883    #[test]
9884    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9885        let state = Interrupt::Parking {
9886            parked: vec!["running".to_owned()],
9887            interrupt_task: "marked".to_owned(),
9888        };
9889        // Still in flight: no change.
9890        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9891        assert_eq!(still_going, state);
9892
9893        // Left flight, but the interrupt task has not been dispatched yet on
9894        // this tick - stays `Parking` so `interrupt_gate` can let it through,
9895        // as long as it is still runnable.
9896        let stopped_but_not_yet_dispatched =
9897            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9898        assert_eq!(stopped_but_not_yet_dispatched, state);
9899
9900        // Left flight, and the interrupt task is now in flight itself.
9901        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9902        assert_eq!(
9903            dispatched,
9904            Interrupt::Running {
9905                parked: vec!["running".to_owned()],
9906                interrupt_task: "marked".to_owned(),
9907            }
9908        );
9909    }
9910
9911    #[test]
9912    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9913        let state = Interrupt::Running {
9914            parked: vec!["running".to_owned()],
9915            interrupt_task: "marked".to_owned(),
9916        };
9917        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9918        assert_eq!(still_running, state);
9919
9920        // Whatever it ended as - merged, failed, held - is not this
9921        // function's concern: leaving flight is the only trigger, driven
9922        // straight off the same in-flight list `poll` already reaps. It does
9923        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
9924        // why that would let an unrelated task start ahead of, or alongside,
9925        // the guaranteed resume.
9926        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9927        assert_eq!(
9928            ended,
9929            Interrupt::Resuming {
9930                parked: vec!["running".to_owned()]
9931            }
9932        );
9933    }
9934
9935    #[test]
9936    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9937        let state = Interrupt::Resuming {
9938            parked: vec!["running".to_owned()],
9939        };
9940        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9941        assert_eq!(still_waiting, state);
9942
9943        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9944        assert_eq!(dispatched, Interrupt::Idle);
9945    }
9946
9947    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
9948    /// or otherwise moved on by an operator with no claim standing in the
9949    /// way - must not wedge the sequence (and so the whole loop's dispatch,
9950    /// via `interrupt_gate`) waiting forever for a dispatch that can never
9951    /// come. The parked run still gets its resume.
9952    #[test]
9953    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9954    {
9955        let state = Interrupt::Parking {
9956            parked: vec!["running".to_owned()],
9957            interrupt_task: "marked".to_owned(),
9958        };
9959        // `marked` has been held/blocked/deleted since the sequence began:
9960        // it no longer appears in `runnable` at all.
9961        let next = advance_interrupt(state, &[], &[]);
9962        assert_eq!(
9963            next,
9964            Interrupt::Resuming {
9965                parked: vec!["running".to_owned()]
9966            },
9967            "abandoning the interrupt must not abandon the resume it owes"
9968        );
9969    }
9970
9971    /// The same abandonment, one step later: `Resuming` itself must not wait
9972    /// forever for a parked task that has since become unrunnable.
9973    #[test]
9974    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9975        let state = Interrupt::Resuming {
9976            parked: vec!["running".to_owned()],
9977        };
9978        let next = advance_interrupt(state, &[], &[]);
9979        assert_eq!(
9980            next,
9981            Interrupt::Idle,
9982            "nothing is left to wait for; the loop must not stay wedged"
9983        );
9984    }
9985
9986    #[test]
9987    fn disabled_by_config_the_sequence_can_never_leave_idle() {
9988        let marked = interrupt_task("marked");
9989        let next = advance_interrupt_tick(
9990            false,
9991            Interrupt::Idle,
9992            &["running".to_owned()],
9993            std::slice::from_ref(&marked),
9994        );
9995        assert_eq!(
9996            next,
9997            Interrupt::Idle,
9998            "an unmarked, unconfigured daemon must behave exactly as before"
9999        );
10000    }
10001
10002    #[test]
10003    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
10004        let state = Interrupt::Parking {
10005            parked: vec!["running".to_owned()],
10006            interrupt_task: "marked".to_owned(),
10007        };
10008        let candidates = vec![interrupt_task("marked"), task()];
10009        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
10010        assert!(
10011            allowed.is_empty(),
10012            "nothing may dispatch - not even the interrupt task itself - \
10013             until the parked run has actually stopped"
10014        );
10015    }
10016
10017    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
10018    /// grow a special case for it: an urgent candidate that is not the
10019    /// interrupt task withholds exactly like an ordinary one for as long as
10020    /// the parked run it is racing has not actually left flight. A version
10021    /// of this feature once bypassed the gate for urgent candidates, on the
10022    /// theory that a genuinely separate concurrency lane could not collide
10023    /// with 75dd's own; it could, and did - the bypassed task dispatched
10024    /// alongside a run 75dd's own state machine had only *asked* to park,
10025    /// not yet confirmed gone, which is exactly the second run
10026    /// `Interrupt::Parking`'s own doc says must never happen. There is no
10027    /// tick during Parking/Running/Resuming where letting an extra
10028    /// candidate through is safe, urgent or not - the parked run may still
10029    /// be genuinely mid-call.
10030    #[test]
10031    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
10032        for state in [
10033            Interrupt::Parking {
10034                parked: vec!["running".to_owned()],
10035                interrupt_task: "marked".to_owned(),
10036            },
10037            Interrupt::Running {
10038                parked: vec!["running".to_owned()],
10039                interrupt_task: "marked".to_owned(),
10040            },
10041            Interrupt::Resuming {
10042                parked: vec!["running".to_owned()],
10043            },
10044        ] {
10045            let candidates = vec![
10046                interrupt_task("marked"),
10047                urgent_task("hot"),
10048                task_with_id("ordinary"),
10049            ];
10050            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
10051            assert!(
10052                !allowed.iter().any(|t| t.id == "hot"),
10053                "an urgent candidate must wait out the same gate as anything \
10054                 else while the run it would run alongside has not actually \
10055                 left flight, for state {state:?}: {allowed:?}"
10056            );
10057        }
10058    }
10059
10060    /// The one case where marking a task `--urgent` and `interrupt` at once
10061    /// is not redundant: once the interrupt sequence's own guaranteed
10062    /// resume/dispatch actually admits the task, it is unaffected by also
10063    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
10064    /// never on the urgent flag.
10065    #[test]
10066    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
10067        let state = Interrupt::Resuming {
10068            parked: vec!["hot".to_owned()],
10069        };
10070        let candidates = vec![urgent_task("hot"), task()];
10071        let allowed = interrupt_gate(&state, &[], candidates);
10072        assert_eq!(
10073            allowed.iter().filter(|t| t.id == "hot").count(),
10074            1,
10075            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
10076        );
10077    }
10078
10079    #[test]
10080    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
10081        let state = Interrupt::Parking {
10082            parked: vec!["running".to_owned()],
10083            interrupt_task: "marked".to_owned(),
10084        };
10085        let other = task();
10086        let candidates = vec![interrupt_task("marked"), other.clone()];
10087        let allowed = interrupt_gate(&state, &[], candidates);
10088        assert_eq!(allowed.len(), 1);
10089        assert_eq!(allowed[0].id, "marked");
10090    }
10091
10092    #[test]
10093    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
10094        let state = Interrupt::Running {
10095            parked: vec!["running".to_owned()],
10096            interrupt_task: "marked".to_owned(),
10097        };
10098        let candidates = vec![task(), task()];
10099        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
10100        assert!(allowed.is_empty());
10101    }
10102
10103    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
10104    /// sequence began (only reachable above the default
10105    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
10106    /// never both in the same tick, which is what "exactly one resume, no
10107    /// simultaneous run" actually requires structurally rather than by
10108    /// coincidence of how many ordinary slots happen to be free.
10109    #[test]
10110    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
10111        let state = Interrupt::Resuming {
10112            parked: vec!["a".to_owned(), "c".to_owned()],
10113        };
10114        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
10115        let allowed = interrupt_gate(&state, &[], candidates);
10116        assert_eq!(
10117            allowed.len(),
10118            1,
10119            "at most one candidate may be offered while resuming: {allowed:?}"
10120        );
10121        assert_eq!(allowed[0].id, "a");
10122    }
10123
10124    #[test]
10125    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
10126        let state = Interrupt::Resuming {
10127            parked: vec!["a".to_owned()],
10128        };
10129        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
10130        assert!(allowed.is_empty());
10131    }
10132
10133    /// The invariant the completion criteria ask for by name: across a whole
10134    /// simulated sequence, there is never a tick where the gate would let
10135    /// through both the parked run's resume and the interrupt task, and
10136    /// exactly one candidate resumes the instant the interrupt task's run
10137    /// ends - never zero, never more than one.
10138    #[test]
10139    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
10140        let running = task(); // id: whatever `Task::new` minted
10141        let marked = interrupt_task("marked");
10142
10143        let mut state = Interrupt::Idle;
10144        // Tick 1: `running` is in flight, `marked` becomes runnable.
10145        let in_flight = vec![running.id.clone()];
10146        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
10147        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10148        assert!(gated.is_empty(), "still waiting on `running` to park");
10149
10150        // Tick 2: `running` parked and left flight; nothing dispatched yet.
10151        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10152        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10153        assert_eq!(
10154            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10155            vec!["marked"],
10156            "only the interrupt task may be offered to the dispatcher now"
10157        );
10158
10159        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
10160        state = advance_interrupt_tick(
10161            true,
10162            state,
10163            &["marked".to_owned()],
10164            std::slice::from_ref(&running),
10165        );
10166        let gated = interrupt_gate(
10167            &state,
10168            &["marked".to_owned()],
10169            vec![marked.clone(), running.clone()],
10170        );
10171        assert!(
10172            gated.is_empty(),
10173            "the parked run must not be offered back while the interrupt \
10174             task is still running"
10175        );
10176
10177        // Tick 4: `marked`'s run reached a terminal status and left flight.
10178        // A higher-priority ordinary task `other` is also runnable now - it
10179        // must not be let through instead of, or alongside, `running`.
10180        let other = task_with_id("other");
10181        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10182        assert_eq!(
10183            state,
10184            Interrupt::Resuming {
10185                parked: vec![running.id.clone()]
10186            }
10187        );
10188        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10189        assert_eq!(
10190            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10191            vec![running.id.as_str()],
10192            "exactly the parked run resumes - not the unrelated task, even \
10193             though it was offered first"
10194        );
10195
10196        // Tick 5: `running` is now in flight (dispatched from tick 4's
10197        // gate). Only now does the sequence end and ordinary dispatch fully
10198        // resume.
10199        state = advance_interrupt_tick(
10200            true,
10201            state,
10202            std::slice::from_ref(&running.id),
10203            std::slice::from_ref(&other),
10204        );
10205        assert_eq!(state, Interrupt::Idle);
10206        let gated = interrupt_gate(
10207            &state,
10208            std::slice::from_ref(&running.id),
10209            vec![other.clone()],
10210        );
10211        assert_eq!(
10212            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10213            vec![other.id.as_str()],
10214            "ordinary dispatch is unrestricted again"
10215        );
10216    }
10217
10218    #[test]
10219    fn every_run_status_settles_the_task_it_came_from() {
10220        // run status, resulting task status, attempts still standing after one
10221        let table = [
10222            (RunStatus::Merged, TaskStatus::Done, 1),
10223            (RunStatus::Ready, TaskStatus::Held, 1),
10224            (RunStatus::Stalled, TaskStatus::Failed, 0),
10225            (RunStatus::Blocked, TaskStatus::Failed, 1),
10226            (RunStatus::Failed, TaskStatus::Failed, 1),
10227            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10228            (RunStatus::Prep, TaskStatus::Failed, 1),
10229            (RunStatus::Implementing, TaskStatus::Failed, 1),
10230            (RunStatus::Judging, TaskStatus::Failed, 1),
10231            (RunStatus::Deliberating, TaskStatus::Failed, 1),
10232            (RunStatus::Voting, TaskStatus::Failed, 1),
10233            (RunStatus::Reviewing, TaskStatus::Failed, 1),
10234            (RunStatus::Gating, TaskStatus::Failed, 1),
10235        ];
10236        for (run, want, attempts) in table {
10237            let mut t = task();
10238            t.start("20260902-000000-aaaa".to_owned());
10239            settle(
10240                &mut t,
10241                Verdict {
10242                    status: run,
10243                    left_pr: false,
10244                    parked: false,
10245                    quota_hit: matches!(run, RunStatus::Stalled),
10246                    no_viable_candidates: false,
10247                },
10248                "why",
10249                2,
10250            );
10251            assert_eq!(t.status, want, "task status after {}", label(run));
10252            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10253        }
10254    }
10255
10256    #[test]
10257    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10258        let mut stalled = task();
10259        stalled.start("20260902-000000-aaaa".to_owned());
10260        settle(
10261            &mut stalled,
10262            Verdict {
10263                status: RunStatus::Stalled,
10264                left_pr: false,
10265                parked: false,
10266                quota_hit: true,
10267                no_viable_candidates: false,
10268            },
10269            "quota",
10270            1,
10271        );
10272        assert_eq!(stalled.attempts, 0);
10273        assert!(
10274            stalled.status.runnable(),
10275            "a machine problem must leave the task in line"
10276        );
10277
10278        let mut blocked = task();
10279        blocked.start("20260902-000000-aaaa".to_owned());
10280        settle(
10281            &mut blocked,
10282            Verdict {
10283                status: RunStatus::Blocked,
10284                left_pr: false,
10285                parked: false,
10286                quota_hit: false,
10287                no_viable_candidates: false,
10288            },
10289            "findings open",
10290            1,
10291        );
10292        assert_eq!(blocked.attempts, 1);
10293        assert_eq!(
10294            blocked.status,
10295            TaskStatus::Held,
10296            "the last attempt hands the task to a human"
10297        );
10298    }
10299
10300    #[test]
10301    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10302        // Attempts to spare: without the pull request this task would go
10303        // straight back in line and run the whole competition again.
10304        let mut delivered = task();
10305        delivered.start("20260903-080619-01c2".to_owned());
10306        settle(
10307            &mut delivered,
10308            Verdict {
10309                status: RunStatus::Blocked,
10310                left_pr: true,
10311                parked: false,
10312                quota_hit: false,
10313                no_viable_candidates: false,
10314            },
10315            "no check status",
10316            4,
10317        );
10318        assert_eq!(
10319            delivered.status,
10320            TaskStatus::Held,
10321            "a pull request waiting on CI or a person is not a retryable failure"
10322        );
10323        assert!(
10324            !delivered.status.runnable(),
10325            "the loop must not pick this task up again"
10326        );
10327        assert_eq!(
10328            delivered.last_error.as_deref(),
10329            Some("no check status"),
10330            "the operator needs to be told what the gate was waiting for"
10331        );
10332
10333        // The same status without a pull request is a plain failure, and with
10334        // attempts left it is retried.
10335        let mut empty_handed = task();
10336        empty_handed.start("20260903-080619-01c2".to_owned());
10337        settle(
10338            &mut empty_handed,
10339            Verdict {
10340                status: RunStatus::Blocked,
10341                left_pr: false,
10342                parked: false,
10343                quota_hit: false,
10344                no_viable_candidates: false,
10345            },
10346            "findings open",
10347            4,
10348        );
10349        assert_eq!(empty_handed.status, TaskStatus::Failed);
10350        assert!(empty_handed.status.runnable());
10351    }
10352
10353    #[test]
10354    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10355        // Every candidate agreed, with evidence, that nothing belonged in the
10356        // worktree. That is not a confirmed success to close automatically -
10357        // a human still has to check the claim - and it is not an ordinary
10358        // failure either, so this settles exactly like a pull request nobody
10359        // merged yet: `Held`, same as `Blocked` with a PR.
10360        let mut noop = task();
10361        noop.start("20260912-131304-391f".to_owned());
10362        settle(
10363            &mut noop,
10364            Verdict {
10365                status: RunStatus::VerifiedNoop,
10366                left_pr: false,
10367                parked: false,
10368                quota_hit: false,
10369                no_viable_candidates: true,
10370            },
10371            "candidate A: already fixed by b32cfc4, on main",
10372            4,
10373        );
10374        assert_eq!(
10375            noop.status,
10376            TaskStatus::Held,
10377            "an unverified claim is a request for a human, not a failure"
10378        );
10379        assert!(
10380            !noop.status.runnable(),
10381            "the loop must not requeue this on the same unverified claim"
10382        );
10383        // `Task::release` resets attempts to zero the moment a human looks at
10384        // the evidence and lets it run again, so it does not matter here
10385        // whether the one attempt already spent stays spent - what matters is
10386        // that nothing retries this task unattended in the meantime.
10387        assert_eq!(noop.attempts, 1);
10388    }
10389
10390    #[test]
10391    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10392        // Parking is the operator asking for the process back - to replace the
10393        // binary, most of all. The run's work is intact on disk, so this is
10394        // not a failed attempt, and charging for it would mean a few upgrades
10395        // could exhaust a budget meant for agents that misbehaved.
10396        let mut parked = task();
10397        parked.start("20260903-183634-2d98".to_owned());
10398        settle(
10399            &mut parked,
10400            Verdict {
10401                status: RunStatus::Implementing,
10402                left_pr: false,
10403                quota_hit: false,
10404                parked: true,
10405                no_viable_candidates: false,
10406            },
10407            "parked after `implementing`",
10408            2,
10409        );
10410        assert_eq!(parked.attempts, 0, "a park is refunded");
10411        assert!(
10412            parked.status.runnable(),
10413            "and the task stays in line so the next loop resumes its run"
10414        );
10415        assert_eq!(parked.status, TaskStatus::Parked);
10416        assert_eq!(
10417            parked.park_reason.as_deref(),
10418            Some("parked after `implementing`"),
10419            "the card says where it stopped"
10420        );
10421        assert_eq!(parked.last_error, None, "nothing failed");
10422
10423        // Without the park flag the same non-terminal status is what it always
10424        // was: `execute` returning mid-flight, which is a bug and spends an
10425        // attempt so a task cannot loop on it forever.
10426        let mut broken = task();
10427        broken.start("20260903-183634-2d98".to_owned());
10428        settle(
10429            &mut broken,
10430            Verdict {
10431                status: RunStatus::Implementing,
10432                left_pr: false,
10433                quota_hit: false,
10434                parked: false,
10435                no_viable_candidates: false,
10436            },
10437            "returned mid-flight",
10438            2,
10439        );
10440        assert_eq!(broken.attempts, 1);
10441    }
10442
10443    #[test]
10444    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10445        // Run e633: quorum lost because two judges answered with the wrong
10446        // JSON shape, `quota: []`. Refunding that takes the bound off the
10447        // retry loop, and each retry pays for a fresh hour-long implement
10448        // wave before it can fail the same way.
10449        let mut flaky = task();
10450        flaky.start("20260903-123023-e633".to_owned());
10451        settle(
10452            &mut flaky,
10453            Verdict {
10454                status: RunStatus::Stalled,
10455                left_pr: false,
10456                parked: false,
10457                quota_hit: false,
10458                no_viable_candidates: false,
10459            },
10460            "verdict rests on 1 of 3 judges",
10461            2,
10462        );
10463        assert_eq!(
10464            flaky.attempts, 1,
10465            "flakiness spends an attempt, so `max_attempts` still bounds it"
10466        );
10467        assert!(flaky.status.runnable(), "and it is still worth retrying");
10468
10469        // The same status, lost to a rate limit, is the machine's fault.
10470        let mut limited = task();
10471        limited.start("20260903-123023-e633".to_owned());
10472        settle(
10473            &mut limited,
10474            Verdict {
10475                status: RunStatus::Stalled,
10476                left_pr: false,
10477                parked: false,
10478                quota_hit: true,
10479                no_viable_candidates: false,
10480            },
10481            "judge-2, judge-3 out of quota",
10482            2,
10483        );
10484        assert_eq!(limited.attempts, 0, "a quota window is refunded");
10485        assert!(limited.status.runnable());
10486
10487        // And the bound really binds: a task that keeps stalling on flakiness
10488        // reaches a human instead of running the roster forever.
10489        let mut worn = task();
10490        for _ in 0..2 {
10491            worn.release();
10492        }
10493        worn.start("20260903-123023-e633".to_owned());
10494        worn.attempts = 2;
10495        settle(
10496            &mut worn,
10497            Verdict {
10498                status: RunStatus::Stalled,
10499                left_pr: false,
10500                parked: false,
10501                quota_hit: false,
10502                no_viable_candidates: false,
10503            },
10504            "no quorum again",
10505            2,
10506        );
10507        assert_eq!(worn.status, TaskStatus::Held);
10508        assert!(!worn.status.runnable());
10509    }
10510
10511    #[test]
10512    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10513        // The implement wave loses every seat to the same rate limit and
10514        // `after_implement` bails with nothing viable, which surfaces as
10515        // `Failed` rather than `Stalled`. That is the same machine fact the
10516        // `Stalled`-quota row already refunds, and must be refunded the same
10517        // way, or a quota outage quietly holds every task it touches instead
10518        // of leaving them in line for the reset.
10519        let mut wiped_out = task();
10520        wiped_out.start("20260907-025000-a1b2".to_owned());
10521        settle(
10522            &mut wiped_out,
10523            Verdict {
10524                status: RunStatus::Failed,
10525                left_pr: false,
10526                parked: false,
10527                quota_hit: true,
10528                no_viable_candidates: true,
10529            },
10530            "no candidate produced a change; nothing to judge",
10531            2,
10532        );
10533        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10534        assert!(
10535            wiped_out.status.runnable(),
10536            "a machine problem must leave the task in line"
10537        );
10538
10539        // This is the exemption that must stay narrow: a candidate that did
10540        // produce a change, and then failed for some other reason, still
10541        // spends the attempt even though a seat elsewhere hit its quota.
10542        // Otherwise every ordinary failure that happens to share a run with
10543        // an unrelated rate limit would be refunded for free.
10544        let mut partial_progress = task();
10545        partial_progress.start("20260907-025500-c3d4".to_owned());
10546        settle(
10547            &mut partial_progress,
10548            Verdict {
10549                status: RunStatus::Failed,
10550                left_pr: false,
10551                parked: false,
10552                quota_hit: true,
10553                no_viable_candidates: false,
10554            },
10555            "gate failed on the winning candidate",
10556            2,
10557        );
10558        assert_eq!(
10559            partial_progress.attempts, 1,
10560            "a candidate that actually produced a change spends the attempt \
10561             even though some other seat hit its quota"
10562        );
10563        assert!(partial_progress.status.runnable());
10564    }
10565
10566    #[test]
10567    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10568        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
10569        // disk, and that construction must reach the same conclusion as the
10570        // one `attempt` builds from a live run, or a crash at exactly the
10571        // wrong moment gives a recovered task a different policy than one a
10572        // daemon finished settling itself.
10573        let mut t = task();
10574        t.start("20260907-025000-a1b2".to_owned());
10575        let mut state = run_state(RunStatus::Failed);
10576        state.quota.push(QuotaLoss {
10577            cause: crate::agent::QuotaCause::UsageLimit,
10578            agent: String::new(),
10579            seat: "cand-a".to_owned(),
10580            node: "implement".to_owned(),
10581            at: Timestamp::now(),
10582            reset: None,
10583        });
10584        assert!(
10585            state.viable().is_empty(),
10586            "no candidate was added, so nothing is viable"
10587        );
10588        reclaim(&mut t, Some(state), 2, "en");
10589        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10590        assert!(t.status.runnable());
10591    }
10592
10593    #[test]
10594    fn a_held_task_is_never_offered_to_the_loop() {
10595        let dir = tempfile::tempdir().unwrap();
10596        let queue = Queue::at(dir.path().to_path_buf());
10597        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10598            let mut t = task();
10599            t.id = format!("2026090{n}-000000-000{n}");
10600            t.priority = priority;
10601            queue.put(&mut t).unwrap();
10602        }
10603        let mut held = task();
10604        held.id = "20260909-000000-9999".to_owned();
10605        held.priority = 99;
10606        held.hold_machine(None);
10607        queue.put(&mut held).unwrap();
10608
10609        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10610        assert_eq!(order.len(), 3);
10611        assert!(!order.contains(&held.id));
10612        assert_eq!(
10613            order.first().cloned(),
10614            queue.next_runnable().map(|t| t.id),
10615            "the loop's first candidate is exactly what the queue offers"
10616        );
10617        assert_eq!(
10618            order,
10619            vec![
10620                "20260902-000000-0002".to_owned(),
10621                "20260903-000000-0003".to_owned(),
10622                "20260901-000000-0001".to_owned(),
10623            ],
10624            "priority first, then oldest, so nothing starves"
10625        );
10626    }
10627
10628    #[test]
10629    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10630        let dir = tempfile::tempdir().unwrap();
10631        let queue = Queue::at(dir.path().to_path_buf());
10632        let mut old = task();
10633        old.id = "20260101-000000-old0".to_owned();
10634        queue.put(&mut old).unwrap();
10635        let mut fresh = task();
10636        fresh.id = "20260101-000000-new0".to_owned();
10637        queue.put(&mut fresh).unwrap();
10638
10639        // No parseable pid at all, so age is the only signal there is to
10640        // check - unlike a real `Queue::claim`, which always names a real,
10641        // and therefore alive, pid this test cannot fake as dead.
10642        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10643        std::thread::sleep(Duration::from_millis(60));
10644        let live = queue.claim(&fresh.id).unwrap();
10645
10646        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10647        assert_eq!(swept, vec![old.id.clone()]);
10648        assert!(
10649            queue.claim(&old.id).is_ok(),
10650            "an unparseable lock older than the threshold is swept"
10651        );
10652        assert!(
10653            queue.claim(&fresh.id).is_err(),
10654            "a live pid protects its lock regardless of age"
10655        );
10656        drop(live);
10657    }
10658
10659    #[test]
10660    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10661        // A live worker's claim remains authoritative even beyond the sweep's
10662        // age limit. Sweeping it would permit a second competing attempt.
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-live".to_owned();
10667        queue.put(&mut t).unwrap();
10668
10669        let claim = queue.claim(&t.id).unwrap();
10670        std::thread::sleep(Duration::from_millis(60));
10671
10672        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10673        assert!(
10674            swept.is_empty(),
10675            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10676        );
10677        assert!(
10678            queue.claim(&t.id).is_err(),
10679            "the lock still protects its task"
10680        );
10681        drop(claim);
10682    }
10683
10684    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
10685    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
10686    fn injected_dead_pid() -> u32 {
10687        std::process::id().checked_add(1).unwrap_or(1)
10688    }
10689
10690    #[test]
10691    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10692        let dir = tempfile::tempdir().unwrap();
10693        let queue = Queue::at(dir.path().to_path_buf());
10694        let mut t = task();
10695        t.id = "20260101-000000-dead".to_owned();
10696        queue.put(&mut t).unwrap();
10697        let dead_pid = injected_dead_pid();
10698
10699        // Written directly rather than through `Queue::claim`, which would
10700        // stamp this test process's own very much alive pid and defeat the
10701        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
10702        // like moments after it died, not six hours later.
10703        std::fs::write(
10704            dir.path().join(format!("{}.lock", t.id)),
10705            dead_pid.to_string(),
10706        )
10707        .unwrap();
10708
10709        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10710            pid != dead_pid
10711        });
10712        assert_eq!(
10713            swept,
10714            vec![t.id.clone()],
10715            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10716        );
10717        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10718    }
10719
10720    #[test]
10721    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10722        let dir = tempfile::tempdir().unwrap();
10723        let queue = Queue::at(dir.path().to_path_buf());
10724        let mut t = task();
10725        t.id = "20260101-000000-late".to_owned();
10726        queue.put(&mut t).unwrap();
10727        let dead_pid = injected_dead_pid();
10728
10729        // Tick one, standing in for the sweep `poll` already runs at
10730        // startup: nothing to find yet.
10731        assert!(
10732            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10733            "nothing has claimed the task yet"
10734        );
10735
10736        // A second daemon claims the task and dies before it ever writes
10737        // `running`, well after this loop's own startup sweep already ran.
10738        std::fs::write(
10739            dir.path().join(format!("{}.lock", t.id)),
10740            dead_pid.to_string(),
10741        )
10742        .unwrap();
10743
10744        // Tick two, standing in for a poll long into this daemon's uptime:
10745        // the same function, called again, notices what only just appeared -
10746        // proving the sweep is not a one-shot startup check.
10747        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10748            pid != dead_pid
10749        });
10750        assert_eq!(swept, vec![t.id.clone()]);
10751    }
10752
10753    #[test]
10754    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10755        // `reclaim_orphaned_running` looks up the task's last run, which
10756        // touches `run::home()`; the first call anywhere in this binary wins,
10757        // so this is a no-op if another test already pinned one, and either
10758        // way the run id below is never written under it.
10759        crate::run::pin_test_home();
10760        let dir = tempfile::tempdir().unwrap();
10761        let queue = Queue::at(dir.path().to_path_buf());
10762        let mut t = task();
10763        t.id = "20260101-000000-crsh".to_owned();
10764        t.status = TaskStatus::Running;
10765        t.attempts = 1;
10766        // No `run.json` behind this id: standing in for a run this test does
10767        // not need to make readable, since the point is the lock, not the
10768        // recovery table `reclaim` already has its own tests for.
10769        t.runs.push("20260904-000000-4043".to_owned());
10770        queue.put(&mut t).unwrap();
10771        let dead_pid = injected_dead_pid();
10772
10773        // The crashed daemon's own claim, naming a pid nothing on the
10774        // machine holds anymore.
10775        std::fs::write(
10776            dir.path().join(format!("{}.lock", t.id)),
10777            dead_pid.to_string(),
10778        )
10779        .unwrap();
10780
10781        // Before the lock is swept the task looks claimed, and
10782        // `reclaim_orphaned_running` must leave it alone - this is exactly
10783        // the bug: a `running` task stranded behind a dead daemon's lock,
10784        // invisible to the claim-as-proof check because the lock outlived
10785        // the process that wrote it.
10786        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10787        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10788
10789        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10790            pid != dead_pid
10791        });
10792        assert_eq!(swept, vec![t.id.clone()]);
10793
10794        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10795        assert_eq!(reclaimed, vec![t.id.clone()]);
10796        let after = queue.get(&t.id).unwrap();
10797        assert_eq!(
10798            after.status,
10799            TaskStatus::Held,
10800            "no run.json to recover from, so a human is asked"
10801        );
10802        assert_eq!(
10803            after.runs,
10804            vec!["20260904-000000-4043".to_owned()],
10805            "the crashed run's id is kept as evidence, not discarded"
10806        );
10807    }
10808
10809    #[test]
10810    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10811        let dir = tempfile::tempdir().unwrap();
10812        let queue = Queue::at(dir.path().to_path_buf());
10813        let mut t = task();
10814        t.id = "20260101-000000-unknown".to_owned();
10815        queue.put(&mut t).unwrap();
10816        let dead_pid = injected_dead_pid();
10817        std::fs::write(
10818            dir.path().join(format!("{}.lock", t.id)),
10819            dead_pid.to_string(),
10820        )
10821        .unwrap();
10822
10823        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10824        assert!(swept.is_empty(), "an unknown pid must keep its lock");
10825        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10826    }
10827
10828    fn run_state_in(status: RunStatus, language: &str) -> RunState {
10829        let mut s = run_state(status);
10830        s.config.graph.language = language.to_owned();
10831        s
10832    }
10833
10834    fn unstarted_verdict(status: RunStatus) -> Verdict {
10835        Verdict {
10836            status,
10837            left_pr: false,
10838            quota_hit: false,
10839            parked: false,
10840            no_viable_candidates: false,
10841        }
10842    }
10843
10844    #[test]
10845    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10846        let mut t = task();
10847        t.attempts = 1;
10848        settle_in(
10849            &mut t,
10850            unstarted_verdict(RunStatus::AlreadyInBase),
10851            "already in main",
10852            1,
10853            phrases("en"),
10854            None,
10855        );
10856        assert_eq!(t.status, TaskStatus::Done);
10857        assert_eq!(t.attempts, 0);
10858    }
10859
10860    #[test]
10861    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10862        let reason = |language: &str| {
10863            let mut t = task();
10864            settle_in(
10865                &mut t,
10866                unstarted_verdict(RunStatus::Judging),
10867                "boom",
10868                1,
10869                phrases(language),
10870                None,
10871            );
10872            t.last_error.or(t.hold_reason).unwrap_or_default()
10873        };
10874        assert!(
10875            reason("en").starts_with("the graph stopped at `"),
10876            "{}",
10877            reason("en")
10878        );
10879        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10880        assert!(reason("日本語").contains("boom"));
10881        assert_eq!(reason("fr"), reason("en"));
10882    }
10883
10884    #[test]
10885    fn describe_follows_the_run_language_and_keeps_the_run_id() {
10886        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10887        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10888        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10889        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10890        assert!(ja.contains("[run "), "{ja}");
10891        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10892        assert!(ended.starts_with("run 終了: "), "{ended}");
10893        let mut de = run_state_in(RunStatus::Failed, "de");
10894        let mut en = run_state_in(RunStatus::Failed, "en");
10895        de.id = "same".to_owned();
10896        en.id = "same".to_owned();
10897        assert_eq!(describe(&de), describe(&en));
10898    }
10899
10900    #[test]
10901    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10902        use crate::handover::Refused;
10903        let cases = [
10904            Refused::Foreign {
10905                branch: "b".into(),
10906                path: "/w/x".into(),
10907                why: "made by hand".into(),
10908            },
10909            Refused::Unsafe {
10910                branch: "b".into(),
10911                path: "/w/x".into(),
10912                why: "its worktree has uncommitted changes (a.rs)".into(),
10913            },
10914            Refused::ReleaseFailed {
10915                branch: "b".into(),
10916                path: "/w/x".into(),
10917                run: "ab12".into(),
10918            },
10919        ];
10920        for r in &cases {
10921            let en = (phrases("en").handover_refused)(r);
10922            assert_eq!(en, r.to_string());
10923            let ja = (phrases("ja").handover_refused)(r);
10924            assert!(
10925                !ja.contains("is checked out") && !ja.contains("try again"),
10926                "{ja}"
10927            );
10928            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10929            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10930                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10931            }
10932        }
10933        assert!(phrases("en").handover_hint.contains("release the task"));
10934        assert!(phrases("ja").handover_hint.contains("解放"));
10935    }
10936
10937    #[test]
10938    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10939        let build = |lang: &str| {
10940            let mut s = run_state_in(RunStatus::Blocked, lang);
10941            s.id = "same".to_owned();
10942            s.config.graph.review_rounds = 3;
10943            let mut r = review_round(3);
10944            r.expected = 3;
10945            r.answered = 1;
10946            s.reviews.push(r);
10947            s.event(
10948                "review",
10949                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10950            );
10951            s
10952        };
10953        let en = describe(&build("en"));
10954        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10955        let ja = describe(&build("ja"));
10956        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10957        assert!(!ja.contains("never answered"), "{ja}");
10958        assert!(ja.contains("[run "), "{ja}");
10959
10960        // An incomplete panel whose verification failed is a different stop:
10961        // the real event must survive in ja too.
10962        let mut failed = build("ja");
10963        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10964            command: "cargo test".to_owned(),
10965            code: Some(1),
10966            output_tail: String::new(),
10967            duration_ms: 0,
10968            resource_blocked: false,
10969            ..Default::default()
10970        });
10971        failed.event("review", "stopped; e2e failed: cargo test");
10972        let ja = describe(&failed);
10973        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10974        assert!(!ja.contains("席のレビュアー"), "{ja}");
10975    }
10976
10977    #[test]
10978    fn refusals_and_recovery_prose_follow_the_language() {
10979        let home = crate::run::test_home();
10980        let t = held_task_with("r1");
10981        let q = action_question(
10982            "r1",
10983            ask::ChoiceAction::Resume {
10984                run: "r1".to_owned(),
10985            },
10986        );
10987        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10988            ActionDecision::Refuse(s) => s,
10989            other => panic!("{other:?}"),
10990        };
10991        assert!(refuse(phrases("en")).contains("could not be read: gone"));
10992        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10993        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10994
10995        let mut held = task();
10996        reclaim(&mut held, None, 2, "ja");
10997        assert!(held.hold_reason.unwrap().contains("保留にしました"));
10998        let mut held = task();
10999        reclaim(&mut held, None, 2, "xx");
11000        assert!(held.hold_reason.unwrap().contains("held for a human"));
11001    }
11002
11003    fn run_state(status: RunStatus) -> RunState {
11004        let mut state = RunState::new(
11005            PathBuf::from("/repo"),
11006            "main".to_owned(),
11007            "abc1234def".to_owned(),
11008            "add retries".to_owned(),
11009            Config::default(),
11010        );
11011        state.status = status;
11012        state
11013    }
11014
11015    #[test]
11016    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
11017        crate::run::pin_test_home();
11018        let dir = tempfile::tempdir().unwrap();
11019        let mut state = run_state(RunStatus::Blocked);
11020        state.id = "20260101-000000-audit".into();
11021        state.save_under(dir.path()).unwrap();
11022        let mut t = task();
11023        t.start(state.id.clone());
11024        // The final state is newer than disk, as when a worker settles its
11025        // in-memory outcome or recovery is passed an already loaded run.
11026        state.status = RunStatus::Merged;
11027        settle_and_diagnose(
11028            &mut t,
11029            unstarted_verdict(RunStatus::Merged),
11030            "Verified delivery",
11031            2,
11032            &state,
11033        );
11034        let completion = t.completion_history.last().unwrap();
11035        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
11036        assert_eq!(completion.prior_status, TaskStatus::Running);
11037        assert_eq!(completion.reason.as_deref(), Some("Verified delivery"));
11038        let snapshot = completion.run.as_ref().unwrap();
11039        assert_eq!(snapshot.id, state.id);
11040        assert_eq!(snapshot.status, Some(RunStatus::Merged));
11041        assert_eq!(
11042            RunState::load_under(&state.id, dir.path()).unwrap().status,
11043            RunStatus::Blocked,
11044            "settlement records the actual outcome without rewriting run history"
11045        );
11046    }
11047
11048    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
11049        Candidate {
11050            index: 0,
11051            label,
11052            agent: "claude".to_owned(),
11053            branch: format!("magi/x/{label}"),
11054            worktree: PathBuf::from("/repo"),
11055            summary: summary.to_owned(),
11056            stat: String::new(),
11057            files: 0,
11058            commits: usize::from(!empty),
11059            empty,
11060            failed: failed.map(str::to_owned),
11061            verified_noop: None,
11062            duration_ms: 0,
11063            folded: false,
11064        }
11065    }
11066
11067    #[test]
11068    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
11069        let mut state = run_state(RunStatus::Blocked);
11070        state.gate = vec![
11071            CommandOutcome {
11072                command: "cargo make check".to_owned(),
11073                code: Some(0),
11074                output_tail: "ok".to_owned(),
11075                duration_ms: 0,
11076                resource_blocked: false,
11077                ..Default::default()
11078            },
11079            CommandOutcome {
11080                command: "cargo test".to_owned(),
11081                code: Some(101),
11082                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
11083                duration_ms: 0,
11084                resource_blocked: false,
11085                ..Default::default()
11086            },
11087        ];
11088        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
11089        assert!(d.contains("cargo test"), "{d}");
11090        assert!(
11091            !d.contains("cargo make check"),
11092            "a passing check is not a diagnostic: {d}"
11093        );
11094        assert!(d.contains("assertion failed"), "{d}");
11095    }
11096
11097    #[test]
11098    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
11099        let mut state = run_state(RunStatus::Blocked);
11100        state.event(
11101            "land",
11102            "stopped: the fixer produced no commit while 2 check(s) were failing \
11103             (build, lint); stopping instead of looping on an unchanged tree",
11104        );
11105        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
11106        assert!(d.contains("build"), "{d}");
11107        assert!(d.contains("lint"), "{d}");
11108        assert!(d.contains("fixer produced no commit"), "{d}");
11109    }
11110
11111    #[test]
11112    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
11113        // `describe`'s output becomes `Task::last_error` verbatim, and the
11114        // phone renders that in the same alarm-styled box an ordinary
11115        // failure gets. A bare `verified_noop` there would read exactly like
11116        // the failure this status exists to be told apart from.
11117        let state = run_state(RunStatus::VerifiedNoop);
11118        let d = describe(&state);
11119        assert!(
11120            d.contains("agent-verified no-op"),
11121            "expected the display label, not the wire spelling: {d}"
11122        );
11123        assert!(!d.contains("verified_noop"), "{d}");
11124    }
11125
11126    #[test]
11127    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
11128        let mut state = run_state(RunStatus::Failed);
11129        state.gate.push(crate::run::CommandOutcome {
11130            command: "cargo test".into(),
11131            code: Some(101),
11132            output_tail: format!(
11133                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
11134                "  41: 0x1234 - backtrace frame\n".repeat(10000)
11135            ),
11136            duration_ms: 1,
11137            resource_blocked: false,
11138            ..Default::default()
11139        });
11140        let d = diagnostic(&state).unwrap();
11141        assert!(d.contains("panicked at widget.rs:12"), "{d}");
11142        assert!(d.contains("assertion failed: widget missing"));
11143        assert!(d.contains("widget log"));
11144    }
11145
11146    #[test]
11147    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11148        // The whole point of the feature: a run held as "no candidate produced
11149        // a change" can mean the implementer actually finished the task and
11150        // only left a clean local tree behind - see AGENTS.md on this exact
11151        // failure mode. The diagnostic has to carry what the agent actually
11152        // said, not just the fact that nothing was there to judge.
11153        let mut state = run_state(RunStatus::Failed);
11154        state.candidates = vec![candidate(
11155            'A',
11156            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11157            true,
11158            None,
11159        )];
11160        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11161        assert!(d.contains("candidate A"), "{d}");
11162        assert!(d.contains("tagged v1.2.3"), "{d}");
11163    }
11164
11165    #[test]
11166    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11167        let mut state = run_state(RunStatus::Failed);
11168        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11169        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11170        assert!(d.contains("candidate A"), "{d}");
11171        assert!(d.contains("agent timed out"), "{d}");
11172    }
11173
11174    #[test]
11175    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11176        // A viable candidate existed, the gate never ran, and nothing land
11177        // said matches - `Task::last_error` is left to explain this one alone.
11178        let mut state = run_state(RunStatus::Failed);
11179        state.candidates = vec![candidate('A', "did the work", false, None)];
11180        assert!(diagnostic(&state).is_none());
11181    }
11182
11183    #[test]
11184    fn diagnostic_is_bounded_however_much_a_run_printed() {
11185        let mut state = run_state(RunStatus::Blocked);
11186        state.gate = vec![
11187            CommandOutcome {
11188                command: "cargo test".to_owned(),
11189                code: Some(101),
11190                output_tail: "x".repeat(50_000),
11191                duration_ms: 0,
11192                resource_blocked: false,
11193                ..Default::default()
11194            },
11195            CommandOutcome {
11196                command: "cargo clippy".to_owned(),
11197                code: Some(1),
11198                output_tail: "y".repeat(50_000),
11199                duration_ms: 0,
11200                resource_blocked: false,
11201                ..Default::default()
11202            },
11203        ];
11204        state.candidates = vec![
11205            candidate('A', &"z".repeat(50_000), true, None),
11206            candidate('B', &"w".repeat(50_000), true, None),
11207        ];
11208        let d = diagnostic(&state).expect("plenty here to diagnose");
11209        assert!(
11210            d.len() <= DIAGNOSTIC_MAX,
11211            "diagnostic grew to {} bytes, unbounded",
11212            d.len()
11213        );
11214    }
11215
11216    #[test]
11217    fn selected_delivery_guards_survive_recovery_failure_accounting() {
11218        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11219            let mut t = task();
11220            let mut state = run_state(status);
11221            t.pr_recovery = Some(crate::pr_recovery::Selection {
11222                url: "url".into(),
11223                branch: format!("magi/task-{}", t.id),
11224                head: "a".repeat(40),
11225                source_head: None,
11226                source_run: None,
11227                source_proof: None,
11228                disposition: Some(crate::pr_recovery::Disposition::Land),
11229                instruction: t.instruction.clone(),
11230                approved_at: Timestamp::now(),
11231            });
11232            state.pr_recovery = t.pr_recovery.clone();
11233            t.start(state.id.clone());
11234            settle_and_diagnose(
11235                &mut t,
11236                Verdict {
11237                    status,
11238                    left_pr: false,
11239                    quota_hit: false,
11240                    parked: false,
11241                    no_viable_candidates: false,
11242                },
11243                "delivery stopped",
11244                5,
11245                &state,
11246            );
11247            assert_eq!(t.status, TaskStatus::Held);
11248            let reason = t.hold_reason.as_deref().unwrap();
11249            if status == RunStatus::Ready {
11250                assert!(reason.contains("Selected PR delivery is incomplete"));
11251                assert!(t.recovery_budget.is_none());
11252            } else {
11253                assert!(reason.contains("Selected recovery stopped"));
11254                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11255            }
11256            assert!(t.pr_recovery.is_some());
11257        }
11258    }
11259
11260    #[test]
11261    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11262        let mut state = run_state(RunStatus::Voting);
11263        state.base_sync = Some(crate::run::BaseSync {
11264            tip: "base-tip".into(),
11265            behind: 3,
11266            attempts: 4,
11267            conflict: Some("base stopped".into()),
11268            already_in: None,
11269        });
11270        state.record_base_sync_stop("candidate-head");
11271        let mut t = task();
11272        t.start(state.id.clone());
11273        let verdict = Verdict {
11274            status: RunStatus::Blocked,
11275            left_pr: false,
11276            quota_hit: false,
11277            parked: false,
11278            no_viable_candidates: false,
11279        };
11280        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11281        assert_eq!(
11282            t.status,
11283            TaskStatus::Held,
11284            "unspent task attempts cannot start another competition"
11285        );
11286        let at = t.held_at;
11287        let cause = t.hold_notice_cause.clone();
11288        state.begin_pass();
11289        t.release_operator("test-resume", None);
11290        t.start(state.id.clone());
11291        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11292        assert_eq!(t.status, TaskStatus::Held);
11293        assert_eq!(t.held_at, at);
11294        assert_eq!(t.hold_notice_cause, cause);
11295    }
11296
11297    #[test]
11298    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11299        let mut state = run_state(RunStatus::Blocked);
11300        state.gate = vec![CommandOutcome {
11301            command: "cargo test".to_owned(),
11302            code: Some(101),
11303            output_tail: "assertion failed".to_owned(),
11304            duration_ms: 0,
11305            resource_blocked: false,
11306            ..Default::default()
11307        }];
11308        let verdict = Verdict {
11309            status: RunStatus::Blocked,
11310            left_pr: false,
11311            quota_hit: false,
11312            parked: false,
11313            no_viable_candidates: false,
11314        };
11315
11316        // Attempt one of two still has a retry coming: no diagnostic yet, the
11317        // task is going to run again and this run's evidence would go stale.
11318        let mut t = task();
11319        t.start("run-1".to_owned());
11320        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11321        assert_eq!(t.status, TaskStatus::Failed);
11322        assert!(t.diagnostic.is_none());
11323
11324        // Attempt two exhausts the budget: now it is held, and the
11325        // diagnostic is what `magi task show` has to say more than one line.
11326        t.start("run-2".to_owned());
11327        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11328        assert_eq!(t.status, TaskStatus::Held);
11329        let d = t.diagnostic.expect("a held task must carry its diagnostic");
11330        assert!(d.contains("cargo test"), "{d}");
11331    }
11332
11333    fn verified_noop_run_state() -> RunState {
11334        let mut state = run_state(RunStatus::VerifiedNoop);
11335        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":[]}"#;
11336        let mut c = candidate('A', summary, true, None);
11337        c.verified_noop = Some(summary.to_owned());
11338        state.candidates = vec![c];
11339        state
11340    }
11341
11342    #[test]
11343    fn a_held_task_names_the_open_question_it_is_waiting_on() {
11344        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
11345        // `magi ask` question settled Held with `hold_reason: null`, so the
11346        // notification said nothing actionable. `note_open_question` should
11347        // append the question id to whatever `handed_off` already wrote.
11348        crate::run::pin_test_home();
11349        let home = crate::run::home();
11350        let state = verified_noop_run_state();
11351        let mut q = ask::Question::new(
11352            state.id.clone(),
11353            "implement".to_owned(),
11354            "impl-A".to_owned(),
11355            "is this really a no-op?".to_owned(),
11356            String::new(),
11357            Vec::new(),
11358        );
11359        Questions::at(home.join("questions")).put(&mut q).unwrap();
11360
11361        let verdict = Verdict {
11362            status: RunStatus::VerifiedNoop,
11363            left_pr: false,
11364            quota_hit: false,
11365            parked: false,
11366            no_viable_candidates: true,
11367        };
11368        let mut t = task();
11369        t.start(state.id.clone());
11370        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11371
11372        assert_eq!(t.status, TaskStatus::Held);
11373        let reason = t.hold_reason.expect("a held task must record why");
11374        assert!(
11375            reason.starts_with("run ended agent-verified no-op"),
11376            "the original settle reason must survive unchanged: {reason}"
11377        );
11378        assert!(
11379            reason.contains(q.short()),
11380            "the open question's id must be named so the notice is actionable: {reason}"
11381        );
11382    }
11383
11384    #[test]
11385    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11386        crate::run::pin_test_home();
11387        let state = verified_noop_run_state();
11388
11389        let verdict = Verdict {
11390            status: RunStatus::VerifiedNoop,
11391            left_pr: false,
11392            quota_hit: false,
11393            parked: false,
11394            no_viable_candidates: true,
11395        };
11396        let mut t = task();
11397        t.start(state.id.clone());
11398        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11399
11400        assert_eq!(t.status, TaskStatus::Held);
11401        assert_eq!(
11402            t.hold_reason.as_deref(),
11403            Some("run ended agent-verified no-op"),
11404            "nothing to append when the question was already answered or never asked"
11405        );
11406    }
11407
11408    #[test]
11409    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11410        crate::run::pin_test_home();
11411
11412        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
11413        // regression prose instead of valid structured evidence.
11414        let mut bad = run_state(RunStatus::VerifiedNoop);
11415        let mut c = candidate(
11416            'A',
11417            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11418            true,
11419            None,
11420        );
11421        c.verified_noop = Some("Not established.".to_owned());
11422        bad.candidates = vec![c];
11423
11424        let mut t = task();
11425        t.start(bad.id.clone());
11426        let verdict = Verdict {
11427            status: RunStatus::VerifiedNoop,
11428            left_pr: false,
11429            quota_hit: true,
11430            parked: false,
11431            no_viable_candidates: true,
11432        };
11433        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11434        assert_eq!(
11435            t.status,
11436            TaskStatus::Failed,
11437            "inconsistent verified_noop must retry as Failed when attempts remain"
11438        );
11439        assert_eq!(t.attempts, 1);
11440        assert_eq!(
11441            t.last_error.as_deref(),
11442            Some("no-change result lacks verified evidence")
11443        );
11444        assert!(t.hold_reason.is_none());
11445
11446        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
11447        // attempts exhausted holds as `failed`, never `verified_noop`, and
11448        // never auto-closes to `Done`.
11449        let mut t_exhausted = task();
11450        t_exhausted.start(bad.id.clone());
11451        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11452        assert_eq!(t_exhausted.status, TaskStatus::Held);
11453        assert_eq!(t_exhausted.attempts, 1);
11454        assert_eq!(
11455            t_exhausted
11456                .hold_notice_cause
11457                .as_ref()
11458                .map(|c| c.stage.as_str()),
11459            Some("failed"),
11460            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11461        );
11462        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11463        assert!(
11464            !diag.contains("agent-verified no-op"),
11465            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11466        );
11467        assert!(diag.contains("Not established"), "{diag}");
11468    }
11469
11470    #[test]
11471    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11472        let mut state = verified_noop_run_state();
11473        let summary = state.candidates[0].summary.clone();
11474        state.candidates[0].summary = "Already satisfied.".to_owned();
11475        assert!(state.all_candidates_verified_noop());
11476
11477        state.candidates[0].summary = summary;
11478        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11479        assert!(!state.all_candidates_verified_noop());
11480    }
11481
11482    #[test]
11483    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11484        crate::run::pin_test_home();
11485        let mut first = run_state(RunStatus::Blocked);
11486        first.id = "20260101-000000-sup1".to_owned();
11487        first.save().unwrap();
11488        let mut second = run_state(RunStatus::Merged);
11489        second.id = "20260101-000000-sup2".to_owned();
11490        second.save().unwrap();
11491
11492        let mut t = task();
11493        t.runs = vec![first.id.clone(), second.id.clone()];
11494        t.status = TaskStatus::Done;
11495
11496        supersede_prior_runs(&t, &crate::run::home());
11497
11498        assert_eq!(
11499            RunState::load(&first.id).unwrap().status,
11500            RunStatus::Superseded,
11501            "the first attempt's Blocked no longer needs anyone's attention"
11502        );
11503        assert_eq!(
11504            RunState::load(&second.id).unwrap().status,
11505            RunStatus::Merged,
11506            "the run that actually succeeded is left exactly as it was"
11507        );
11508    }
11509
11510    #[test]
11511    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11512        // `is_working_on` alone only proves a *daemon* claim; a `magi run
11513        // --resume` invoked by hand outside the daemon never touches
11514        // `daemon.json` at all, so it would look identical to a genuinely
11515        // idle run without also consulting `RunState::liveness`, which reads
11516        // this run's own recorded `driver_pid` instead.
11517        crate::run::pin_test_home();
11518        let mut first = run_state(RunStatus::Blocked);
11519        first.id = "20260101-000000-sup9".to_owned();
11520        // This test process's own pid: guaranteed alive without needing a
11521        // real second process or daemon.
11522        first.driver_pid = Some(std::process::id());
11523        first.driver_started_at = Some(
11524            crate::proc::process_started_at(std::process::id())
11525                .expect("this test process's own start time must be queryable"),
11526        );
11527        first.save().unwrap();
11528        let mut second = run_state(RunStatus::Merged);
11529        second.id = "20260101-000000-supa".to_owned();
11530        second.save().unwrap();
11531
11532        let mut t = task();
11533        t.runs = vec![first.id.clone(), second.id.clone()];
11534        t.status = TaskStatus::Done;
11535
11536        supersede_prior_runs(&t, &crate::run::home());
11537
11538        assert_eq!(
11539            RunState::load(&first.id).unwrap().status,
11540            RunStatus::Blocked,
11541            "a live driver_pid means something is still actually working this run, \
11542             even though no daemon claims it - rewriting under it would just be \
11543             undone the next time that process saves"
11544        );
11545    }
11546
11547    #[test]
11548    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11549        // The first resweep must skip a still-live attempt exactly like
11550        // `supersede_prior_runs` itself does; a later resweep, once that
11551        // process is no longer actually driving it, is what closes the gap
11552        // `supersede_prior_runs` alone leaves - a task only ever reaches
11553        // `Done` once, so nothing else would ever look at this run again.
11554        let dir = tempfile::tempdir().unwrap();
11555        let home = dir.path().to_path_buf();
11556        let queue = Queue::at(dir.path().join("queue"));
11557
11558        let mut first = run_state(RunStatus::Blocked);
11559        first.id = "20260101-000000-supd".to_owned();
11560        first.driver_pid = Some(std::process::id());
11561        first.driver_started_at = Some(
11562            crate::proc::process_started_at(std::process::id())
11563                .expect("this test process's own start time must be queryable"),
11564        );
11565        first.save_under(&home).unwrap();
11566        let mut second = run_state(RunStatus::Merged);
11567        second.id = "20260101-000000-supe".to_owned();
11568        second.save_under(&home).unwrap();
11569
11570        let mut t = task();
11571        t.runs = vec![first.id.clone(), second.id.clone()];
11572        t.status = TaskStatus::Done;
11573        queue.put(&mut t).unwrap();
11574
11575        resweep_superseded_attempts(&queue, &home);
11576        assert_eq!(
11577            RunState::load_under(&first.id, &home).unwrap().status,
11578            RunStatus::Blocked,
11579            "still live on the first pass, so still untouched"
11580        );
11581
11582        // Stand in for the manual process no longer being the one driving
11583        // this run: same pid (this test process really is still alive), but
11584        // an identity marker that no longer matches it - see
11585        // `RunState::liveness`'s own doc for why a mismatched
11586        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
11587        let mut stale = RunState::load_under(&first.id, &home).unwrap();
11588        stale.driver_started_at = Some("1".to_owned());
11589        stale.save_under(&home).unwrap();
11590
11591        resweep_superseded_attempts(&queue, &home);
11592        assert_eq!(
11593            RunState::load_under(&first.id, &home).unwrap().status,
11594            RunStatus::Superseded,
11595            "the second pass catches up what the first one correctly skipped"
11596        );
11597    }
11598
11599    #[test]
11600    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11601        crate::run::pin_test_home();
11602        let mut first = run_state(RunStatus::Blocked);
11603        first.id = "20260101-000000-sup3".to_owned();
11604        first.save().unwrap();
11605        let mut second = run_state(RunStatus::Blocked);
11606        second.id = "20260101-000000-sup4".to_owned();
11607        second.save().unwrap();
11608
11609        let mut t = task();
11610        t.runs = vec![first.id.clone(), second.id.clone()];
11611        // Still retrying: nothing about this task's story is settled yet, so
11612        // neither Blocked run may be relabelled, even though a later attempt
11613        // already exists.
11614        t.status = TaskStatus::Failed;
11615
11616        supersede_prior_runs(&t, &crate::run::home());
11617
11618        assert_eq!(
11619            RunState::load(&first.id).unwrap().status,
11620            RunStatus::Blocked
11621        );
11622        assert_eq!(
11623            RunState::load(&second.id).unwrap().status,
11624            RunStatus::Blocked
11625        );
11626    }
11627
11628    #[test]
11629    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11630        // `magi task done` (or the API's equivalent) can close a task with no
11631        // run of its own ever having succeeded - there is nothing here that
11632        // counts as "the attempt that finished it", so nothing is rewritten.
11633        crate::run::pin_test_home();
11634        let mut first = run_state(RunStatus::Blocked);
11635        first.id = "20260101-000000-sup5".to_owned();
11636        first.save().unwrap();
11637
11638        let mut t = task();
11639        t.runs = vec![first.id.clone()];
11640        t.status = TaskStatus::Done;
11641
11642        supersede_prior_runs(&t, &crate::run::home());
11643
11644        assert_eq!(
11645            RunState::load(&first.id).unwrap().status,
11646            RunStatus::Blocked,
11647            "a single-attempt task has no earlier run to supersede"
11648        );
11649    }
11650
11651    #[test]
11652    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11653        for status in [
11654            RunStatus::Blocked,
11655            RunStatus::Stalled,
11656            RunStatus::Failed,
11657            RunStatus::Ready,
11658            RunStatus::Merged,
11659        ] {
11660            let dir = tempfile::tempdir().unwrap();
11661            let home = dir.path();
11662            let mut first = run_state(RunStatus::Blocked);
11663            first.id = "20260101-000000-supb".to_owned();
11664            first.save_under(home).unwrap();
11665            let mut second = run_state(status);
11666            second.id = "20260101-000000-supc".to_owned();
11667            second.save_under(home).unwrap();
11668
11669            let mut t = task();
11670            t.runs = vec![first.id.clone(), second.id.clone()];
11671            t.hold_manual(Some("Unmerged work remains".into()));
11672            let mut context = CompletionContext::new(
11673                CompletionActor::Cli,
11674                Some("Discard the unmerged attempts".into()),
11675                home,
11676                &t,
11677            );
11678            context.discard = true;
11679            t.succeed(context);
11680            assert_eq!(t.completion_history.len(), 1);
11681
11682            supersede_prior_runs(&t, home);
11683
11684            assert_eq!(
11685                RunState::load_under(&first.id, home).unwrap().status,
11686                RunStatus::Blocked,
11687                "an audited manual close is not proof the earlier work landed"
11688            );
11689            assert_eq!(
11690                RunState::load_under(&second.id, home).unwrap().status,
11691                status,
11692                "the latest attempt retains its actual outcome"
11693            );
11694        }
11695    }
11696
11697    #[test]
11698    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11699        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
11700        // to look" - `Failed` and `VerifiedNoop` are already their own
11701        // terminal answers and must not be relabelled into a third one.
11702        crate::run::pin_test_home();
11703        let mut failed = run_state(RunStatus::Failed);
11704        failed.id = "20260101-000000-sup6".to_owned();
11705        failed.save().unwrap();
11706        let mut noop = run_state(RunStatus::VerifiedNoop);
11707        noop.id = "20260101-000000-sup7".to_owned();
11708        noop.save().unwrap();
11709        let mut winner = run_state(RunStatus::Ready);
11710        winner.id = "20260101-000000-sup8".to_owned();
11711        winner.save().unwrap();
11712
11713        let mut t = task();
11714        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11715        t.status = TaskStatus::Done;
11716
11717        supersede_prior_runs(&t, &crate::run::home());
11718
11719        assert_eq!(
11720            RunState::load(&failed.id).unwrap().status,
11721            RunStatus::Failed
11722        );
11723        assert_eq!(
11724            RunState::load(&noop.id).unwrap().status,
11725            RunStatus::VerifiedNoop
11726        );
11727    }
11728
11729    fn approval_question(run: &str) -> ask::Question {
11730        ask::Question::new(
11731            run.to_owned(),
11732            land::APPROVAL_NODE.to_owned(),
11733            "land".to_owned(),
11734            "merge?".to_owned(),
11735            String::new(),
11736            vec!["merge".to_owned(), "hold".to_owned()],
11737        )
11738    }
11739
11740    #[test]
11741    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11742        crate::run::pin_test_home();
11743        let mut state = run_state(RunStatus::Landing);
11744        state.id = "20260101-000000-fre1".to_owned();
11745        state.parked = true;
11746        state.save().unwrap();
11747        ask::Questions::open()
11748            .put(&mut approval_question(&state.id))
11749            .unwrap();
11750
11751        let mut t = task();
11752        t.runs.push(state.id.clone());
11753        assert_eq!(
11754            land_resume_state(&t),
11755            LandResume::StillWaiting,
11756            "nobody has answered and the timeout has not passed"
11757        );
11758    }
11759
11760    #[test]
11761    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11762        crate::run::pin_test_home();
11763        let mut state = run_state(RunStatus::Gating);
11764        state.id = "20260101-000000-gt01".to_owned();
11765        state.parked = true;
11766        state.config.graph.answer_timeout = 60;
11767        state.github_text = Some(crate::run::GithubTextAsk {
11768            rewrite: None,
11769            fingerprint: "f".into(),
11770            title: true,
11771            body: false,
11772            categories: vec!["title-language".into()],
11773            question: None,
11774            asks: 1,
11775            resolved: false,
11776            chosen_title: None,
11777            choice: None,
11778            publication: None,
11779        });
11780        state.save().unwrap();
11781        let store = ask::Questions::open();
11782        let mut q = ask::Question::new(
11783            state.id.clone(),
11784            crate::github_text::ASK_NODE.to_owned(),
11785            crate::github_text::ASK_SEAT.to_owned(),
11786            "s".into(),
11787            String::new(),
11788            vec!["use fallback".into()],
11789        );
11790        store.put(&mut q).unwrap();
11791        let mut t = task();
11792        t.runs.push(state.id.clone());
11793        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11794        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11795        store.put(&mut q).unwrap();
11796        assert_eq!(land_resume_state(&t), LandResume::Ready);
11797        assert!(!store.get(&q.id).unwrap().status.open());
11798        // Once decided, a parked run is an ordinary candidate again.
11799        state.github_text.as_mut().unwrap().resolved = true;
11800        state.save().unwrap();
11801        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11802    }
11803
11804    #[test]
11805    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11806        // `ask::ask_and_wait`'s own deadline used to retire a question
11807        // nobody answered; land's approval bypasses that wait (see
11808        // `land::approval_gate`), so this is now the only place
11809        // `graph.answer_timeout` is enforced for a land approval at all.
11810        crate::run::pin_test_home();
11811        let mut state = run_state(RunStatus::Landing);
11812        state.id = "20260101-000000-exp1".to_owned();
11813        state.parked = true;
11814        state.config.graph.answer_timeout = 60;
11815        state.save().unwrap();
11816
11817        let store = ask::Questions::open();
11818        let mut q = approval_question(&state.id);
11819        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11820        store.put(&mut q).unwrap();
11821
11822        let mut t = task();
11823        t.runs.push(state.id.clone());
11824        assert_eq!(
11825            land_resume_state(&t),
11826            LandResume::Ready,
11827            "an expired question must not be waited on forever"
11828        );
11829
11830        let after = store.get(&q.id).unwrap();
11831        assert!(
11832            !after.status.open(),
11833            "the question is abandoned, not silently ignored"
11834        );
11835        assert!(
11836            after.resolution().is_none(),
11837            "an abandoned question is not read as a decision"
11838        );
11839    }
11840
11841    #[test]
11842    fn reclaim_settles_a_running_task_against_its_last_run() {
11843        let mut t = task();
11844        t.start("20260904-000000-4043".to_owned());
11845        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11846        assert_eq!(
11847            t.status,
11848            TaskStatus::Held,
11849            "an unlanded Ready run settles to held awaiting landing rather than staying `running`"
11850        );
11851        assert!(t.has_awaiting_landing_cause());
11852        let mut merged = task();
11853        merged.start("20260904-000000-4044".to_owned());
11854        reclaim(&mut merged, Some(run_state(RunStatus::Merged)), 2, "en");
11855        assert_eq!(
11856            merged.status,
11857            TaskStatus::Done,
11858            "a merged run closes the task cleanly"
11859        );
11860    }
11861
11862    #[test]
11863    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11864        let dir = tempfile::tempdir().unwrap();
11865        let queue = Queue::at(dir.path().join("queue"));
11866        let mut task = task();
11867        let mut run = run_state(RunStatus::Blocked);
11868        run.reserve_under(dir.path()).unwrap();
11869        run.driver_exited = true;
11870        run.save_under(dir.path()).unwrap();
11871        queue.put(&mut task).unwrap();
11872        let stale = task.clone();
11873        task.resume_override = Some(crate::queue::OperatorResume {
11874            question_id: "pending-resume".into(),
11875            at: Timestamp::now(),
11876            conductor_rehold: None,
11877            forced: true,
11878            pinned_run: Some(run.id.clone()),
11879        });
11880        task.start(run.id.clone());
11881        queue.put(&mut task).unwrap();
11882        // Discard every in-memory handoff, as a worker death before execute does.
11883        let mut recovered = queue.get(&task.id).unwrap();
11884        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11885        reclaim(&mut recovered, Some(disk), 2, "en");
11886        queue.put(&mut recovered).unwrap();
11887        assert!(recovered.resume_override.is_none());
11888        assert_eq!(
11889            recovered.dispatched_resumes.get("pending-resume"),
11890            Some(&run.id)
11891        );
11892        let mut stale = stale;
11893        queue.put(&mut stale).unwrap();
11894        assert_eq!(
11895            stale.dispatched_resumes, recovered.dispatched_resumes,
11896            "a stale task writer cannot erase dispatch ownership"
11897        );
11898        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11899        assert!(resumed.decision_starts.is_empty());
11900        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11901        assert!(
11902            resumed.decision_starts.is_empty(),
11903            "handoff is not execution proof"
11904        );
11905        resumed.begin_pass();
11906        resumed.save_under(dir.path()).unwrap();
11907        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11908        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11909        disk.carry_dispatched_resumes(&recovered);
11910        disk.begin_pass();
11911        assert_eq!(
11912            disk.decision_starts.get("pending-resume"),
11913            Some(&0),
11914            "later execution must preserve the original pass receipt"
11915        );
11916    }
11917
11918    #[test]
11919    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11920        let mut t = task();
11921        t.start("20260904-000000-4043".to_owned());
11922        t.last_error = Some("earlier trouble".to_owned());
11923        let mut state = run_state(RunStatus::Judging);
11924        state.parked = true;
11925        reclaim(&mut t, Some(state), 1, "en");
11926        assert_eq!(t.status, TaskStatus::Parked);
11927        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11928        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11929        assert!(t.park_reason.is_some());
11930        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11931        assert!(!t.fresh_start);
11932        assert!(t.status.runnable());
11933    }
11934
11935    #[test]
11936    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11937        let mut t = task();
11938        t.start("20260904-000000-4043".to_owned());
11939        t.last_error = Some("earlier trouble".to_owned());
11940        settle(
11941            &mut t,
11942            Verdict {
11943                status: RunStatus::Judging,
11944                left_pr: false,
11945                quota_hit: false,
11946                parked: true,
11947                no_viable_candidates: false,
11948            },
11949            "parked after `judging`",
11950            1,
11951        );
11952        assert_eq!(t.status, TaskStatus::Parked);
11953        assert_eq!(t.attempts, 0);
11954        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11955        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11956        assert_eq!(t.schema, crate::queue::SCHEMA);
11957        assert!(
11958            crate::notices::task_held(&t).is_none(),
11959            "a park is not news"
11960        );
11961        t.start("20260904-000000-4043".to_owned());
11962        assert_eq!(t.park_reason, None);
11963    }
11964
11965    #[test]
11966    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11967        // A blocked run with attempts left goes back to `Failed`, exactly as
11968        // it would from `attempt` itself - `reclaim` must not invent a second
11969        // policy for a task a daemon merely stopped without reporting.
11970        let mut t = task();
11971        t.start("20260904-000000-4043".to_owned());
11972        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11973        assert_eq!(t.status, TaskStatus::Failed);
11974        assert!(t.status.runnable());
11975    }
11976
11977    #[test]
11978    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11979        let mut t = task();
11980        t.start("20260904-000000-4043".to_owned());
11981        assert_eq!(t.attempts, 1);
11982        let mut run = run_state(RunStatus::Implementing);
11983        run.id = "20260904-000000-4043".to_owned();
11984        run.begin_pass();
11985        let cause = crate::run::ParkCause::Upgrade {
11986            from: "0.121.0".to_owned(),
11987            to: Some("0.121.1".to_owned()),
11988        };
11989        run.end_pass_parked(cause.clone());
11990        run.parked = true;
11991        let verdict = Verdict {
11992            status: run.status,
11993            left_pr: false,
11994            quota_hit: false,
11995            parked: true,
11996            no_viable_candidates: false,
11997        };
11998        // A crash after the checkpoint but before queue settlement must
11999        // recover exactly the same scheduling evidence and refund.
12000        let mut orphan = t.clone();
12001        reclaim(&mut orphan, Some(run.clone()), 2, "en");
12002        assert_eq!(orphan.status, TaskStatus::Parked);
12003        assert_eq!(orphan.attempts, 0);
12004        assert_eq!(
12005            orphan.upgrade_resume_key(),
12006            Some((run.passes[0].started_at, orphan.id.as_str()))
12007        );
12008        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
12009        assert_eq!(t.attempts, 0);
12010        assert_eq!(t.passes.len(), 1);
12011        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
12012        assert_eq!(t.passes[0].parked, Some(cause));
12013        assert_eq!(t.passes[0].pass_index, 0);
12014        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
12015        assert!(t.upgrade_resume_key().is_some());
12016
12017        // A resumed pass that then fails spends its attempt, and the earlier
12018        // pass's entry is untouched.
12019        t.start("20260904-000000-4043".to_owned());
12020        run.begin_pass();
12021        run.status = RunStatus::Failed;
12022        let verdict = Verdict {
12023            status: RunStatus::Failed,
12024            left_pr: false,
12025            quota_hit: false,
12026            parked: false,
12027            no_viable_candidates: false,
12028        };
12029        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
12030        assert_eq!(t.passes.len(), 2);
12031        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
12032        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
12033        assert_eq!(t.passes[1].pass_index, 1);
12034        assert_eq!(t.attempts, 1);
12035    }
12036
12037    #[test]
12038    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
12039        let mut t = task();
12040        t.start("20260904-000000-4043".to_owned());
12041        reclaim(&mut t, None, 2, "en");
12042        assert_eq!(t.status, TaskStatus::Held);
12043        assert!(
12044            t.last_error
12045                .as_deref()
12046                .is_some_and(|e| e.contains("running")),
12047            "the operator needs to know why this task was held"
12048        );
12049    }
12050
12051    #[test]
12052    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
12053        let dir = tempfile::tempdir().unwrap();
12054        let queue = Queue::at(dir.path().to_path_buf());
12055        let mut task = task();
12056        let run = "20261124-000000-dead";
12057        task.link_run(run);
12058        task.attempts = 2;
12059        task.status = TaskStatus::Running;
12060        task.sync_only = Some(crate::base_sync_only::Request {
12061            run: run.into(),
12062            at: Timestamp::now(),
12063        });
12064        queue.put(&mut task).unwrap();
12065        assert_eq!(
12066            reclaim_orphaned_running(&queue, 3, &Default::default()),
12067            vec![task.id.clone()]
12068        );
12069        let saved = queue.get(&task.id).unwrap();
12070        assert_eq!(saved.status, TaskStatus::Held);
12071        assert_eq!(saved.attempts, 2);
12072        assert_eq!(saved.execution_runs(), [run]);
12073        assert!(
12074            saved
12075                .last_error
12076                .unwrap()
12077                .contains("verification was not allowed")
12078        );
12079        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
12080    }
12081
12082    #[test]
12083    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
12084        use crate::base_sync_only::{Outcome, Pass, Request};
12085
12086        let mut state = run_state(RunStatus::Blocked);
12087        let mut task = task();
12088        let request = Request {
12089            run: state.id.clone(),
12090            at: Timestamp::now(),
12091        };
12092        task.start(state.id.clone());
12093        task.sync_only = Some(request.clone());
12094        // Dedicated dispatch saves Running with the pre-pass attempt count.
12095        task.attempts = 2;
12096        let mut pass = Pass::new(request, &state);
12097        pass.result = Outcome::AlreadyCurrent;
12098        state.sync_only_passes.push(pass);
12099        state.begin_pass();
12100
12101        reclaim(&mut task, Some(state), 3, "en");
12102
12103        assert_eq!(task.status, TaskStatus::Held);
12104        assert_eq!(task.attempts, 2);
12105        assert!(task.sync_only.is_none());
12106        let detail = task.hold_reason.unwrap();
12107        assert!(detail.contains("HEAD already contains the base"));
12108        assert!(detail.contains("verification was not allowed"));
12109    }
12110
12111    #[test]
12112    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
12113        let dir = tempfile::tempdir().unwrap();
12114        let queue = Queue::at(dir.path().to_path_buf());
12115
12116        // No run recorded, so this never has to touch `RunState::load`.
12117        let mut orphaned = task();
12118        orphaned.id = "20260904-000000-orph".to_owned();
12119        orphaned.status = TaskStatus::Running;
12120        orphaned.attempts = 1;
12121        queue.put(&mut orphaned).unwrap();
12122
12123        let mut alive = task();
12124        alive.id = "20260904-000000-live".to_owned();
12125        alive.status = TaskStatus::Running;
12126        alive.attempts = 1;
12127        queue.put(&mut alive).unwrap();
12128        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
12129
12130        let mut queued = task();
12131        queued.id = "20260904-000000-wait".to_owned();
12132        queue.put(&mut queued).unwrap();
12133
12134        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
12135        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
12136
12137        assert_eq!(
12138            queue.get(&orphaned.id).unwrap().status,
12139            TaskStatus::Held,
12140            "nothing was driving it and there was no run to recover"
12141        );
12142        assert_eq!(
12143            queue.get(&alive.id).unwrap().status,
12144            TaskStatus::Running,
12145            "a live claim must protect the task it belongs to"
12146        );
12147        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
12148    }
12149
12150    /// Read a run.json back from an explicit `home`, the same way
12151    /// `reclaim_abandoned_runs` itself does - never through the
12152    /// process-global `RunState::load`, which this test's own `home` (an
12153    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
12154    /// use at all.
12155    fn read_run_under(home: &Path, id: &str) -> RunState {
12156        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12157        serde_json::from_str(&body).unwrap()
12158    }
12159
12160    #[test]
12161    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12162        let dir = tempfile::tempdir().unwrap();
12163        let home = dir.path().to_path_buf();
12164        let now = Timestamp::now();
12165        let overrun_seat = || crate::run::ActiveSeat {
12166            node: "implement".to_owned(),
12167            started_at: now - jiff::SignedDuration::new(21_000, 0),
12168            timeout_secs: 3_600,
12169            attempt: 0,
12170            task: None,
12171            command: None,
12172            index: None,
12173            total: None,
12174        };
12175
12176        let mut dead = run_state(RunStatus::Implementing);
12177        dead.id = "20260101-000000-dead".to_owned();
12178        dead.active.insert("impl-A".to_owned(), overrun_seat());
12179        // A `driver_pid` the injected query below confirms gone outright —
12180        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
12181        dead.driver_pid = Some(4242);
12182        dead.save_under(&home).unwrap();
12183
12184        // Same shape, but a live daemon's heartbeat names it: must be left
12185        // exactly alone, however far past its own timeout the seat sits.
12186        let mut alive = run_state(RunStatus::Implementing);
12187        alive.id = "20260101-000000-aliv".to_owned();
12188        alive.active.insert("impl-A".to_owned(), overrun_seat());
12189        alive.save_under(&home).unwrap();
12190        let mut status = Status::new();
12191        status.current = vec![Current {
12192            worker: None,
12193            task: "20260101-000000-task".to_owned(),
12194            run: alive.id.clone(),
12195        }];
12196        write_status_to(&home.join("daemon.json"), &status).unwrap();
12197
12198        // The abandoned seat left an open question behind: nobody is left to
12199        // read an answer once the run is failed, and this must not wait for
12200        // some later daemon startup's own sweep to notice that.
12201        let questions = Questions::at(home.join("questions"));
12202        let mut q = ask::Question::new(
12203            dead.id.clone(),
12204            "implement".to_owned(),
12205            "impl-A".to_owned(),
12206            "Which storage backend?".to_owned(),
12207            String::new(),
12208            vec!["SQLite".to_owned(), "Redis".to_owned()],
12209        );
12210        questions.put(&mut q).unwrap();
12211
12212        let abandoned = reclaim_abandoned_runs_with(
12213            &home,
12214            now,
12215            |pid| if pid == 4242 { Some(false) } else { None },
12216            |_| panic!("a query answering Dead outright needs no identity corroboration"),
12217        );
12218        assert_eq!(abandoned, vec![dead.id.clone()]);
12219
12220        let reloaded = read_run_under(&home, &dead.id);
12221        assert_eq!(reloaded.status, RunStatus::Failed);
12222        assert!(reloaded.active.is_empty());
12223        assert!(
12224            !questions.get(&q.id).unwrap().status.open(),
12225            "the failed run's own open question must be settled in the same pass"
12226        );
12227
12228        let still_alive = read_run_under(&home, &alive.id);
12229        assert_eq!(
12230            still_alive.status,
12231            RunStatus::Implementing,
12232            "a live daemon's claim protects it"
12233        );
12234        assert!(!still_alive.active.is_empty());
12235    }
12236
12237    /// The exact shape a review round flagged as broken: `magi serve` running
12238    /// in this same `home` scans *every* run on disk, including a manual
12239    /// `magi review` / `magi run` this daemon never started and that
12240    /// therefore claims no heartbeat of its own. Before this scan asked
12241    /// `liveness` rather than just `is_working_on`, a manual run whose active
12242    /// seat merely ran a little past its own timeout — the CLI finishing up,
12243    /// its result still being collected — got wiped and failed by a daemon
12244    /// that had nothing to do with it, out from under a process that was
12245    /// still very much running.
12246    #[test]
12247    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12248        let dir = tempfile::tempdir().unwrap();
12249        let home = dir.path().to_path_buf();
12250        let now = Timestamp::now();
12251
12252        let mut manual = run_state(RunStatus::Reviewing);
12253        manual.id = "20260101-000000-manl".to_owned();
12254        manual.active.insert(
12255            "review-1".to_owned(),
12256            crate::run::ActiveSeat {
12257                node: "review".to_owned(),
12258                started_at: now - jiff::SignedDuration::new(21_000, 0),
12259                timeout_secs: 3_600,
12260                attempt: 0,
12261                task: None,
12262                command: None,
12263                index: None,
12264                total: None,
12265            },
12266        );
12267        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
12268        // but a real, still-running process: `liveness` must corroborate this
12269        // as `Live`, not read the missing daemon claim as death.
12270        manual.driver_pid = Some(4242);
12271        manual.driver_started_at = Some("1790000000".to_owned());
12272        manual.save_under(&home).unwrap();
12273
12274        let abandoned = reclaim_abandoned_runs_with(
12275            &home,
12276            now,
12277            |pid| if pid == 4242 { Some(true) } else { None },
12278            |pid| {
12279                if pid == 4242 {
12280                    Some("1790000000".to_owned())
12281                } else {
12282                    None
12283                }
12284            },
12285        );
12286        assert!(
12287            abandoned.is_empty(),
12288            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12289        );
12290
12291        let reloaded = read_run_under(&home, &manual.id);
12292        assert_eq!(reloaded.status, RunStatus::Reviewing);
12293        assert!(!reloaded.active.is_empty());
12294    }
12295
12296    #[test]
12297    fn an_already_claimed_task_is_skipped_rather_than_failed() {
12298        let dir = tempfile::tempdir().unwrap();
12299        let queue = Queue::at(dir.path().to_path_buf());
12300        let mut only = task();
12301        queue.put(&mut only).unwrap();
12302
12303        let _elsewhere = queue.claim(&only.id).unwrap();
12304        let candidates = runnable(&queue);
12305        assert_eq!(candidates.len(), 1, "the task is still runnable");
12306        assert!(
12307            queue.claim(&candidates[0].id).is_err(),
12308            "the loop cannot take a claim somebody else holds"
12309        );
12310
12311        let after = queue.get(&only.id).unwrap();
12312        assert_eq!(after.status, TaskStatus::Queued);
12313        assert_eq!(
12314            after.attempts, 0,
12315            "losing the race is not an attempt at the task"
12316        );
12317        assert_eq!(after.last_error, None);
12318    }
12319
12320    #[test]
12321    fn the_status_file_round_trips_and_its_heartbeat_advances() {
12322        let dir = tempfile::tempdir().unwrap();
12323        let path = dir.path().join("daemon.json");
12324
12325        let mut status = Status::new();
12326        status.idle = false;
12327        status.completed = 7;
12328        status.current = vec![Current {
12329            worker: None,
12330            task: "20260902-000000-t111".to_owned(),
12331            run: "20260902-000001-r111".to_owned(),
12332        }];
12333        write_status_to(&path, &status).unwrap();
12334        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12335        assert_eq!(first.schema, SCHEMA);
12336        assert_eq!(first.pid, std::process::id());
12337        assert!(!first.idle);
12338        assert_eq!(first.completed, 7);
12339        assert_eq!(first.current, status.current);
12340        assert!(
12341            !path.with_extension("json.tmp").exists(),
12342            "the temp file is renamed, not left behind"
12343        );
12344
12345        std::thread::sleep(Duration::from_millis(5));
12346        status.updated_at = Timestamp::now();
12347        status.polls = 3;
12348        write_status_to(&path, &status).unwrap();
12349        let second: Status =
12350            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12351        assert!(
12352            second.updated_at > first.updated_at,
12353            "a reader can only detect staleness if the heartbeat moves"
12354        );
12355        assert_eq!(
12356            second.started_at, first.started_at,
12357            "the start time is not a heartbeat"
12358        );
12359        assert_eq!(second.polls, 3);
12360    }
12361
12362    #[test]
12363    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12364        let dir = tempfile::tempdir().unwrap();
12365
12366        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12367
12368        let mut status = Status::new();
12369        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12370        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12371        let stale = read_status(dir.path()).unwrap();
12372        assert!(
12373            !stale.running(Timestamp::now()),
12374            "a minute without a heartbeat is a dead daemon, not a busy one"
12375        );
12376        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12377
12378        status.updated_at = Timestamp::now();
12379        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12380        let fresh = read_status(dir.path()).unwrap();
12381        assert!(fresh.running(Timestamp::now()));
12382    }
12383
12384    #[test]
12385    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12386        let dir = tempfile::tempdir().unwrap();
12387        let now = Timestamp::now();
12388        let mine = "20260903-080619-01c2";
12389
12390        assert!(
12391            !is_working_on(dir.path(), mine, now),
12392            "no status file means nobody is working on anything"
12393        );
12394
12395        let mut status = Status::new();
12396        status.current = vec![Current {
12397            worker: None,
12398            task: "20260903-080340-0167".to_owned(),
12399            run: mine.to_owned(),
12400        }];
12401        status.updated_at = now;
12402        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12403        assert!(is_working_on(dir.path(), mine, now));
12404        assert!(
12405            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12406            "a daemon busy with one run is not working on another"
12407        );
12408
12409        // A killed daemon stops writing heartbeats but leaves the file behind
12410        // naming the run it died in. That run must not be undeletable forever.
12411        status.updated_at = now - jiff::SignedDuration::from_secs(600);
12412        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12413        assert!(
12414            !is_working_on(dir.path(), mine, now),
12415            "a stale heartbeat is a dead daemon, so its run is a leftover"
12416        );
12417    }
12418
12419    #[test]
12420    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12421        let dir = tempfile::tempdir().unwrap();
12422        let now = Timestamp::now();
12423
12424        assert!(
12425            !is_working_on_short(dir.path(), "01c2", now),
12426            "no status file means nobody is working on anything"
12427        );
12428
12429        let mut status = Status::new();
12430        status.current = vec![Current {
12431            worker: None,
12432            task: "20260903-080340-0167".to_owned(),
12433            run: "20260903-080619-01c2".to_owned(),
12434        }];
12435        status.updated_at = now;
12436        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12437        assert!(
12438            is_working_on_short(dir.path(), "01c2", now),
12439            "the run's short id is the last block of its full id"
12440        );
12441        assert!(
12442            !is_working_on_short(dir.path(), "3cbf", now),
12443            "a daemon busy with one worktree bay is not working on another"
12444        );
12445    }
12446
12447    #[test]
12448    fn a_newer_status_file_still_yields_a_reading() {
12449        let dir = tempfile::tempdir().unwrap();
12450        // A field this build has never heard of must not turn the reading into
12451        // nothing at all; that is the whole reason the reader is permissive.
12452        std::fs::write(
12453            dir.path().join("daemon.json"),
12454            serde_json::json!({
12455                "schema": 2,
12456                "updated_at": Timestamp::now().to_string(),
12457                "idle": true,
12458                "surprise": { "nested": [1, 2, 3] },
12459            })
12460            .to_string(),
12461        )
12462        .unwrap();
12463
12464        let reading = read_status(dir.path()).expect("a forward-compatible read");
12465        assert!(reading.running(Timestamp::now()));
12466        assert!(reading.idle);
12467        assert!(reading.current.is_empty());
12468    }
12469
12470    #[test]
12471    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12472        // A daemon started before `current` became a list keeps writing this
12473        // shape on every heartbeat until it is restarted. A rolling upgrade
12474        // - a newer `magi web` or `magi doctor` reading an older `magi
12475        // serve`'s heartbeat - must still see the run it is on, not "no
12476        // daemon" from a type mismatch failing the whole struct.
12477        let dir = tempfile::tempdir().unwrap();
12478        std::fs::write(
12479            dir.path().join("daemon.json"),
12480            serde_json::json!({
12481                "schema": 1,
12482                "pid": 4242,
12483                "updated_at": Timestamp::now().to_string(),
12484                "idle": false,
12485                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12486                "completed": 3,
12487                "polls": 9,
12488            })
12489            .to_string(),
12490        )
12491        .unwrap();
12492
12493        let reading = read_status(dir.path()).expect("an older shape must still parse");
12494        assert!(reading.running(Timestamp::now()));
12495        assert_eq!(
12496            reading.current,
12497            vec![Current {
12498                worker: None,
12499                task: "20260902-140501-aaaa".to_owned(),
12500                run: "20260902-140502-bbbb".to_owned(),
12501            }]
12502        );
12503    }
12504
12505    #[test]
12506    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12507        let dir = tempfile::tempdir().unwrap();
12508        std::fs::write(
12509            dir.path().join("daemon.json"),
12510            serde_json::json!({
12511                "schema": 1,
12512                "updated_at": Timestamp::now().to_string(),
12513                "idle": true,
12514                "current": null,
12515            })
12516            .to_string(),
12517        )
12518        .unwrap();
12519        let with_null = read_status(dir.path()).expect("null must still parse");
12520        assert!(with_null.current.is_empty());
12521
12522        std::fs::write(
12523            dir.path().join("daemon.json"),
12524            serde_json::json!({
12525                "schema": 1,
12526                "updated_at": Timestamp::now().to_string(),
12527                "idle": true,
12528            })
12529            .to_string(),
12530        )
12531        .unwrap();
12532        let absent = read_status(dir.path()).expect("a missing field must still parse");
12533        assert!(absent.current.is_empty());
12534    }
12535
12536    #[test]
12537    fn a_task_without_a_repository_runs_in_the_daemons_default() {
12538        let fallback = Path::new("/default");
12539        let mut blank = task();
12540        blank.repo = PathBuf::new();
12541        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12542        let mut dot = task();
12543        dot.repo = PathBuf::from(".");
12544        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12545        assert_eq!(
12546            repo_for(&task(), fallback),
12547            PathBuf::from("/repo"),
12548            "a task that names a repository keeps it"
12549        );
12550    }
12551
12552    #[test]
12553    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12554        let dir = tempfile::tempdir().unwrap();
12555        let repo = dir.path();
12556        let path = repo.join("explicit.toml");
12557        std::fs::write(
12558            &path,
12559            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12560        )
12561        .unwrap();
12562        let opts = Opts {
12563            config: Some(path),
12564            ..Opts::default()
12565        };
12566        let queue = Queue::at(repo.join("queue"));
12567        let mut new = task();
12568        queue.put(&mut new).unwrap();
12569        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12570        assert_eq!(
12571            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12572            BuildCache::Isolated
12573        );
12574
12575        let mut old = task();
12576        old.schema = 22;
12577        queue.put(&mut old).unwrap();
12578        let mut old = queue.get(&old.id).unwrap();
12579        let config = resolved(&old);
12580        assert_eq!(config.verify.build_cache, BuildCache::Shared);
12581        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12582        old.hold_manual(Some("wait".into()));
12583        queue.put(&mut old).unwrap();
12584
12585        let mut saved = queue.get(&old.id).unwrap();
12586        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12587        saved
12588            .overrides
12589            .as_mut()
12590            .unwrap()
12591            .merge_over(&crate::queue::RunOverrides {
12592                build_cache: Some(BuildCache::Isolated),
12593                ..Default::default()
12594            });
12595        queue.put(&mut saved).unwrap();
12596        assert_eq!(
12597            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12598            BuildCache::Isolated
12599        );
12600    }
12601
12602    #[test]
12603    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12604        let dir = tempfile::tempdir().unwrap();
12605        let path = dir.path().join("explicit.toml");
12606        let write = |verify: &str| {
12607            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12608        };
12609        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12610        let opts = Opts {
12611            config: Some(path.clone()),
12612            ..Opts::default()
12613        };
12614        let mut task = task();
12615        task.set_urgent(true).unwrap();
12616        let resolved = |task: &Task| {
12617            prepare_for(dir.path(), &opts, task)
12618                .unwrap()
12619                .verify
12620                .build_cache
12621        };
12622        assert_eq!(resolved(&task), BuildCache::Isolated);
12623        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12624        assert_eq!(resolved(&task), BuildCache::Shared);
12625        task.change_build_cache(None).unwrap();
12626        assert_eq!(resolved(&task), BuildCache::Isolated);
12627        task.set_urgent(false).unwrap();
12628        assert_eq!(resolved(&task), BuildCache::Shared);
12629
12630        // Urgent work must never be the one stopped by isolation: with no
12631        // shared cache to wait behind, or with a verification command isolated
12632        // mode cannot run, an urgent task keeps the configured mode.
12633        task.set_urgent(true).unwrap();
12634        write("e2e = [\"npm test\"]\n");
12635        assert_eq!(resolved(&task), BuildCache::Shared);
12636        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12637        assert_eq!(resolved(&task), BuildCache::Shared);
12638        // An explicit choice stays strict and is applied as asked.
12639        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12640        assert_eq!(resolved(&task), BuildCache::Isolated);
12641    }
12642
12643    #[test]
12644    fn task_implementers_edit_inherits_daemon_config_and_merge() {
12645        let dir = tempfile::tempdir().unwrap();
12646        let path = dir.path().join("explicit.toml");
12647        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12648        let opts = Opts {
12649            config: Some(path),
12650            merge: Some("none".into()),
12651            ..Default::default()
12652        };
12653        let mut t = task();
12654        t.set_implementers(
12655            2,
12656            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12657                .unwrap(),
12658        )
12659        .unwrap();
12660        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12661        assert_eq!(cfg.graph.implementers, 2);
12662        assert_eq!(cfg.graph.judges, 1);
12663        assert_eq!(cfg.merge.mode, MergeMode::None);
12664        t.set_implementers(1, &cfg).unwrap();
12665        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12666        apply_task_implementers(&mut cfg, &t);
12667        assert_eq!(cfg.graph.implementers, 1);
12668        assert_eq!(cfg.graph.judges, 1);
12669        assert_eq!(cfg.merge.mode, MergeMode::None);
12670    }
12671
12672    #[test]
12673    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12674        let dir = tempfile::tempdir().unwrap();
12675        let repo = dir.path().join("repo");
12676        std::fs::create_dir(&repo).unwrap();
12677        std::fs::write(
12678            repo.join("magi.toml"),
12679            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12680        )
12681        .unwrap();
12682        let daemon_config = dir.path().join("daemon.toml");
12683        std::fs::write(
12684            &daemon_config,
12685            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12686        )
12687        .unwrap();
12688        let opts = Opts {
12689            config: Some(daemon_config),
12690            merge: Some("pr".into()),
12691            ..Default::default()
12692        };
12693        let q = Queue::at(dir.path().join("queue"));
12694        let validation: Config =
12695            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12696                .unwrap();
12697        // No provenance field on legacy direct tasks: both shapes stay isolated.
12698        for record in ["{}", r#"{"candidates":2}"#] {
12699            let overrides = serde_json::from_str(record).unwrap();
12700            let filing = crate::direct::Filing {
12701                instruction: "work".into(),
12702                title: "direct".into(),
12703                repo: repo.clone(),
12704                source: crate::queue::Source::Human,
12705                issue: None,
12706                solo: false,
12707                overrides,
12708                review_of: None,
12709                sources: Default::default(),
12710            };
12711            let filed =
12712                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12713            let crate::direct::Filed::Standalone {
12714                mut task,
12715                claim: _claim,
12716            } = filed
12717            else {
12718                panic!("local filing")
12719            };
12720            let before = prepare_for(&repo, &opts, &task).unwrap();
12721            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12722            assert_eq!(
12723                before.merge.mode,
12724                MergeMode::None,
12725                "daemon --merge must not leak"
12726            );
12727            for n in [2, 1, 2] {
12728                task.set_implementers(n, &validation).unwrap();
12729                q.put(&mut task).unwrap();
12730                task = q.get(&task.id).unwrap();
12731                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12732                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12733                apply_task_implementers(&mut cfg, &task);
12734                assert_eq!(cfg.graph.implementers, usize::from(n));
12735                assert_eq!(cfg.graph.judges, 2);
12736                assert_eq!(cfg.merge.mode, MergeMode::None);
12737            }
12738        }
12739    }
12740
12741    #[test]
12742    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12743        let cfg: Config =
12744            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12745                .unwrap();
12746        let mut t = task();
12747        t.review_of = Some("review-target".into());
12748        t.hold_manual(Some("retry".into()));
12749        let mut previous = RunState::new(
12750            PathBuf::from("/repo"),
12751            "main".into(),
12752            "abc1234".into(),
12753            "review".into(),
12754            cfg.clone(),
12755        );
12756        previous.config.graph.implementers = 2;
12757        for count in [1, 3] {
12758            t.set_implementers(count, &cfg).unwrap();
12759            t.release();
12760            assert_eq!(t.review_of.as_deref(), Some("review-target"));
12761            for proposed in [
12762                Starter::Resume(previous.id.clone()),
12763                Starter::Review("recovery-target".into()),
12764            ] {
12765                assert_eq!(
12766                    starter_with_implementers(&t, Some(&previous), proposed),
12767                    Starter::Review("review-target".into())
12768                );
12769            }
12770            let mut configured = cfg.clone();
12771            apply_task_implementers(&mut configured, &t);
12772            assert_eq!(configured.graph.implementers, usize::from(count));
12773            assert_eq!(previous.config.graph.implementers, 2);
12774        }
12775    }
12776
12777    #[test]
12778    fn task_implementers_dispatch_and_resume_agree() {
12779        let mut t = task();
12780        let cfg: crate::config::Config =
12781            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12782                .unwrap();
12783        let mut run = RunState::new(
12784            PathBuf::from("/repo"),
12785            "main".into(),
12786            "abc1234".into(),
12787            "work".into(),
12788            cfg.clone(),
12789        );
12790        run.config.graph.implementers = 2;
12791        for n in [2, 1, 3, 2] {
12792            t.set_implementers(n, &cfg).unwrap();
12793            let mut dispatched = cfg.clone();
12794            apply_task_implementers(&mut dispatched, &t);
12795            assert_eq!(dispatched.graph.implementers, usize::from(n));
12796            assert_eq!(implementers_match(&t, &run), n == 2);
12797            for proposed in [
12798                Starter::Resume(run.id.clone()),
12799                Starter::Review("old-branch".into()),
12800            ] {
12801                let expected = if n == 2 {
12802                    proposed.clone()
12803                } else {
12804                    Starter::Start
12805                };
12806                assert_eq!(
12807                    starter_with_implementers(&t, Some(&run), proposed),
12808                    expected
12809                );
12810            }
12811            assert_eq!(
12812                run.config.graph.implementers, 2,
12813                "history must not be rewritten"
12814            );
12815        }
12816        t.solo = false;
12817        t.overrides = None;
12818        assert!(implementers_match(&t, &run));
12819    }
12820
12821    #[test]
12822    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12823        // Three seats said out loud. What `solo` promises is one candidate
12824        // *whatever the config asks for*, so the contrast has to be a number
12825        // this test owns - it used to be `Config::default()`'s, which became
12826        // 1 when one implementation became the default and left the two
12827        // halves of this test asserting the same thing.
12828        let mut solo_cfg = Config::default();
12829        solo_cfg.graph.implementers = 3;
12830        let mut solo_task = task();
12831        solo_task.solo = true;
12832        apply_task_implementers(&mut solo_cfg, &solo_task);
12833        assert_eq!(solo_cfg.graph.implementers, 1);
12834
12835        let mut plain_cfg = Config::default();
12836        plain_cfg.graph.implementers = 3;
12837        let plain_task = task();
12838        assert!(!plain_task.solo);
12839        apply_task_implementers(&mut plain_cfg, &plain_task);
12840        assert_eq!(
12841            plain_cfg.graph.implementers, 3,
12842            "a task that did not ask to run alone keeps the config's candidates"
12843        );
12844    }
12845
12846    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12847        QuotaLoss {
12848            cause: crate::agent::QuotaCause::UsageLimit,
12849            agent: String::new(),
12850            seat: seat.into(),
12851            node: "judge".into(),
12852            at: at.parse().unwrap(),
12853            reset: reset.map(str::to_string),
12854        }
12855    }
12856
12857    #[test]
12858    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12859        let now = Timestamp::now();
12860        for reset in [None, Some("in 1h")] {
12861            let auth = crate::agent::Quota {
12862                cause: crate::agent::QuotaCause::Authentication,
12863                agent: "alpha".into(),
12864                reset: reset.map(str::to_owned),
12865            };
12866            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12867            assert_eq!(cooldown_until(&[loss], now), None);
12868        }
12869    }
12870
12871    #[test]
12872    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12873        let old: Vec<QuotaLoss> = (1..=4)
12874            .map(|i| {
12875                loss(
12876                    &format!("judge-{i}"),
12877                    "2026-09-23T05:23:00Z",
12878                    Some("2:40pm (Asia/Tokyo)"),
12879                )
12880            })
12881            .collect();
12882        let fresh = losses_this_attempt(&old, &old);
12883        assert!(fresh.is_empty());
12884        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12885        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
12886    }
12887
12888    #[test]
12889    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12890        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12891        let now = Timestamp::now();
12892        let mut after = old.clone();
12893        after.push(loss("judge-2", &now.to_string(), None));
12894        let fresh = losses_this_attempt(&old, &after);
12895        assert_eq!(fresh, vec![after[1].clone()]);
12896        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12897        assert_eq!(
12898            until,
12899            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12900        );
12901    }
12902
12903    #[test]
12904    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12905        // `recover_stall` removes judge-1's loss and the retry then hits quota
12906        // again: the vector is the same length, so an index diff sees nothing.
12907        let before = vec![
12908            loss("judge-1", "2026-09-23T05:23:00Z", None),
12909            loss("judge-2", "2026-09-23T05:24:00Z", None),
12910        ];
12911        let after = vec![
12912            loss("judge-2", "2026-09-23T05:24:00Z", None),
12913            loss("judge-1", "2026-09-24T01:00:00Z", None),
12914        ];
12915        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12916    }
12917
12918    #[test]
12919    fn merge_overrides_are_parsed_or_refused() {
12920        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12921        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12922        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12923        assert!(merge_mode("squash").is_err());
12924    }
12925
12926    #[test]
12927    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12928        let now = Timestamp::now();
12929        let fallback = Duration::from_secs(300);
12930        let cap = Duration::from_secs(1800);
12931
12932        // No reset hint at all: the fallback.
12933        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12934
12935        // A reset ten minutes out, well inside the cap: waited for exactly.
12936        let soon = now + jiff::SignedDuration::from_secs(600);
12937        assert_eq!(
12938            quota_wait(Some(soon), now, fallback, cap),
12939            Duration::from_secs(600)
12940        );
12941
12942        // A reset already in the past is not trusted: the fallback, not a
12943        // zero or negative wait that would spin the loop right back around.
12944        let past = now - jiff::SignedDuration::from_secs(60);
12945        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12946
12947        // A reset further out than the cap is trusted for direction but not
12948        // for magnitude: a parsing slip must not sleep the loop for a day.
12949        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12950        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12951    }
12952
12953    #[test]
12954    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12955        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12956
12957        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12958        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12959
12960        // Same clock reading, but it has already gone by today: read as
12961        // tomorrow's, since the CLI would not still be reporting a limit past
12962        // its own stated reset.
12963        let already_past =
12964            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12965        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12966
12967        assert!(
12968            parse_reset_hint("session limit reached", now, now).is_none(),
12969            "free text with no recognised shape is not guessed at"
12970        );
12971        assert!(
12972            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12973            "an unresolvable zone name is not guessed at either"
12974        );
12975    }
12976
12977    #[test]
12978    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12979        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12980
12981        let at = parse_reset_hint(
12982            "You've hit your usage limit. Visit \
12983             https://chatgpt.com/codex/settings/usage to purchase more \
12984             credits or try again at Sep 19th, 2026 5:10 PM.",
12985            now,
12986            now,
12987        )
12988        .expect("the codex reset wording is a recognised shape");
12989        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12990
12991        // The month is explicit, so a date already earlier in the same
12992        // sentence-implied year than `now` is trusted as written rather than
12993        // rolled forward a year the way the bracketed shape rolls a
12994        // same-day clock reading to tomorrow.
12995        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12996            .expect("an explicit year needs no rollover");
12997        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12998
12999        assert!(
13000            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
13001            "a two-digit year is not the documented shape and is not guessed at"
13002        );
13003        assert!(
13004            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
13005            "a four-letter month name is not the documented three-letter abbreviation"
13006        );
13007        assert!(
13008            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
13009            "an explicit zone on the dated shape is a format nobody has \
13010             documented, and is refused rather than guessed at as UTC"
13011        );
13012    }
13013
13014    #[test]
13015    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
13016        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
13017        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
13018
13019        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
13020        assert_eq!(at.as_second() - recorded.as_second(), 3769);
13021
13022        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
13023        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
13024
13025        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
13026            assert!(
13027                parse_reset_hint(bad, now, recorded).is_none(),
13028                "{bad:?} must not be guessed at"
13029            );
13030        }
13031    }
13032
13033    /// A loop whose queue lives in a temp tree and whose poll interval is far
13034    /// longer than the test's patience, so anything that waits out a poll
13035    /// instead of noticing the stop fails rather than merely being slow.
13036    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
13037        let config = dir.join("magi.toml");
13038        std::fs::write(
13039            &config,
13040            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
13041        )
13042        .unwrap();
13043        let opts = Opts {
13044            poll: Duration::from_secs(30),
13045            config: Some(config),
13046            // The explicit fixture config keeps startup cleanup from reading
13047            // machine configuration. This fictional repository likewise
13048            // keeps any best-effort git cleanup away from this checkout.
13049            repo: dir.join("repo"),
13050            ..Opts::default()
13051        };
13052        // The status file goes in a directory that does not exist yet, so its
13053        // creation is itself evidence the loop published one. `worktrees`
13054        // must be just as fictional: the janitor reclaims worktrees under it
13055        // for real, and a test that let it fall through to
13056        // `crate::run::default_worktree_root()` would have it reclaim
13057        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
13058        // which is exactly what happened before this function took the
13059        // parameter at all.
13060        let home = dir.join("home");
13061        // These control-only fixtures do not launch native workers. Give the
13062        // independently tested maintenance services a fresh cadence receipt.
13063        let stamps = home.join("service-ticks");
13064        std::fs::create_dir_all(&stamps).unwrap();
13065        for service in ["waiter", "deputies", "release-watch"] {
13066            std::fs::write(
13067                stamps.join(service),
13068                Timestamp::now().as_second().to_string(),
13069            )
13070            .unwrap();
13071        }
13072        for operation in [
13073            "conductor",
13074            "maintenance",
13075            "housekeeping",
13076            "disk-pressure",
13077            "fold",
13078            "cache",
13079            "fetch",
13080            "chat-goals",
13081            "decisions",
13082        ] {
13083            std::fs::write(
13084                stamps.join(format!("daemon-{operation}")),
13085                serde_json::to_vec(&Timestamp::now()).unwrap(),
13086            )
13087            .unwrap();
13088        }
13089        let worktrees = dir.join("wt");
13090        (
13091            opts,
13092            Queue::at(dir.join("queue")),
13093            home.join("daemon.json"),
13094            home,
13095            worktrees,
13096        )
13097    }
13098
13099    #[tokio::test]
13100    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
13101        let dir = tempfile::tempdir().unwrap();
13102        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13103        let mut waiting = task();
13104        waiting.repo = opts.repo.clone();
13105        waiting.hold_machine(crate::disk::gate(1, 100));
13106        waiting.mark_disk_capacity();
13107        waiting.attempts = 2;
13108        queue.put(&mut waiting).unwrap();
13109        let mut busy = task();
13110        busy.status = TaskStatus::Running;
13111        queue.put(&mut busy).unwrap();
13112        let payload = serde_json::to_value(ServiceWorker {
13113            opts,
13114            queue: queue.root().to_owned(),
13115            worktrees_root: worktrees,
13116            operation: "maintenance".into(),
13117        })
13118        .unwrap();
13119        run_service_worker(&home, payload.clone()).await.unwrap();
13120        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13121        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
13122        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13123        run_service_worker(&home, payload).await.unwrap();
13124        assert!(
13125            crate::worker::active(&home).unwrap().is_empty(),
13126            "monitoring only queues; normal dispatch owns launches"
13127        );
13128        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
13129    }
13130
13131    #[tokio::test]
13132    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
13133        let dir = tempfile::tempdir().unwrap();
13134        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13135        let cfg = Config::default();
13136        start_service(
13137            &home,
13138            &opts,
13139            &queue,
13140            &worktrees,
13141            "housekeeping",
13142            Some(&cfg),
13143            true,
13144        )
13145        .await
13146        .unwrap();
13147        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
13148        let read = |path: &Path| -> serde_json::Value {
13149            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
13150        };
13151        assert_eq!(read(&receipt)["detail"], "cadence not due");
13152        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
13153        start_service(
13154            &home,
13155            &opts,
13156            &queue,
13157            &worktrees,
13158            "housekeeping",
13159            Some(&cfg),
13160            true,
13161        )
13162        .await
13163        .unwrap();
13164        assert_eq!(
13165            read(&receipt)["detail"],
13166            "active work or runnable task queue"
13167        );
13168        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13169        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13170        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13171        start_service(
13172            &home,
13173            &opts,
13174            &queue,
13175            &worktrees,
13176            "disk-pressure",
13177            Some(&cfg),
13178            false,
13179        )
13180        .await
13181        .unwrap();
13182        assert_eq!(
13183            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13184            "no active work; idle housekeeping owns scan"
13185        );
13186        assert!(crate::worker::active(&home).unwrap().is_empty());
13187    }
13188
13189    /// The folding turn exists exactly where idle housekeeping does not: with
13190    /// work busy or runnable. On `origin/main` the only caller of
13191    /// `clean::fold_due` was housekeeping, so a queue that was never empty
13192    /// admitted no finished-run folding at all.
13193    #[test]
13194    fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13195        let on = Config::default();
13196        for busy in [false, true] {
13197            for runnable in [false, true] {
13198                assert_ne!(
13199                    housekeeping_eligible(busy, runnable),
13200                    fold_turn_eligible(busy, runnable, Some(&on)),
13201                    "busy={busy} runnable={runnable}"
13202                );
13203            }
13204        }
13205        assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13206        assert!(!fold_turn_eligible(true, true, None));
13207        let mut off = Config::default();
13208        off.disk.auto_fold = false;
13209        assert!(!fold_turn_eligible(true, true, Some(&off)));
13210        assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13211    }
13212
13213    #[tokio::test]
13214    async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13215        let dir = tempfile::tempdir().unwrap();
13216        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13217        let read = || -> serde_json::Value {
13218            serde_json::from_slice(
13219                &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13220            )
13221            .unwrap()
13222        };
13223        let tick = home.join("service-ticks/daemon-fold");
13224        let cfg = Config::default();
13225        let dispatch = |busy: bool, cfg: Config| {
13226            let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13227            async move {
13228                start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13229                    .await
13230                    .unwrap();
13231            }
13232        };
13233        dispatch(true, cfg.clone()).await;
13234        assert_eq!(read()["detail"], "cadence not due");
13235
13236        std::fs::remove_file(&tick).unwrap();
13237        dispatch(false, cfg.clone()).await;
13238        assert_eq!(
13239            read()["detail"],
13240            "idle machine; housekeeping owns finished-run folding"
13241        );
13242        let mut off = cfg.clone();
13243        off.disk.auto_fold = false;
13244        dispatch(true, off).await;
13245        assert_eq!(read()["detail"], "auto_fold disabled");
13246        // An unreadable startup configuration is its own reason, not "idle".
13247        start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13248            .await
13249            .unwrap();
13250        assert_eq!(read()["detail"], "startup configuration unavailable");
13251
13252        // A housekeeping worker already folding: one folding service at a time.
13253        let directory = home.join("workers/jobs/abcdef");
13254        std::fs::create_dir_all(&directory).unwrap();
13255        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13256        crate::pr_head::try_lock_file(&lease).unwrap();
13257        let mut job = crate::worker::Job {
13258            id: "abcdef".into(),
13259            sequence: 1,
13260            kind: "daemon-service".into(),
13261            key: "service:daemon-housekeeping".into(),
13262            payload: serde_json::Value::Null,
13263            generation: "fixture".into(),
13264            version: None,
13265            status: crate::worker::Status::Running,
13266            result: None,
13267            pid: Some(std::process::id()),
13268            created_at: Timestamp::now().as_second() as u64,
13269            finished_at: None,
13270        };
13271        let record = directory.join("job.json");
13272        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13273        dispatch(true, cfg).await;
13274        assert_eq!(
13275            read()["detail"],
13276            "another finished-run folding service is active"
13277        );
13278        assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13279        job.status = crate::worker::Status::Finished;
13280        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13281        drop(lease);
13282    }
13283
13284    /// Issue 1275 through the scheduler's own admission: a leased task worker is
13285    /// busy, another task is runnable, and a confirmed merged run of the same
13286    /// repository is long past its grace. `poll` admits the fold service (the
13287    /// worker runs inline here: a unit test has no `magi` executable to exec),
13288    /// the historical worktree goes, the repository's active checkout stays and
13289    /// the merged run's evidence is kept. Removing `"fold"` from the operation
13290    /// list in `poll` leaves the worktree standing and fails this test.
13291    #[tokio::test]
13292    async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13293        let dir = tempfile::tempdir().unwrap();
13294        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13295        let repo = dir.path().join("checkout");
13296        std::fs::create_dir_all(&repo).unwrap();
13297        crate::clean::tests::init_repo(&repo);
13298        std::fs::write(
13299            opts.config.as_ref().unwrap(),
13300            "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13301        )
13302        .unwrap();
13303        let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13304            &home,
13305            &repo,
13306            &worktrees,
13307            "20260801-000000-s001",
13308        )
13309        .await;
13310        let active = dir.path().join("active");
13311        crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13312            .await
13313            .unwrap();
13314        // The busy worker belongs to the scheduler's own queue and owns a
13315        // recorded run of the same repository that is eligible on paper
13316        // (finished, past its grace). Its execution lease is held, as a
13317        // driving worker holds it.
13318        let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13319            &home.join("runs"),
13320            &worktrees,
13321            &repo,
13322            "20260801-000000-s002",
13323            RunStatus::Superseded,
13324        )
13325        .await;
13326        let owned_run = home.join("runs").join(&owned_id);
13327        let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13328        let mut busy = task();
13329        busy.repo = repo.clone();
13330        busy.status = TaskStatus::Running;
13331        busy.link_run(&owned_id);
13332        queue.put(&mut busy).unwrap();
13333        let worker_lease = crate::worker::running_fixture(
13334            &home,
13335            &format!("task:{}", busy.id),
13336            serde_json::to_value(TaskWorker {
13337                opts: Opts::default(),
13338                queue: queue.root().to_owned(),
13339                task: busy.id.clone(),
13340                lane: PermitKind::default(),
13341                standalone: true,
13342            })
13343            .unwrap(),
13344        )
13345        .unwrap();
13346        let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13347        let mut waiting = task();
13348        waiting.repo = repo.clone();
13349        queue.put(&mut waiting).unwrap();
13350        std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13351
13352        let mut cfg = Config::default();
13353        cfg.disk.auto_fold = true;
13354        INLINE_SERVICES.with(|inline| inline.set(true));
13355        let status = Arc::new(Mutex::new(Status::new()));
13356        let stop = Stop::new();
13357        let mut dispatch = Box::pin(poll(
13358            &opts,
13359            &queue,
13360            &status,
13361            &home,
13362            &worktrees,
13363            &stop,
13364            DispatchLimits {
13365                max_concurrent: 0,
13366                pause_for_interrupts: false,
13367                recovery_cfg: Some(cfg),
13368            },
13369        ));
13370        let receipt = home.join("source-eviction-fold-worker.json");
13371        let completed = async {
13372            loop {
13373                let done = std::fs::read(&receipt)
13374                    .ok()
13375                    .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13376                    .is_some_and(|receipt| receipt["outcome"] == "completed");
13377                if done {
13378                    break;
13379                }
13380                tokio::time::sleep(Duration::from_millis(25)).await;
13381            }
13382        };
13383        tokio::select! {
13384            result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13385            result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13386                result.expect("the scheduler never admitted the fold service");
13387            }
13388        }
13389        stop.stop();
13390        dispatch.await.unwrap();
13391        INLINE_SERVICES.with(|inline| inline.set(false));
13392
13393        assert!(!historical.exists(), "the merged run's worktree is folded");
13394        assert!(
13395            active.join("README.md").is_file(),
13396            "the repository's active checkout is untouched"
13397        );
13398        let run = home.join("runs").join(&id);
13399        assert!(run.join("run.json").is_file());
13400        assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13401        let read = |name: &str| -> serde_json::Value {
13402            serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13403        };
13404        assert_eq!(
13405            read("source-eviction-fold-dispatch.json")["detail"],
13406            "eligible and cadence due"
13407        );
13408        let worker = read("source-eviction-fold-worker.json");
13409        assert_eq!(worker["fold"]["records"], 2);
13410        assert_eq!(worker["fold"]["folded"], 1);
13411        assert_eq!(worker["fold"]["invoked"], 1);
13412        assert_eq!(
13413            worker["fold"]["live"], 1,
13414            "the busy worker's own run is left alone: {worker}"
13415        );
13416        // The run the busy worker owns - eligible on paper (finished, past its
13417        // grace) - keeps its checkout, its candidate and its record, byte for byte.
13418        assert!(owned_worktree.exists());
13419        assert_eq!(
13420            std::fs::read(owned_run.join("run.json")).unwrap(),
13421            owned_record
13422        );
13423        assert!(
13424            !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13425            "the owned run's candidate is not folded"
13426        );
13427        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13428        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13429        drop(execution);
13430        drop(worker_lease);
13431    }
13432
13433    /// On a platform without process containment the disk-pressure service
13434    /// refuses to reclaim, and says so in both places an operator looks: the
13435    /// persisted retention report and the worker receipt. Driven through the
13436    /// service handler itself, so removing either publication fails this test.
13437    #[tokio::test]
13438    async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13439        let dir = tempfile::tempdir().unwrap();
13440        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13441        let payload = serde_json::to_value(ServiceWorker {
13442            opts,
13443            queue: queue.root().to_owned(),
13444            worktrees_root: worktrees,
13445            operation: "disk-pressure".into(),
13446        })
13447        .unwrap();
13448        let _platform = crate::retention::WithoutContainment::new();
13449        run_service_worker(&home, payload).await.unwrap();
13450
13451        let refusal = "Automatic output reclamation requires Unix process containment";
13452        let report: serde_json::Value =
13453            serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13454        assert_eq!(report["failures"], serde_json::json!([refusal]));
13455        let receipt: serde_json::Value = serde_json::from_slice(
13456            &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13457        )
13458        .unwrap();
13459        assert_eq!(receipt["outcome"], "retention swept");
13460        assert_eq!(receipt["retention"]["failure_count"], 1);
13461        assert_eq!(
13462            receipt["retention"]["failures"],
13463            serde_json::json!([refusal])
13464        );
13465    }
13466
13467    #[tokio::test]
13468    async fn goal_observation_service_does_not_block_scheduler_decisions() {
13469        let dir = tempfile::tempdir().unwrap();
13470        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13471        let queue = Queue::at(home.join("queue"));
13472        let mut task = task();
13473        task.repo = opts.repo.clone();
13474        task.chat = Some("decision-chat".into());
13475        let mut state = run_state(RunStatus::Merged);
13476        state.repo = task.repo.clone();
13477        state.merge = Some(crate::run::MergeOutcome {
13478            mode: MergeMode::Pr,
13479            ok: true,
13480            detail: "confirmed merge".into(),
13481            empty: false,
13482        });
13483        task.link_run(&state.id);
13484        state.save_under(&home).unwrap();
13485        task.hold_machine(Some("waiting for a decision".into()));
13486        queue.put(&mut task).unwrap();
13487        let questions = Questions::at(home.join("questions"));
13488        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13489        question.node = crate::conduct::NODE.into();
13490        question.status = ask::QuestionStatus::Open;
13491        question.answer = None;
13492        question.answered_at = None;
13493        questions.put(&mut question).unwrap();
13494        questions
13495            .update(&question.id, |q| {
13496                q.answer(ask::Answer::Choice("resume で続行する".into()))
13497            })
13498            .unwrap();
13499
13500        let talks = crate::talk::Talks::at(home.join("talks"));
13501        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13502        decision_chat.pending = "Keep this unsent status question".into();
13503        talks.put(&mut decision_chat).unwrap();
13504        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13505        talk.goals.push(serde_json::from_value(serde_json::json!({
13506            "id":"goal","purpose":"follow the retained job","scope":"one task",
13507            "condition":{"description":"land the result","kind":"runs_merged"},
13508            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13509            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13510            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13511        })).unwrap());
13512        talks.put(&mut talk).unwrap();
13513
13514        // A retained service lease models an observation still waiting on its
13515        // external dependency. Admission must neither await nor repeat it.
13516        let directory = home.join("workers/jobs/abcdef");
13517        std::fs::create_dir_all(&directory).unwrap();
13518        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13519        crate::pr_head::try_lock_file(&lease).unwrap();
13520        let mut job = crate::worker::Job {
13521            id: "abcdef".into(),
13522            sequence: 1,
13523            kind: "daemon-service".into(),
13524            key: "service:daemon-chat-goals".into(),
13525            payload: serde_json::Value::Null,
13526            generation: "fixture".into(),
13527            version: None,
13528            status: crate::worker::Status::Running,
13529            result: None,
13530            pid: Some(std::process::id()),
13531            created_at: Timestamp::now().as_second() as u64,
13532            finished_at: None,
13533        };
13534        let record = directory.join("job.json");
13535        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13536        let status = Arc::new(Mutex::new(Status::new()));
13537        let stop = Stop::new();
13538        let mut dispatch = Box::pin(poll(
13539            &opts,
13540            &queue,
13541            &status,
13542            &home,
13543            &worktrees,
13544            &stop,
13545            DispatchLimits {
13546                max_concurrent: 1,
13547                pause_for_interrupts: false,
13548                recovery_cfg: None,
13549            },
13550        ));
13551        std::future::poll_fn(|cx| {
13552            assert!(dispatch.as_mut().poll(cx).is_pending());
13553            std::task::Poll::Ready(())
13554        })
13555        .await;
13556        assert!(lock(&status).polls > 0);
13557        let saved = queue.get(&task.id).unwrap();
13558        assert_eq!(saved.status, TaskStatus::Done);
13559        assert!(saved.action_applied(&question.id));
13560        assert!(
13561            talks
13562                .get("decision-chat")
13563                .unwrap()
13564                .pending
13565                .contains("Keep this unsent status question")
13566        );
13567        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13568        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13569        assert_eq!(
13570            goal.started,
13571            Some(1),
13572            "only the observation worker may reconcile its goal"
13573        );
13574        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13575
13576        stop.stop();
13577        dispatch.await.unwrap();
13578        job.status = crate::worker::Status::Finished;
13579        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13580        drop(lease);
13581    }
13582
13583    #[test]
13584    fn a_stop_is_idempotent_and_once_set_stays_set() {
13585        let stop = Stop::new();
13586        assert!(!stop.stopped());
13587
13588        stop.stop();
13589        assert!(stop.stopped());
13590        stop.stop();
13591        assert!(stop.stopped(), "a second stop is not a toggle");
13592
13593        let shared = stop.clone();
13594        assert!(
13595            shared.stopped(),
13596            "a clone is the same stop; that is how the loop and its caller share one"
13597        );
13598    }
13599
13600    #[tokio::test]
13601    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13602        for operation in ["conductor", "maintenance", "housekeeping", "decisions"] {
13603            let dir = tempfile::tempdir().unwrap();
13604            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13605            opts.once = true;
13606            opts.poll = Duration::from_millis(1);
13607            // This test exercises answer scheduling, not explicit discard:
13608            // ordinary Done requires confirmed landing.
13609            let mut state = run_state(RunStatus::Merged);
13610            state.merge = Some(crate::run::MergeOutcome {
13611                mode: MergeMode::Pr,
13612                ok: true,
13613                detail: "confirmed merge".into(),
13614                empty: false,
13615            });
13616            state.reserve_under(&home).unwrap();
13617            state.save_under(&home).unwrap();
13618            let mut task = task();
13619            // Completing a human task would reserve a task chat and start a
13620            // chat worker; this fixture only exercises answer scheduling. A
13621            // linked chat that does not exist is skipped, never created.
13622            task.chat = Some("task-fixture".into());
13623            task.chat_reservation = crate::queue::ChatReservation::Established;
13624            task.runs.push(state.id.clone());
13625            queue.put(&mut task).unwrap();
13626            let claim = queue.claim(&task.id).unwrap();
13627
13628            // Model a live service holding the task's claim across the
13629            // scheduler's dispatch scan. No real subprocess or timed race.
13630            let directory = home.join("workers/jobs/abcdef");
13631            std::fs::create_dir_all(&directory).unwrap();
13632            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13633            crate::pr_head::try_lock_file(&lease).unwrap();
13634            let mut job = crate::worker::Job {
13635                id: "abcdef".into(),
13636                sequence: 1,
13637                kind: "daemon-service".into(),
13638                key: format!("service:daemon-{operation}"),
13639                payload: serde_json::Value::Null,
13640                generation: "fixture".into(),
13641                version: None,
13642                status: crate::worker::Status::Running,
13643                result: None,
13644                pid: Some(std::process::id()),
13645                created_at: Timestamp::now().as_second() as u64,
13646                finished_at: None,
13647            };
13648            let record = directory.join("job.json");
13649            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13650
13651            let status = Arc::new(Mutex::new(Status::new()));
13652            let stop = Stop::new();
13653            let mut drain = Box::pin(poll(
13654                &opts,
13655                &queue,
13656                &status,
13657                &home,
13658                &worktrees,
13659                &stop,
13660                DispatchLimits {
13661                    max_concurrent: 1,
13662                    pause_for_interrupts: false,
13663                    recovery_cfg: None,
13664                },
13665            ));
13666            std::future::poll_fn(|cx| {
13667                use std::future::Future;
13668                assert!(
13669                    drain.as_mut().poll(cx).is_pending(),
13670                    "--once must wait for {operation} to release its queue claim"
13671                );
13672                std::task::Poll::Ready(())
13673            })
13674            .await;
13675            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13676
13677            // An answer arrives while the service still owns the claim. A
13678            // fresh scheduling pass must apply it before declaring idle.
13679            let questions = Questions::at(home.join("questions"));
13680            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13681            questions.put(&mut q).unwrap();
13682            drop(claim);
13683            // Model services that took longer than their cadence, without a
13684            // wall-clock sleep. The final scans must not respawn them even
13685            // though their receipts now permit another periodic invocation.
13686            let expired =
13687                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13688            for service in [operation, "housekeeping"] {
13689                std::fs::write(
13690                    home.join("service-ticks").join(format!("daemon-{service}")),
13691                    &expired,
13692                )
13693                .unwrap();
13694            }
13695            job.status = crate::worker::Status::Finished;
13696            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13697            drop(lease);
13698            tokio::time::timeout(Duration::from_secs(2), drain)
13699                .await
13700                .expect("the settled service must allow the drain to finish")
13701                .unwrap();
13702            let after = queue.get(&task.id).unwrap();
13703            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13704            assert!(after.action_applied(&q.id));
13705            for service in [operation, "housekeeping"] {
13706                assert_eq!(
13707                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13708                        .unwrap(),
13709                    expired,
13710                    "the final once rescan must not restart {service}"
13711                );
13712            }
13713        }
13714    }
13715
13716    #[test]
13717    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13718        let stop = Stop::new();
13719        stop.busy.store(1, Ordering::SeqCst);
13720        assert!(
13721            !stop.finishing(),
13722            "a busy loop nobody has asked to stop is just running"
13723        );
13724
13725        stop.stop();
13726        assert!(
13727            stop.finishing(),
13728            "a stop asked for mid-run has not landed until the run is settled"
13729        );
13730
13731        stop.busy.store(0, Ordering::SeqCst);
13732        assert!(
13733            !stop.finishing(),
13734            "once the run is settled the stop has landed and there is nothing to finish"
13735        );
13736    }
13737
13738    #[test]
13739    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13740        let stop = Stop::new();
13741        stop.busy.store(2, Ordering::SeqCst);
13742        stop.stop();
13743        assert!(stop.finishing(), "two runs still in flight");
13744
13745        stop.busy.store(1, Ordering::SeqCst);
13746        assert!(
13747            stop.finishing(),
13748            "one run finished, but a sibling is still working"
13749        );
13750
13751        stop.busy.store(0, Ordering::SeqCst);
13752        assert!(
13753            !stop.finishing(),
13754            "the last run out is what actually lands the stop"
13755        );
13756    }
13757
13758    #[tokio::test]
13759    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13760        let dir = tempfile::tempdir().unwrap();
13761        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13762        let stop = Stop::new();
13763        stop.stop();
13764
13765        let began = std::time::Instant::now();
13766        tokio::time::timeout(
13767            Duration::from_secs(2),
13768            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13769        )
13770        .await
13771        .expect("a stopped loop must return, not sit out its poll interval")
13772        .expect("the loop's own setup and teardown must not fail");
13773        assert!(
13774            began.elapsed() < opts.poll,
13775            "returned only after {:?}, which is a poll interval, not a stop",
13776            began.elapsed()
13777        );
13778    }
13779
13780    #[tokio::test]
13781    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13782        let dir = tempfile::tempdir().unwrap();
13783        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13784        let stop = Stop::new();
13785
13786        // Asked for after the loop is already parked on its empty queue, which
13787        // is the case an operator tapping stop on a phone actually hits.
13788        let asker = {
13789            let stop = stop.clone();
13790            tokio::spawn(async move {
13791                tokio::time::sleep(Duration::from_millis(20)).await;
13792                stop.stop();
13793            })
13794        };
13795
13796        let began = std::time::Instant::now();
13797        tokio::time::timeout(
13798            Duration::from_secs(2),
13799            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13800        )
13801        .await
13802        .expect("a stop asked for while idle must wake the wait")
13803        .expect("the loop's own setup and teardown must not fail");
13804        asker.await.unwrap();
13805        assert!(
13806            began.elapsed() < opts.poll,
13807            "returned only after {:?}, so the stop waited on the sleep",
13808            began.elapsed()
13809        );
13810    }
13811
13812    #[tokio::test]
13813    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13814        let dir = tempfile::tempdir().unwrap();
13815        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13816        let stop = Stop::new();
13817        stop.stop();
13818
13819        tokio::time::timeout(
13820            Duration::from_secs(2),
13821            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13822        )
13823        .await
13824        .expect("a stopped loop must return")
13825        .expect("the loop's own setup and teardown must not fail");
13826
13827        assert!(
13828            home.is_dir(),
13829            "the loop did publish a status file, so its removal is the teardown and not an absence"
13830        );
13831        assert!(
13832            !status_file.exists(),
13833            "a stopped loop clears its status file"
13834        );
13835        assert!(
13836            read_status(&home).is_none(),
13837            "a reader must see no daemon at all, not a heartbeat that merely stopped"
13838        );
13839    }
13840
13841    #[tokio::test]
13842    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13843        let dir = tempfile::tempdir().unwrap();
13844        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13845
13846        let mut settled = RunState::new(
13847            dir.path().join("repo"),
13848            "main".to_owned(),
13849            "abc1234".to_owned(),
13850            "fixture".to_owned(),
13851            Config::default(),
13852        );
13853        settled.status = RunStatus::Ready;
13854        let run_dir = home.join("runs").join(&settled.id);
13855        std::fs::create_dir_all(&run_dir).unwrap();
13856        std::fs::write(
13857            run_dir.join("run.json"),
13858            serde_json::to_string_pretty(&settled).unwrap(),
13859        )
13860        .unwrap();
13861        let questions = Questions::at(home.join("questions"));
13862        let mut question = ask::Question::new(
13863            settled.id.clone(),
13864            "review".to_owned(),
13865            "reviewer-1".to_owned(),
13866            "Continue?".to_owned(),
13867            String::new(),
13868            Vec::new(),
13869        );
13870        questions.put(&mut question).unwrap();
13871
13872        run_service_worker(
13873            &home,
13874            serde_json::to_value(ServiceWorker {
13875                opts,
13876                queue: queue.root().to_path_buf(),
13877                worktrees_root: worktrees,
13878                operation: "housekeeping".to_owned(),
13879            })
13880            .unwrap(),
13881        )
13882        .await
13883        .unwrap();
13884
13885        assert_eq!(
13886            questions.get(&question.id).unwrap().status,
13887            ask::QuestionStatus::Abandoned,
13888            "the independent housekeeping worker settles ended-run questions"
13889        );
13890    }
13891
13892    #[test]
13893    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13894        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13895
13896        assert!(
13897            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13898            "never checked before: due at once"
13899        );
13900
13901        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13902        assert!(
13903            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13904            "well inside the interval: not due yet"
13905        );
13906
13907        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13908        assert!(
13909            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13910            "exactly at the edge: not yet due, same convention as `clean::due`"
13911        );
13912
13913        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13914        assert!(
13915            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13916            "past the interval: due again"
13917        );
13918    }
13919
13920    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
13921    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
13922    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
13923    /// and the congestion test below both need, and must not drift apart.
13924    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13925        let config = dir.join("magi.toml");
13926        // A literal (single-quoted) TOML string, not a basic one: the cache
13927        // path is a Windows path full of backslashes, and a basic string
13928        // would have TOML try to interpret `\U` (from `\Users\...`) as a
13929        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
13930        // `{{ vars.cache }}` rendering documents.
13931        std::fs::write(
13932            &config,
13933            format!(
13934                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13935                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13936                cache_dir.display()
13937            ),
13938        )
13939        .unwrap();
13940        Opts {
13941            config: Some(config),
13942            repo: dir.join("repo"),
13943            ..Opts::default()
13944        }
13945    }
13946
13947    #[tokio::test]
13948    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13949        let dir = tempfile::tempdir().unwrap();
13950        let home = dir.path().join("home");
13951        let cache_dir = dir.path().join("cache");
13952        std::fs::create_dir_all(&cache_dir).unwrap();
13953        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13954        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13955
13956        // Nobody has asked this daemon to stop, which is the ordinary case;
13957        // the skip that a stop buys is asserted by its own test below.
13958        let running = Stop::new();
13959        let mut last_checked = None;
13960        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13961        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13962            .await;
13963        assert_eq!(
13964            crate::disk::dir_size(&cache_dir),
13965            0,
13966            "over the cap on the first check ever: pruned at once, no idle queue required"
13967        );
13968        assert_eq!(last_checked, Some(t0));
13969
13970        // A fresh oversized file lands, but the next check is not due yet.
13971        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13972        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13973        maybe_prune_cache_between_runs(
13974            &opts.repo,
13975            &opts,
13976            &home,
13977            &running,
13978            &mut last_checked,
13979            too_soon,
13980        )
13981        .await;
13982        assert_eq!(
13983            crate::disk::dir_size(&cache_dir),
13984            10,
13985            "too soon since the last check: left alone rather than rescanned every call"
13986        );
13987        assert_eq!(
13988            last_checked,
13989            Some(t0),
13990            "an idle check does not reset the clock"
13991        );
13992
13993        // Once the interval elapses, the same oversized cache is caught again.
13994        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13995        maybe_prune_cache_between_runs(
13996            &opts.repo,
13997            &opts,
13998            &home,
13999            &running,
14000            &mut last_checked,
14001            due_again,
14002        )
14003        .await;
14004        assert_eq!(
14005            crate::disk::dir_size(&cache_dir),
14006            0,
14007            "due again: pruned back under the cap"
14008        );
14009    }
14010
14011    /// A stop must not queue behind housekeeping. The prune below is a
14012    /// synchronous walk of the whole cache with no await point in it, so a
14013    /// loop that entered it could not get back to its own `stopped()` test
14014    /// until the walk finished - and because no run is in flight at this
14015    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
14016    /// the stop had already landed. The idle branch has always made this same
14017    /// check before reaching `janitor`; the between-runs path makes it too.
14018    #[tokio::test]
14019    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
14020        let dir = tempfile::tempdir().unwrap();
14021        let home = dir.path().join("home");
14022        let cache_dir = dir.path().join("cache");
14023        std::fs::create_dir_all(&cache_dir).unwrap();
14024        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
14025        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
14026
14027        let stop = Stop::new();
14028        stop.stop();
14029        assert!(
14030            !stop.finishing(),
14031            "no run is in flight at a between-runs boundary, so nothing else \
14032             would tell the operator this stop had not taken effect yet"
14033        );
14034
14035        let mut last_checked = None;
14036        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
14037        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
14038            .await;
14039        assert_eq!(
14040            crate::disk::dir_size(&cache_dir),
14041            10,
14042            "over its cap, and due for the first check ever, but a stop outranks \
14043             it: the cap is a standing policy the next start measures again"
14044        );
14045        assert_eq!(
14046            last_checked, None,
14047            "a check that never happened must not claim the interval"
14048        );
14049    }
14050
14051    /// A backlog must not starve cache pruning. The finite cache worker runs
14052    /// independently of queue drain and must not consume any task attempts.
14053    #[tokio::test]
14054    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
14055        let dir = tempfile::tempdir().unwrap();
14056        let cache_dir = dir.path().join("cache");
14057        std::fs::create_dir_all(&cache_dir).unwrap();
14058        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
14059
14060        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
14061        opts.poll = Duration::from_millis(20);
14062        opts.max_attempts = 1_000;
14063
14064        let queue = Queue::at(dir.path().join("queue"));
14065        for i in 0..128 {
14066            let mut task = Task::new(
14067                format!("queued work {i}"),
14068                format!("queued work {i}"),
14069                opts.repo.clone(),
14070                Source::Human,
14071            );
14072            queue.put(&mut task).unwrap();
14073        }
14074
14075        let home = dir.path().join("home");
14076        let worktrees = dir.path().join("wt");
14077        run_service_worker(
14078            &home,
14079            serde_json::to_value(ServiceWorker {
14080                opts,
14081                queue: queue.root().to_path_buf(),
14082                worktrees_root: worktrees,
14083                operation: "cache".to_owned(),
14084            })
14085            .unwrap(),
14086        )
14087        .await
14088        .unwrap();
14089        let after = queue.list();
14090        assert_eq!(after.len(), 128);
14091        assert!(
14092            after
14093                .iter()
14094                .all(|task| task.status.runnable() && task.attempts == 0)
14095        );
14096
14097        assert_eq!(
14098            crate::disk::dir_size(&cache_dir),
14099            0,
14100            "an oversized cache must not be left to grow unboundedly just because the \
14101             queue kept the loop busy the whole time"
14102        );
14103    }
14104
14105    #[test]
14106    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
14107        let dir = tempfile::tempdir().unwrap();
14108        let queue = Queue::at(dir.path().join("queue"));
14109        let questions = Questions::at(dir.path().join("questions"));
14110        let mut task = task();
14111        queue.put(&mut task).unwrap();
14112
14113        let mut task_question = ask::Question::new(
14114            task.id.clone(),
14115            crate::conduct::NODE.to_owned(),
14116            "conduct".to_owned(),
14117            "Which backend?".to_owned(),
14118            String::new(),
14119            Vec::new(),
14120        );
14121        questions.put(&mut task_question).unwrap();
14122        task.block(vec![task_question.id.clone()], None);
14123        queue.put(&mut task).unwrap();
14124
14125        let mut run_question = ask::Question::new(
14126            "20260101-000000-run1".to_owned(),
14127            "review".to_owned(),
14128            "reviewer-1".to_owned(),
14129            "Run question".to_owned(),
14130            String::new(),
14131            Vec::new(),
14132        );
14133        questions.put(&mut run_question).unwrap();
14134
14135        // A question from another node whose `run` happens to equal this
14136        // task's id — the same field, filled in for an unrelated reason. Only
14137        // `crate::conduct::NODE` questions use `run` as a task id; this one
14138        // must never be touched by this reconciliation, even after release.
14139        let mut coincidental = ask::Question::new(
14140            task.id.clone(),
14141            "review".to_owned(),
14142            "reviewer-1".to_owned(),
14143            "Unrelated review question".to_owned(),
14144            String::new(),
14145            Vec::new(),
14146        );
14147        questions.put(&mut coincidental).unwrap();
14148
14149        reconcile_task_questions(&queue, &questions);
14150        assert!(questions.get(&task_question.id).unwrap().status.open());
14151        assert!(questions.get(&run_question.id).unwrap().status.open());
14152        assert!(questions.get(&coincidental.id).unwrap().status.open());
14153
14154        task.release();
14155        queue.put(&mut task).unwrap();
14156        reconcile_task_questions(&queue, &questions);
14157        assert_eq!(
14158            questions.get(&task_question.id).unwrap().status,
14159            ask::QuestionStatus::Abandoned
14160        );
14161        assert!(
14162            questions.get(&run_question.id).unwrap().status.open(),
14163            "run questions remain the run janitor's responsibility"
14164        );
14165        assert!(
14166            questions.get(&coincidental.id).unwrap().status.open(),
14167            "a non-conductor question must not be abandoned just because its \
14168             run id coincides with a task id"
14169        );
14170    }
14171
14172    #[test]
14173    fn a_freshly_started_running_task_is_never_stalled() {
14174        let dir = tempfile::tempdir().unwrap();
14175        let mut t = task();
14176        t.start("run-1".to_owned());
14177        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
14178        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
14179        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14180    }
14181
14182    #[test]
14183    fn a_long_running_task_with_no_live_daemon_is_stalled() {
14184        let dir = tempfile::tempdir().unwrap();
14185        let mut t = task();
14186        t.start("run-1".to_owned());
14187        t.updated_at = Timestamp::now()
14188            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14189        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14190        assert_eq!(
14191            stalled_tasks(
14192                &Queue::at(dir.path().join("q")),
14193                dir.path(),
14194                Timestamp::now()
14195            )
14196            .len(),
14197            0,
14198            "the task was never written to this queue"
14199        );
14200    }
14201
14202    #[test]
14203    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14204        let dir = tempfile::tempdir().unwrap();
14205        let mut t = task();
14206        t.id = "20260903-080340-0167".to_owned();
14207        t.start("20260903-080619-01c2".to_owned());
14208        t.updated_at = Timestamp::now()
14209            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14210
14211        let mut status = Status::new();
14212        status.current = vec![Current {
14213            worker: None,
14214            task: t.id.clone(),
14215            run: "20260903-080619-01c2".to_owned(),
14216        }];
14217        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14218
14219        assert!(
14220            !is_stalled(&t, dir.path(), Timestamp::now()),
14221            "a live daemon's own heartbeat rules out stalled, however long the task has run"
14222        );
14223    }
14224
14225    /// Rewrite a task's `updated_at` on disk directly, bypassing
14226    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
14227    /// a fixture look like it has genuinely been `running` for a while.
14228    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14229        let path = queue.path_of(id);
14230        let body = std::fs::read_to_string(&path).unwrap();
14231        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14232        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14233        v["updated_at"] = serde_json::Value::String(old.to_string());
14234        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14235    }
14236
14237    #[test]
14238    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14239        // The realistic `poll()` ordering, not `is_stalled` in isolation:
14240        // `reclaim_orphaned_running` runs first, on every poll, and settles
14241        // any `running` task whose claim it can actually take. For most
14242        // crashes that is immediate - a dead pid is proof enough for
14243        // `sweep_stale_claims` to drop the lock the same tick, and the very
14244        // next claim attempt succeeds. But a lock whose pid cannot be parsed
14245        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
14246        // `sweep_stale_claims`'s own doc), so the lock - and the claim
14247        // failure behind it - can legitimately outlive many polls. This is
14248        // exactly the gap `stalled_tasks` exists to surface well before that
14249        // six-hour sweep would: reclaim leaves the task `running`, and it
14250        // must still reach the conductor as stalled.
14251        let dir = tempfile::tempdir().unwrap();
14252        let queue = Queue::at(dir.path().join("queue"));
14253        let home = dir.path().join("home");
14254
14255        let mut t = task();
14256        t.id = "20260101-000001-lock".to_owned();
14257        t.start("run-1".to_owned());
14258        queue.put(&mut t).unwrap();
14259        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14260        std::fs::write(
14261            dir.path().join("queue").join(format!("{}.lock", t.id)),
14262            "not a pid",
14263        )
14264        .unwrap();
14265
14266        let now = Timestamp::now();
14267        assert!(
14268            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14269            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14270             and reclaim must leave the task alone"
14271        );
14272        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14273
14274        let stalled = stalled_tasks(&queue, &home, now);
14275        assert_eq!(
14276            stalled.len(),
14277            1,
14278            "reclaim's inability to claim it yet must not hide it from the conductor"
14279        );
14280        assert_eq!(stalled[0].id, t.id);
14281    }
14282
14283    #[test]
14284    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14285        let dir = tempfile::tempdir().unwrap();
14286        crate::run::set_home(dir.path().join("run-home"));
14287        let queue = Queue::at(dir.path().join("queue"));
14288        let home = dir.path().join("home");
14289        let questions = Questions::at(dir.path().join("questions"));
14290
14291        let mut t = task();
14292        t.id = "20260101-000003-dead".to_owned();
14293        t.start("missing-run".to_owned());
14294        queue.put(&mut t).unwrap();
14295        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14296
14297        // This is the real poll ordering: retain the deterministic stalled
14298        // input before a claim proves the owner is gone and reclaims it.
14299        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14300        assert_eq!(
14301            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14302            [&t.id]
14303        );
14304        assert_eq!(
14305            reclaim_orphaned_running(&queue, 2, &Default::default()),
14306            [t.id.clone()]
14307        );
14308        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14309
14310        // Reclaim drops its guard before conductor decisions are applied, so
14311        // the decision for the captured stalled input has a real write path.
14312        crate::conduct::apply(
14313            &queue,
14314            &questions,
14315            &crate::conduct::Verdict {
14316                decisions: vec![crate::conduct::Decision {
14317                    id: t.id.clone(),
14318                    recovery: Some(crate::conduct::Recovery::Requeue),
14319                    ..crate::conduct::Decision::default()
14320                }],
14321            },
14322        )
14323        .unwrap();
14324        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14325    }
14326
14327    #[test]
14328    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14329        let dir = tempfile::tempdir().unwrap();
14330        let queue = Queue::at(dir.path().join("queue"));
14331        let home = dir.path().join("home");
14332
14333        let mut fresh = task();
14334        fresh.id = "20260101-000001-aaaa".to_owned();
14335        fresh.start("run-1".to_owned());
14336        queue.put(&mut fresh).unwrap();
14337
14338        let mut old = task();
14339        old.id = "20260101-000002-bbbb".to_owned();
14340        old.start("run-2".to_owned());
14341        queue.put(&mut old).unwrap();
14342        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14343
14344        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14345        assert_eq!(stalled.len(), 1);
14346        assert_eq!(stalled[0].id, old.id);
14347    }
14348
14349    #[test]
14350    fn queued_and_finished_task_views_partition_by_status() {
14351        let dir = tempfile::tempdir().unwrap();
14352        let queue = Queue::at(dir.path().join("queue"));
14353
14354        let mut queued = task();
14355        queued.id = "20260101-000001-aaaa".to_owned();
14356        queue.put(&mut queued).unwrap();
14357
14358        let mut failed = task();
14359        failed.id = "20260101-000002-bbbb".to_owned();
14360        failed.start("run-1".to_owned());
14361        failed.fail("gate red", 5);
14362        queue.put(&mut failed).unwrap();
14363
14364        let mut held = task();
14365        held.id = "20260101-000003-cccc".to_owned();
14366        held.hold_machine(None);
14367        queue.put(&mut held).unwrap();
14368
14369        let mut running = task();
14370        running.id = "20260101-000004-dddd".to_owned();
14371        running.start("run-2".to_owned());
14372        queue.put(&mut running).unwrap();
14373
14374        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14375        assert_eq!(queued_ids, [queued.id.clone()]);
14376
14377        let mut finished_ids: Vec<String> =
14378            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14379        finished_ids.sort_unstable();
14380        let mut want = vec![failed.id.clone(), held.id.clone()];
14381        want.sort_unstable();
14382        assert_eq!(finished_ids, want);
14383    }
14384
14385    #[test]
14386    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14387        for short in [false, true] {
14388            let dir = tempfile::tempdir().unwrap();
14389            let queue = Queue::at(dir.path().join("queue"));
14390            let questions = ask::Questions::at(dir.path().join("questions"));
14391            let mut running = task();
14392            running.id = "20261013-192213-feb2".into();
14393            running.start("existing-run".into());
14394            queue.put(&mut running).unwrap();
14395            let mut middle = task();
14396            middle.id = "20261013-193611-ca5b".into();
14397            middle.block(
14398                vec![if short {
14399                    "feb2".into()
14400                } else {
14401                    running.id.clone()
14402                }],
14403                None,
14404            );
14405            queue.put(&mut middle).unwrap();
14406            let mut waiting = task();
14407            waiting.id = "20261013-202849-ee37".into();
14408            waiting.block(
14409                vec![if short {
14410                    "ca5b".into()
14411                } else {
14412                    middle.id.clone()
14413                }],
14414                Some("wait for implementation".into()),
14415            );
14416            queue.put(&mut waiting).unwrap();
14417            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14418            let inv = crate::blockers::Inventory::load(&queue, &questions);
14419            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14420            assert!(inv.stuck().is_empty());
14421            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14422            assert!(report.quarantined.is_empty());
14423            assert!(report.asked.is_empty());
14424            resolve_blockers(&queue, &questions);
14425            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14426            assert!(questions.list().is_empty());
14427            // Finishing the transitive prerequisite alone does not satisfy
14428            // the task's direct dependency.
14429            running.succeed(CompletionContext::new(
14430                CompletionActor::DaemonSettle,
14431                None,
14432                dir.path(),
14433                &running,
14434            ));
14435            queue.put(&mut running).unwrap();
14436            resolve_blockers(&queue, &questions);
14437            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14438            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14439            middle = queue.get(&middle.id).unwrap();
14440            middle.succeed(CompletionContext::new(
14441                CompletionActor::DaemonSettle,
14442                None,
14443                dir.path(),
14444                &middle,
14445            ));
14446            queue.put(&mut middle).unwrap();
14447            resolve_blockers(&queue, &questions);
14448            let after = queue.get(&waiting.id).unwrap();
14449            assert_eq!(after.status, TaskStatus::Queued);
14450            assert!(after.blocked_by.is_empty());
14451            assert_eq!(after.instruction, waiting.instruction);
14452        }
14453    }
14454
14455    #[test]
14456    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14457        for future_schema in [false, true] {
14458            let name = "20261013-193611-ca5b";
14459            let mut future = task();
14460            future.id = name.into();
14461            future.schema = crate::queue::SCHEMA + 1;
14462            let contents = if future_schema {
14463                serde_json::to_string(&future).unwrap()
14464            } else {
14465                "corrupt".into()
14466            };
14467            let dir = tempfile::tempdir().unwrap();
14468            let queue = Queue::at(dir.path().join("queue"));
14469            let questions = ask::Questions::at(dir.path().join("questions"));
14470            let mut waiting = task();
14471            waiting.id = "20261013-202849-ee37".into();
14472            waiting.block(vec!["ca5b".into()], None);
14473            queue.put(&mut waiting).unwrap();
14474            std::fs::write(queue.path_of(name), contents).unwrap();
14475            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14476            assert!(
14477                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14478            );
14479            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14480            assert!(report.asked.is_empty());
14481            resolve_blockers(&queue, &questions);
14482            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14483            assert!(questions.list().is_empty());
14484        }
14485        let dir = tempfile::tempdir().unwrap();
14486        let queue = Queue::at(dir.path().join("queue"));
14487        let questions = ask::Questions::at(dir.path().join("questions"));
14488        let mut waiting = task();
14489        waiting.id = "20261013-202849-ee37".into();
14490        waiting.block(vec!["ca5b".into()], None);
14491        queue.put(&mut waiting).unwrap();
14492        let mut done = task();
14493        done.id = "20261013-193611-ca5b".into();
14494        done.succeed(CompletionContext::new(
14495            CompletionActor::Cli,
14496            None,
14497            dir.path(),
14498            &done,
14499        ));
14500        queue.put(&mut done).unwrap();
14501        // An unreadable second match must not disappear from uniqueness
14502        // checks just because Queue::list skips it.
14503        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14504        assert!(queue.get("ca5b").is_err());
14505        assert_eq!(
14506            crate::queue::dependency(&queue, &questions, "ca5b"),
14507            crate::queue::Dependency::Ambiguous
14508        );
14509        resolve_blockers(&queue, &questions);
14510        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14511        assert!(report.asked.is_empty());
14512        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14513        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14514    }
14515
14516    #[test]
14517    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14518        for held in [false, true] {
14519            for question in [false, true] {
14520                for reference in ["ca5b", "20261013-193611-ca5b"] {
14521                    let dir = tempfile::tempdir().unwrap();
14522                    let queue = Queue::at(dir.path().join("queue"));
14523                    let questions = ask::Questions::at(dir.path().join("questions"));
14524                    let mut prerequisite = task();
14525                    prerequisite.id = "20261013-193611-ca5b".into();
14526                    prerequisite.start("existing-run".into());
14527                    queue.put(&mut prerequisite).unwrap();
14528                    let mut waiting = task();
14529                    waiting.id = "20261013-202849-ee37".into();
14530                    if held {
14531                        waiting.hold_machine(Some("waiting for separate consent".into()));
14532                    }
14533                    queue.put(&mut waiting).unwrap();
14534                    let reason = "Deleting saved data requires separate owner consent";
14535                    crate::conduct::apply(
14536                        &queue,
14537                        &questions,
14538                        &crate::conduct::Verdict {
14539                            decisions: vec![crate::conduct::Decision {
14540                                id: waiting.id.clone(),
14541                                blocked_by: vec![reference.into()],
14542                                question: question.then(|| "May the saved data be deleted?".into()),
14543                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14544                                reason: Some(reason.into()),
14545                                ..crate::conduct::Decision::default()
14546                            }],
14547                        },
14548                    )
14549                    .unwrap();
14550                    let before = queue.get(&waiting.id).unwrap();
14551                    if question {
14552                        assert_eq!(before.status, TaskStatus::Blocked);
14553                        let q = questions.get(&before.blocked_by[0]).unwrap();
14554                        assert_eq!(q.summary, "May the saved data be deleted?");
14555                        assert!(q.status.open());
14556                    } else {
14557                        assert_eq!(before.status, TaskStatus::Held);
14558                        let recorded_reason = before.hold_reason.as_deref().unwrap();
14559                        assert!(recorded_reason.starts_with(reason));
14560                        if held {
14561                            assert!(recorded_reason.contains("waiting for separate consent"));
14562                        }
14563                    }
14564                    prerequisite.succeed(CompletionContext::new(
14565                        CompletionActor::DaemonSettle,
14566                        None,
14567                        dir.path(),
14568                        &prerequisite,
14569                    ));
14570                    queue.put(&mut prerequisite).unwrap();
14571                    resolve_blockers(&queue, &questions);
14572                    let after = queue.get(&waiting.id).unwrap();
14573                    assert_eq!(after.status, before.status);
14574                    assert_eq!(after.blocked_by, before.blocked_by);
14575                    assert_eq!(after.hold_reason, before.hold_reason);
14576                    assert_eq!(after.instruction, waiting.instruction);
14577                    if question {
14578                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14579                    }
14580                    assert!(
14581                        queue.next_runnable().is_none(),
14582                        "dependency completion is not consent"
14583                    );
14584                }
14585            }
14586        }
14587    }
14588
14589    #[test]
14590    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14591        let dir = tempfile::tempdir().unwrap();
14592        let queue = Queue::at(dir.path().join("queue"));
14593        let questions = ask::Questions::at(dir.path().join("questions"));
14594
14595        let mut dep = task();
14596        dep.id = "20260101-000001-dep0".to_owned();
14597        dep.succeed(CompletionContext::new(
14598            CompletionActor::DaemonSettle,
14599            None,
14600            dir.path(),
14601            &dep,
14602        ));
14603        queue.put(&mut dep).unwrap();
14604
14605        let mut still_going = task();
14606        still_going.id = "20260101-000002-dep1".to_owned();
14607        queue.put(&mut still_going).unwrap();
14608
14609        let mut blocked = task();
14610        blocked.id = "20260101-000003-main".to_owned();
14611        blocked.block(
14612            vec![dep.id.clone(), still_going.id.clone()],
14613            Some("waits on both".to_owned()),
14614        );
14615        queue.put(&mut blocked).unwrap();
14616
14617        resolve_blockers(&queue, &questions);
14618
14619        let after = queue.get(&blocked.id).unwrap();
14620        assert_eq!(
14621            after.status,
14622            TaskStatus::Blocked,
14623            "one dependency is still outstanding"
14624        );
14625        assert_eq!(after.blocked_by, [still_going.id.clone()]);
14626    }
14627
14628    #[test]
14629    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14630        let dir = tempfile::tempdir().unwrap();
14631        let queue = Queue::at(dir.path().join("queue"));
14632        let questions = ask::Questions::at(dir.path().join("questions"));
14633
14634        let mut q = crate::ask::Question::new(
14635            "20260101-000001-main".to_owned(),
14636            crate::conduct::NODE.to_owned(),
14637            "conduct".to_owned(),
14638            "Which backend?".to_owned(),
14639            String::new(),
14640            Vec::new(),
14641        );
14642        questions.put(&mut q).unwrap();
14643        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14644            .unwrap();
14645        questions.put(&mut q).unwrap();
14646
14647        let mut blocked = task();
14648        blocked.id = "20260101-000001-main".to_owned();
14649        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14650        queue.put(&mut blocked).unwrap();
14651
14652        resolve_blockers(&queue, &questions);
14653
14654        let after = queue.get(&blocked.id).unwrap();
14655        assert_eq!(
14656            after.status,
14657            TaskStatus::Queued,
14658            "the only blocker resolved"
14659        );
14660        assert_eq!(after.answers.len(), 1);
14661        assert_eq!(after.answers[0].question, "Which backend?");
14662        assert_eq!(after.answers[0].answer, "SQLite");
14663
14664        // And the run this task starts next is told about it.
14665        let instruction = instruction_for(&after);
14666        assert!(instruction.contains("Which backend?"));
14667        assert!(instruction.contains("SQLite"));
14668    }
14669
14670    #[test]
14671    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14672        let dir = tempfile::tempdir().unwrap();
14673        let queue = Queue::at(dir.path().join("queue"));
14674        let questions = ask::Questions::at(dir.path().join("questions"));
14675
14676        let mut q = crate::ask::Question::new(
14677            "20260101-000001-main".to_owned(),
14678            crate::conduct::NODE.to_owned(),
14679            "conduct".to_owned(),
14680            "Is the setup done?".to_owned(),
14681            String::new(),
14682            Vec::new(),
14683        );
14684        q.abandon("no answer within 60s of asking");
14685        questions.put(&mut q).unwrap();
14686
14687        let mut blocked = task();
14688        blocked.id = "20260101-000001-main".to_owned();
14689        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14690        queue.put(&mut blocked).unwrap();
14691
14692        resolve_blockers(&queue, &questions);
14693
14694        let after = queue.get(&blocked.id).unwrap();
14695        assert_eq!(
14696            after.status,
14697            TaskStatus::Held,
14698            "never left blocked on nothing"
14699        );
14700        assert!(!after.operator_held(), "a machine hold, for triage");
14701        assert!(
14702            after
14703                .hold_reason
14704                .as_deref()
14705                .unwrap_or_default()
14706                .contains("went unanswered")
14707        );
14708    }
14709
14710    #[test]
14711    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14712        // Reproduces the reported bug (task 3958): a task held out of
14713        // attempts, blocked on a `crate::conduct` follow-up question, must
14714        // come back `held` once that question is answered - never `queued`,
14715        // whatever the answer said - or it silently re-enters the
14716        // competition queue with its attempts already exhausted.
14717        let dir = tempfile::tempdir().unwrap();
14718        let queue = Queue::at(dir.path().join("queue"));
14719        let questions = ask::Questions::at(dir.path().join("questions"));
14720
14721        let mut q = crate::ask::Question::new(
14722            "20260101-000001-main".to_owned(),
14723            crate::conduct::NODE.to_owned(),
14724            "conduct".to_owned(),
14725            "How should this be handled?".to_owned(),
14726            String::new(),
14727            Vec::new(),
14728        );
14729        questions.put(&mut q).unwrap();
14730        q.answer(crate::ask::Answer::Text(
14731            "leave it held, a human will look at it later".to_owned(),
14732        ))
14733        .unwrap();
14734        questions.put(&mut q).unwrap();
14735
14736        let mut held = task();
14737        held.id = "20260101-000001-main".to_owned();
14738        held.hold_machine(Some("out of attempts".to_owned()));
14739        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14740        queue.put(&mut held).unwrap();
14741
14742        resolve_blockers(&queue, &questions);
14743
14744        let after = queue.get(&held.id).unwrap();
14745        assert_eq!(after.status, TaskStatus::Held);
14746        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14747        assert_eq!(
14748            after.answers[0].answer,
14749            "leave it held, a human will look at it later"
14750        );
14751    }
14752
14753    #[test]
14754    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14755        let dir = tempfile::tempdir().unwrap();
14756        let queue = Queue::at(dir.path().join("queue"));
14757        let questions = ask::Questions::at(dir.path().join("questions"));
14758        let mut dep = task();
14759        dep.id = "20260101-000001-gone".to_owned();
14760        queue.put(&mut dep).unwrap();
14761        let mut blocked = task();
14762        blocked.id = "20260101-000003-main".to_owned();
14763        blocked.block(vec![dep.id.clone()], None);
14764        queue.put(&mut blocked).unwrap();
14765
14766        // Claimed, so `remove` cannot rewrite it and the resolver must.
14767        let claim = queue.claim(&blocked.id).unwrap();
14768        queue.remove(&dep.id, false, &questions).unwrap();
14769        drop(claim);
14770        resolve_blockers(&queue, &questions);
14771
14772        let after = queue.get(&blocked.id).unwrap();
14773        assert_eq!(after.status, TaskStatus::Queued);
14774        assert!(after.blocked_by.is_empty());
14775    }
14776
14777    #[test]
14778    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14779        // Reproduces the reported bug: a task blocked on a task id that was
14780        // removed (`magi task rm`, or deleted by hand) can never see that id
14781        // reach `Done`, so the ordinary per-id loop has nothing to notice and
14782        // would otherwise leave the task `blocked` forever with no way for an
14783        // operator to find out why.
14784        let dir = tempfile::tempdir().unwrap();
14785        let queue = Queue::at(dir.path().join("queue"));
14786        let questions = ask::Questions::at(dir.path().join("questions"));
14787
14788        let mut still_going = task();
14789        still_going.id = "20260101-000002-dep1".to_owned();
14790        queue.put(&mut still_going).unwrap();
14791
14792        let mut blocked = task();
14793        blocked.id = "20260101-000003-main".to_owned();
14794        blocked.block(
14795            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14796            Some("waits on both".to_owned()),
14797        );
14798        queue.put(&mut blocked).unwrap();
14799
14800        resolve_blockers(&queue, &questions);
14801
14802        let after = queue.get(&blocked.id).unwrap();
14803        assert_eq!(
14804            after.status,
14805            TaskStatus::Held,
14806            "a missing dependency must not leave the task blocked forever"
14807        );
14808        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14809        assert!(after.blocked_by.is_empty());
14810        let reason = after.hold_reason.as_deref().unwrap_or_default();
14811        assert!(
14812            reason.contains("20260101-000001-gone"),
14813            "the missing id must be named so an operator can tell what happened: {reason}"
14814        );
14815        assert!(
14816            reason.contains(&still_going.id),
14817            "the still-valid dependency must not silently vanish from the record: {reason}"
14818        );
14819    }
14820
14821    #[test]
14822    fn instruction_for_is_unchanged_without_any_answers() {
14823        let t = task();
14824        assert_eq!(instruction_for(&t), t.instruction);
14825    }
14826
14827    #[test]
14828    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14829        let dir = tempfile::tempdir().unwrap();
14830        let q = Queue::at(dir.path().join("queue"));
14831        let src = dir.path().join("shot.png");
14832        std::fs::write(&src, "x").unwrap();
14833        let mut t = task();
14834        q.attach(&mut t, &[src]).unwrap();
14835        let paths = task_attachments(&q, &t).unwrap();
14836        assert_eq!(paths.len(), 1);
14837        assert!(paths[0].is_absolute() && paths[0].is_file());
14838        std::fs::remove_file(&paths[0]).unwrap();
14839        let err = task_attachments(&q, &t).unwrap_err().to_string();
14840        assert!(err.contains("shot.png"), "{err}");
14841    }
14842
14843    #[tokio::test]
14844    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14845        let dir = tempfile::tempdir().unwrap();
14846        let queue_path = dir.path().join("queue");
14847        let queue = Queue::at(queue_path.clone());
14848        let mut t = task();
14849        t.source = Source::Agent {
14850            run: "originating-chat".into(),
14851            node: crate::queue::CHAT_NODE.into(),
14852        };
14853        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14854            stage: "config-fetch",
14855            target: "origin/main".into(),
14856        });
14857        record_config_failure(&mut t, &fetch);
14858        t.hold_machine(Some(format!("{fetch:#}")));
14859        let fetch_key = t.chat_notice_due().unwrap();
14860        t.chat_notices.push(fetch_key.clone());
14861        queue.put(&mut t).unwrap();
14862
14863        let queue = Queue::at(queue_path);
14864        let mut t = queue.get(&t.id).unwrap();
14865        let a = dir.path().join("a.toml");
14866        let b = dir.path().join("b.toml");
14867        for (path, text, new_cause) in [
14868            (&a, "[graph", true),
14869            (&a, "[verify", false),
14870            (&a, "[graph]\nimplementers = 'invalid-type'", true),
14871            (&b, "[graph]\nimplementers = 'invalid-type'", true),
14872        ] {
14873            t.release_operator("test", None);
14874            std::fs::write(path, text).unwrap();
14875            let error = Config::discover_fetched(dir.path(), Some(path))
14876                .await
14877                .unwrap_err();
14878            record_config_failure(&mut t, &error);
14879            t.hold_machine(Some(format!("{error:#}")));
14880            let due = t.chat_notice_due();
14881            assert_eq!(due.is_some(), new_cause, "{error:#}");
14882            if let Some(key) = due {
14883                assert_ne!(key, fetch_key);
14884                t.chat_notices.push(key);
14885            }
14886        }
14887        t.succeed(CompletionContext::new(
14888            CompletionActor::DaemonSettle,
14889            None,
14890            dir.path(),
14891            &t,
14892        ));
14893        assert_eq!(
14894            t.chat_notice_due(),
14895            Some(format!(
14896                "done:{}",
14897                t.completion_history.last().unwrap().occurrence
14898            ))
14899        );
14900    }
14901
14902    #[test]
14903    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14904        let dir = tempfile::tempdir().unwrap();
14905        let queue_path = dir.path().join("queue");
14906        let queue = Queue::at(queue_path.clone());
14907        let mut t = task();
14908        t.source = crate::queue::Source::Agent {
14909            run: "originating-chat".into(),
14910            node: crate::queue::CHAT_NODE.into(),
14911        };
14912        let a = dir.path().join("a.png");
14913        let b = dir.path().join("b.png");
14914        std::fs::write(&a, "a").unwrap();
14915        std::fs::write(&b, "b").unwrap();
14916        queue.attach(&mut t, &[a, b]).unwrap();
14917        let paths = task_attachments(&queue, &t).unwrap();
14918        for path in &paths {
14919            std::fs::remove_file(path).unwrap();
14920        }
14921        let missing = task_attachments(&queue, &t).unwrap_err();
14922        t.attempts += 1;
14923        let reason = missing.to_string();
14924        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14925        let first = t.chat_notice_due().expect("first attachment notice");
14926        t.chat_notices.push(first.clone());
14927        queue.put(&mut t).unwrap();
14928
14929        let queue = Queue::at(queue_path.clone());
14930        let mut t = queue.get(&t.id).unwrap();
14931        assert!(t.chat_notice_due().is_none(), "restart does not replay");
14932        t.release_operator("test", None);
14933        t.attempts += 1;
14934        let missing = task_attachments(&queue, &t).unwrap_err();
14935        t.fail_startup_target(
14936            "startup-attachments",
14937            missing.name,
14938            "same missing attachment with regenerated wording",
14939            1,
14940        );
14941        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14942
14943        std::fs::write(&paths[0], "restored").unwrap();
14944        t.release_operator("test", None);
14945        t.attempts += 1;
14946        let missing = task_attachments(&queue, &t).unwrap_err();
14947        let reason = missing.to_string();
14948        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14949        let second = t
14950            .chat_notice_due()
14951            .expect("different attachment must notify");
14952        assert_ne!(first, second);
14953        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14954    }
14955
14956    #[test]
14957    fn resumed_instruction_is_unchanged_without_any_answers() {
14958        let t = task();
14959        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14960    }
14961
14962    #[test]
14963    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14964        let mut t = task();
14965        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14966        // The run's own instruction on disk predates the answer: it is the
14967        // plain original text `Runner::start` saved before the operator was
14968        // ever asked anything.
14969        let old = t.instruction.clone();
14970
14971        let refreshed = resumed_instruction(&old, &t);
14972        assert!(refreshed.starts_with(&old), "the original text is kept");
14973        assert!(refreshed.contains("Which backend?"));
14974        assert!(refreshed.contains("SQLite"));
14975    }
14976
14977    #[test]
14978    fn resumed_instruction_keeps_an_original_answers_heading() {
14979        let mut t = task();
14980        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14981        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14982
14983        let refreshed = resumed_instruction(&t.instruction, &t);
14984
14985        assert!(
14986            refreshed.starts_with(&t.instruction),
14987            "an answers heading in the original instruction is not the appended block"
14988        );
14989        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14990        assert!(refreshed.contains("Which backend?"));
14991        assert!(refreshed.contains("SQLite"));
14992
14993        let repeated = resumed_instruction(&refreshed, &t);
14994        assert_eq!(
14995            repeated, refreshed,
14996            "only the final appended block is refreshed"
14997        );
14998    }
14999
15000    #[test]
15001    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
15002        let mut t = task();
15003        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
15004
15005        // A first resume appends the block; a second resume of the same run,
15006        // with no new answer in between, must reproduce exactly the same
15007        // text rather than appending the block a second time.
15008        let once = resumed_instruction(&t.instruction, &t);
15009        let twice = resumed_instruction(&once, &t);
15010        assert_eq!(once, twice);
15011        assert_eq!(once.matches("Which backend?").count(), 1);
15012
15013        // A later answer replaces the block wholesale rather than growing it.
15014        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
15015        let refreshed = resumed_instruction(&once, &t);
15016        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
15017        assert!(refreshed.contains("Which backend?"));
15018        assert!(refreshed.contains("Which cache?"));
15019    }
15020
15021    #[test]
15022    fn prepare_instruction_covers_all_three_starters() {
15023        let mut t = task();
15024        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
15025
15026        // Start: a fresh run gets the task text plus every answer so far —
15027        // exactly `instruction_for`.
15028        assert_eq!(
15029            prepare_instruction(&Starter::Start, None, &t),
15030            Some(instruction_for(&t))
15031        );
15032
15033        // Resume: the run's prior instruction is refreshed with the answer,
15034        // not discarded and not left stale.
15035        let old = t.instruction.clone();
15036        assert_eq!(
15037            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
15038            Some(resumed_instruction(&old, &t))
15039        );
15040
15041        // Review: a review-only pass builds its own instruction from the
15042        // branch's history in `crate::graph`, with no task statement at all -
15043        // this boundary must leave it alone.
15044        assert_eq!(
15045            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
15046            None
15047        );
15048    }
15049
15050    #[test]
15051    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
15052        assert_eq!(
15053            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
15054            Starter::Review("magi/eba2/A".to_owned())
15055        );
15056    }
15057
15058    #[test]
15059    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
15060        assert_eq!(
15061            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
15062            Starter::Start,
15063            "a vanished review branch must not fall back to resuming the old run either"
15064        );
15065    }
15066
15067    #[test]
15068    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
15069        let mut t = task();
15070        t.start("old-run".to_owned());
15071        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
15072        t.release();
15073        let branch = t.review_branch.take();
15074        assert_eq!(
15075            choose_starter(branch.as_deref(), true, Some("old-run")),
15076            Starter::Review("magi/eba2/A".to_owned()),
15077            "a review wins over resuming the old run"
15078        );
15079    }
15080
15081    #[test]
15082    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
15083        assert_eq!(
15084            choose_starter(None, false, Some("some-run")),
15085            Starter::Resume("some-run".to_owned())
15086        );
15087        assert_eq!(choose_starter(None, false, None), Starter::Start);
15088    }
15089
15090    #[test]
15091    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
15092        let mut released = task();
15093        released.start("stalled-run".to_owned());
15094        released.requeue();
15095        let unfinished = (!released.fresh_start)
15096            .then(|| Some("stalled-run".to_owned()))
15097            .flatten();
15098        assert_eq!(
15099            choose_starter(None, false, unfinished.as_deref()),
15100            Starter::Start,
15101            "release keeps run history but must not resume it"
15102        );
15103        assert_eq!(released.runs, ["stalled-run"]);
15104    }
15105
15106    #[test]
15107    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
15108        let dir = tempfile::tempdir().unwrap();
15109        let queue = Queue::at(dir.path().join("queue"));
15110        let mut state = run_state(RunStatus::Blocked);
15111        state.merge_decision = Some(crate::merge_decision::Decision {
15112            question: "hold-inquiry".into(),
15113            target: crate::merge_decision::Target {
15114                pr: "https://example.test/pull/1".into(),
15115                head: "reviewed-head".into(),
15116                language: "en".into(),
15117            },
15118            choice: land::HOLD.into(),
15119            closed: false,
15120            replacement_run: None,
15121            replacement_pr: None,
15122        });
15123        let mut t = task();
15124        t.start(state.id.clone());
15125        settle_and_diagnose(
15126            &mut t,
15127            Verdict {
15128                status: RunStatus::Blocked,
15129                left_pr: true,
15130                quota_hit: false,
15131                parked: false,
15132                no_viable_candidates: false,
15133            },
15134            "held",
15135            2,
15136            &state,
15137        );
15138        queue.put(&mut t).unwrap();
15139        t.release_operator("chat", None);
15140        t.edit("revised".into(), "revised instruction".into())
15141            .unwrap();
15142        queue.put(&mut t).unwrap();
15143        drop(state);
15144        assert_eq!(
15145            queue
15146                .get(&t.id)
15147                .unwrap()
15148                .decision_effects
15149                .get("hold-inquiry"),
15150            Some(&format!("decision: {}", land::HOLD))
15151        );
15152    }
15153
15154    fn stopped_public_run(status: RunStatus) -> RunState {
15155        let mut state = run_state(status);
15156        state.driver_exited = true;
15157        state.config.graph.land = true;
15158        state.config.graph.review_rounds = 1;
15159        state.reviews = vec![review_round(1)];
15160        state.merge = Some(crate::run::MergeOutcome {
15161            mode: MergeMode::Pr,
15162            ok: false,
15163            detail: "landing stopped".into(),
15164            empty: false,
15165        });
15166        state.pr = Some(crate::run::PrRecord {
15167            url: "https://example.test/pull/1".into(),
15168            number: 1,
15169            state: "open".into(),
15170            checks: "red".into(),
15171            round: 1,
15172            rounds: 1,
15173            red_at_merge: Vec::new(),
15174        });
15175        state
15176    }
15177
15178    #[test]
15179    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15180        for status in [RunStatus::Blocked, RunStatus::Gating] {
15181            let home = tempfile::tempdir().unwrap();
15182            let mut state = stopped_public_run(status);
15183            state.save_under(home.path()).unwrap();
15184            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15185            assert!(!exhausted_review_budget(&state));
15186            let mut task = held_task_with(&state.id);
15187            task.release();
15188            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15189            assert_eq!(
15190                choose_starter(None, false, unfinished.as_deref()),
15191                Starter::Resume(state.id.clone())
15192            );
15193            let question = action_question(&state.id, resume_action(&state.id));
15194            assert_eq!(
15195                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15196                    state.clone()
15197                )),
15198                ActionDecision::Resume(state.id.clone())
15199            );
15200            // The control-plane command uses this same preflight before pinning.
15201            assert_eq!(
15202                crate::resume::validate(home.path(), &state.id).unwrap().id,
15203                state.id
15204            );
15205            let queue = Queue::at(home.path().join("queue"));
15206            let mut controlled = Task::new(
15207                "resume land".into(),
15208                state.instruction.clone(),
15209                state.repo.clone(),
15210                Source::Agent {
15211                    run: "talk".into(),
15212                    node: crate::queue::CHAT_NODE.into(),
15213                },
15214            );
15215            controlled.runs.push(state.id.clone());
15216            controlled.hold_machine(Some("land stopped".into()));
15217            queue.put(&mut controlled).unwrap();
15218            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15219            assert_eq!(resumed.status, TaskStatus::Queued);
15220            assert_eq!(
15221                resumed.resume_override.unwrap().pinned_run,
15222                Some(state.id.clone())
15223            );
15224            assert_eq!(resumed.attempts, 0);
15225        }
15226    }
15227
15228    #[test]
15229    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15230        for review_rounds in [0, 1] {
15231            let home = tempfile::tempdir().unwrap();
15232            let mut state = run_state(RunStatus::Blocked);
15233            state.config.graph.review_rounds = review_rounds;
15234            if review_rounds > 0 {
15235                let mut review = review_round(1);
15236                review.clean = true;
15237                state.reviews = vec![review];
15238            }
15239            state.gate_ran = true;
15240            state.gate = vec![crate::run::CommandOutcome {
15241                command: "verify".into(),
15242                code: Some(1),
15243                output_tail: "gate failed after repair budget exhausted".into(),
15244                duration_ms: 0,
15245                resource_blocked: false,
15246                ..Default::default()
15247            }];
15248            state.save_under(home.path()).unwrap();
15249            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15250            assert!(exhausted_review_budget(&state));
15251            let mut task = held_task_with(&state.id);
15252            task.release();
15253            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15254            let question = action_question(&state.id, resume_action(&state.id));
15255            assert_ne!(
15256                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15257                    state.clone()
15258                )),
15259                ActionDecision::Resume(state.id.clone())
15260            );
15261            let error = crate::resume::validate(home.path(), &state.id)
15262                .unwrap_err()
15263                .to_string();
15264            assert!(!error.contains("review budget exhausted"), "{error}");
15265            assert!(
15266                error.contains(if review_rounds == 0 {
15267                    "review is disabled"
15268                } else {
15269                    "gate already ran"
15270                }),
15271                "{error}"
15272            );
15273
15274            // An unexecuted gate still has work to do with or without reviews.
15275            state.gate_ran = false;
15276            state.gate.clear();
15277            assert!(!exhausted_review_budget(&state));
15278            assert_eq!(
15279                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15280                Some(state.id)
15281            );
15282        }
15283    }
15284
15285    #[test]
15286    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15287        let home = tempfile::tempdir().unwrap();
15288        let mut state = run_state(RunStatus::Blocked);
15289        state.config.graph.review_rounds = 1;
15290        let mut unresolved = review_round(1);
15291        unresolved.blocking = 1;
15292        unresolved.e2e.push(crate::run::CommandOutcome {
15293            command: "verify".into(),
15294            code: Some(1),
15295            output_tail: "previous verification failed".into(),
15296            ..Default::default()
15297        });
15298        state.reviews.push(unresolved);
15299        state.base_sync = Some(crate::run::BaseSync {
15300            tip: "base".into(),
15301            behind: 1,
15302            attempts: 0,
15303            conflict: None,
15304            already_in: None,
15305        });
15306        state.reserve_base_operation("winner", "base");
15307        state.resource_block = Some(crate::run::ResourceBlock {
15308            cause: crate::run::ResourceBlockCause::Other,
15309            node: "rebase".into(),
15310            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15311            detail: "recording exec failed".into(),
15312            at: jiff::Timestamp::now(),
15313        });
15314        state.save_under(home.path()).unwrap();
15315        assert_eq!(
15316            crate::resume::validate(home.path(), &state.id).unwrap().id,
15317            state.id
15318        );
15319        assert_eq!(
15320            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15321            crate::repair_budget::legacy::Class::SequencerInfrastructure
15322        );
15323        state.finish_base_operation(None);
15324        state.save_under(home.path()).unwrap();
15325        assert!(crate::resume::validate(home.path(), &state.id).is_err());
15326    }
15327
15328    #[test]
15329    fn resource_blocked_verification_resumes_the_same_run() {
15330        for (kind, stage) in [
15331            ("cache", "clean"),
15332            ("coordination", "clean"),
15333            ("cache", "review-e2e"),
15334            ("coordination", "no-reviews"),
15335            ("coordination", "handoff"),
15336        ] {
15337            let home = tempfile::tempdir().unwrap();
15338            let mut state = run_state(RunStatus::Blocked);
15339            state.config.graph.review_rounds = 1;
15340            let mut review = review_round(1);
15341            review.clean = true;
15342            state.reviews = vec![review];
15343            if stage == "review-e2e" {
15344                let review = &mut state.reviews[0];
15345                review.clean = false;
15346                review.blocking = 1;
15347                review.e2e = vec![crate::run::CommandOutcome {
15348                    command: "verify".into(),
15349                    code: None,
15350                    output_tail: "resource wait expired".into(),
15351                    duration_ms: 0,
15352                    resource_blocked: true,
15353                    ..Default::default()
15354                }];
15355            } else if stage == "no-reviews" {
15356                state.config.graph.review_rounds = 0;
15357                state.reviews.clear();
15358            } else if stage == "handoff" {
15359                // A completed final verification can hand off to the gate
15360                // even when the review still carries contested findings.
15361                let review = &mut state.reviews[0];
15362                review.clean = false;
15363                review.blocking = 1;
15364                review.e2e = vec![crate::run::CommandOutcome {
15365                    command: "verify".into(),
15366                    code: Some(0),
15367                    output_tail: String::new(),
15368                    duration_ms: 0,
15369                    resource_blocked: false,
15370                    ..Default::default()
15371                }];
15372            }
15373            state.gate_ran = false;
15374            state.resource_block = Some(crate::run::ResourceBlock {
15375                cause: crate::run::ResourceBlockCause::Other,
15376                node: if stage == "review-e2e" {
15377                    "review"
15378                } else {
15379                    "gate"
15380                }
15381                .into(),
15382                kind: kind.into(),
15383                detail: "resource wait expired".into(),
15384                at: jiff::Timestamp::now(),
15385            });
15386            state.save_under(home.path()).unwrap();
15387            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15388            assert!(!exhausted_review_budget(&state));
15389            let mut task = held_task_with(&state.id);
15390            task.release();
15391            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15392            assert_eq!(
15393                choose_starter(None, false, unfinished.as_deref()),
15394                Starter::Resume(state.id.clone())
15395            );
15396            let question = action_question(&state.id, resume_action(&state.id));
15397            assert_eq!(
15398                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15399                    state.clone()
15400                )),
15401                ActionDecision::Resume(state.id.clone())
15402            );
15403            assert_eq!(
15404                crate::resume::validate(home.path(), &state.id).unwrap().id,
15405                state.id
15406            );
15407            let queue = Queue::at(home.path().join("queue"));
15408            let mut controlled = Task::new(
15409                "resume verification".into(),
15410                state.instruction.clone(),
15411                state.repo.clone(),
15412                Source::Agent {
15413                    run: "talk".into(),
15414                    node: crate::queue::CHAT_NODE.into(),
15415                },
15416            );
15417            controlled.runs.push(state.id.clone());
15418            controlled.hold_machine(Some("verification resource unavailable".into()));
15419            queue.put(&mut controlled).unwrap();
15420            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15421            assert_eq!(resumed.status, TaskStatus::Queued);
15422            assert_eq!(
15423                resumed.resume_override.unwrap().pinned_run,
15424                Some(state.id.clone())
15425            );
15426            assert_eq!(resumed.attempts, 0);
15427
15428            // A genuinely unresolved final review still exhausts the budget.
15429            state.config.graph.review_rounds = 1;
15430            let mut unresolved = review_round(1);
15431            unresolved.blocking = 1;
15432            state.reviews = vec![unresolved];
15433            state.resource_block = None;
15434            state.save_under(home.path()).unwrap();
15435            assert!(exhausted_review_budget(&state));
15436            assert!(crate::resume::validate(home.path(), &state.id).is_err());
15437        }
15438    }
15439
15440    #[tokio::test]
15441    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15442        if !crate::standalone_test(
15443            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15444        ) {
15445            return;
15446        }
15447        let home = tempfile::tempdir().unwrap();
15448        let mut owner = stopped_public_run(RunStatus::Blocked);
15449        owner.save_under(home.path()).unwrap();
15450        let history = vec![owner.id.clone()];
15451        let repo = owner.repo.clone();
15452        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15453        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15454        let initial =
15455            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15456        assert!(
15457            initial.is_pending(),
15458            "a busy record must not hold or resume the task"
15459        );
15460        owner.retired_to = Some("20260101-000001-bbbb".into());
15461        owner.save_under(home.path()).unwrap();
15462        drop(lock);
15463        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15464            .await
15465            .expect("ownership lock released")
15466            .expect("read settled owner");
15467        assert!(
15468            result.is_none(),
15469            "the retired owner must not be resumed from a stale read"
15470        );
15471    }
15472
15473    #[tokio::test]
15474    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15475        if !crate::standalone_test(
15476            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15477        ) {
15478            return;
15479        }
15480        let home = tempfile::tempdir().unwrap();
15481        let mut owner = stopped_public_run(RunStatus::Blocked);
15482        let repo = tempfile::tempdir().unwrap();
15483        crate::git::git(repo.path(), &["init"]).await.unwrap();
15484        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15485        owner.id = "20260101-000001-bbbb".into();
15486        owner.save_under(home.path()).unwrap();
15487        let mut successor = run_state(RunStatus::Blocked);
15488        successor.id = "20260101-000002-cccc".into();
15489        successor.save_under(home.path()).unwrap();
15490        let pruned = "20260101-000000-aaaa".to_owned();
15491        let pruned_dir = home.path().join("runs").join(&pruned);
15492        let nonowners = vec![pruned.clone(), successor.id.clone()];
15493        assert!(
15494            public_resume_owner(home.path(), &nonowners, &owner.repo)
15495                .await
15496                .unwrap()
15497                .is_none()
15498        );
15499        assert!(!pruned_dir.exists());
15500
15501        let lock_path = home
15502            .path()
15503            .join("runs")
15504            .join(&successor.id)
15505            .join("pr-owner.lock");
15506        std::fs::remove_file(&lock_path).unwrap();
15507        std::fs::create_dir(&lock_path).unwrap();
15508        let error = public_resume_owner(home.path(), &nonowners, &owner.repo)
15509            .await
15510            .expect_err("an invalid lock path must stop the scan");
15511        assert!(error.downcast_ref::<std::io::Error>().is_some());
15512        std::fs::remove_dir(lock_path).unwrap();
15513
15514        let runs = vec![pruned, owner.id.clone(), successor.id.clone()];
15515        assert_eq!(
15516            public_resume_owner(home.path(), &runs, &owner.repo)
15517                .await
15518                .unwrap()
15519                .unwrap()
15520                .id,
15521            owner.id
15522        );
15523        let subdir = owner.repo.join("nested");
15524        std::fs::create_dir(&subdir).unwrap();
15525        assert_eq!(
15526            public_resume_owner(home.path(), &runs, &subdir)
15527                .await
15528                .unwrap()
15529                .unwrap()
15530                .id,
15531            owner.id
15532        );
15533        #[cfg(unix)]
15534        {
15535            let alias = home.path().join("repo-alias");
15536            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15537            assert_eq!(
15538                public_resume_owner(home.path(), &runs, &alias.join("nested"))
15539                    .await
15540                    .unwrap()
15541                    .unwrap()
15542                    .id,
15543                owner.id
15544            );
15545        }
15546        let different = tempfile::tempdir().unwrap();
15547        crate::git::git(different.path(), &["init"]).await.unwrap();
15548        assert!(
15549            public_resume_owner(home.path(), &runs, different.path())
15550                .await
15551                .is_err()
15552        );
15553        let mut other_owner = owner.clone();
15554        other_owner.id = "20260101-000003-dddd".into();
15555        other_owner.save_under(home.path()).unwrap();
15556        let mut multiple = runs.clone();
15557        multiple.push(other_owner.id);
15558        assert!(
15559            public_resume_owner(home.path(), &multiple, &owner.repo)
15560                .await
15561                .unwrap_err()
15562                .to_string()
15563                .contains("multiple retained public owners")
15564        );
15565        // Explicit retirement leaves the historical approval on disk but
15566        // removes the predecessor from public-delivery admission.
15567        owner.status = RunStatus::Superseded;
15568        owner.pr.as_mut().unwrap().state = "closed".into();
15569        owner.save_under(home.path()).unwrap();
15570        assert!(
15571            public_resume_owner(home.path(), &runs, &owner.repo)
15572                .await
15573                .unwrap()
15574                .is_none()
15575        );
15576        std::fs::remove_file(
15577            home.path()
15578                .join("runs")
15579                .join(&successor.id)
15580                .join("run.json"),
15581        )
15582        .unwrap();
15583        assert!(
15584            public_resume_owner(home.path(), &runs, &owner.repo)
15585                .await
15586                .is_err()
15587        );
15588    }
15589
15590    #[test]
15591    fn an_ordinary_release_keeps_a_resumable_run_available() {
15592        let mut released = task();
15593        released.start("stalled-run".to_owned());
15594        released.release();
15595        let unfinished = (!released.fresh_start)
15596            .then(|| Some("stalled-run".to_owned()))
15597            .flatten();
15598        assert_eq!(
15599            choose_starter(None, false, unfinished.as_deref()),
15600            Starter::Resume("stalled-run".to_owned()),
15601            "manual release must preserve the normal resume path"
15602        );
15603    }
15604
15605    #[test]
15606    fn resume_refusals_explain_admission_without_changing_task_or_run() {
15607        use crate::handover::{ResumeRefusal, resume_refusal_under};
15608        let home = tempfile::tempdir().unwrap();
15609        let mut exhausted = run_state(RunStatus::Blocked);
15610        exhausted.driver_exited = true;
15611        exhausted.config.graph.review_rounds = 3;
15612        exhausted.reviews = (1..=3).map(review_round).collect();
15613        for refusal in [
15614            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15615            ResumeRefusal::Status(RunStatus::Ready),
15616            ResumeRefusal::Released("20261022-000000-aaaa".into()),
15617            ResumeRefusal::Retired("retirement-successor".into()),
15618            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15619        ] {
15620            let mut state = exhausted.clone();
15621            let expected = match refusal {
15622                ResumeRefusal::Status(_) => {
15623                    state.status = RunStatus::Ready;
15624                    "status `ready`"
15625                }
15626                ResumeRefusal::Released(ref target) => {
15627                    state.released_to = Some(target.clone());
15628                    "execution was released"
15629                }
15630                ResumeRefusal::Retired(ref target) => {
15631                    state.retired_to = Some(target.clone());
15632                    "execution was retired"
15633                }
15634                ResumeRefusal::OwnershipTransferred(ref target) => {
15635                    state.pr_taken_over_by = Some(target.clone());
15636                    "PR ownership was transferred"
15637                }
15638                _ => "review budget exhausted (3/3 rounds used)",
15639            };
15640            assert_eq!(
15641                resume_refusal_under(&state, Some(home.path())),
15642                Some(refusal.clone())
15643            );
15644            assert_eq!(
15645                refusal.successor(),
15646                state
15647                    .released_to
15648                    .as_deref()
15649                    .or(state.retired_to.as_deref())
15650                    .or(state.pr_taken_over_by.as_deref())
15651            );
15652            state.save_under(home.path()).unwrap();
15653            let queue = Queue::at(home.path().join("queue"));
15654            let mut task = Task::new(
15655                "retained implementation".into(),
15656                state.instruction.clone(),
15657                state.repo.clone(),
15658                Source::Agent {
15659                    run: "talk".into(),
15660                    node: crate::queue::CHAT_NODE.into(),
15661                },
15662            );
15663            task.runs.push(state.id.clone());
15664            task.hold_machine(Some("stopped".into()));
15665            queue.put(&mut task).unwrap();
15666            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15667            let before_run = serde_json::to_value(&state).unwrap();
15668            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15669                .unwrap_err()
15670                .to_string();
15671            assert!(error.contains(expected), "{error}");
15672            assert!(!error.contains("only a stalled or blocked"), "{error}");
15673            if matches!(refusal, ResumeRefusal::Status(_)) {
15674                assert!(
15675                    error.contains("is final; there is nothing left to resume"),
15676                    "{error}"
15677                );
15678            }
15679            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15680                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15681                assert!(error.contains("review-only successor with a new review budget"));
15682                assert!(error.contains("does not resume this run"));
15683            }
15684            for target in [
15685                &state.released_to,
15686                &state.retired_to,
15687                &state.pr_taken_over_by,
15688            ]
15689            .into_iter()
15690            .flatten()
15691            {
15692                let short = if state.retired_to.as_ref() == Some(target) {
15693                    target.as_str()
15694                } else {
15695                    crate::run::short_of(target)
15696                };
15697                assert!(
15698                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
15699                    "{error}"
15700                );
15701                if short != target {
15702                    assert!(!error.contains(target), "full successor id leaked: {error}");
15703                }
15704            }
15705            assert_eq!(
15706                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15707                before_task
15708            );
15709            assert_eq!(
15710                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15711                    .unwrap(),
15712                before_run
15713            );
15714            let question = action_question(&state.id, resume_action(&state.id));
15715            for phrases in [&PHRASES_EN, &PHRASES_JA] {
15716                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15717                    RunState::load_under(id, home.path())
15718                });
15719                let ActionDecision::Refuse(detail) = decision else {
15720                    panic!(
15721                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15722                        state.id,
15723                        home.path().display()
15724                    );
15725                };
15726                assert!(detail.contains(expected), "{detail}");
15727            }
15728        }
15729        // Preserve predicate ordering, while keeping every recorded destination visible.
15730        exhausted.status = RunStatus::Ready;
15731        exhausted.released_to = Some("released".into());
15732        exhausted.retired_to = Some("retired".into());
15733        exhausted.pr_taken_over_by = Some("owner".into());
15734        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15735        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15736        let detail = reason.diagnostic(&exhausted);
15737        for target in ["released", "retired", "owner"] {
15738            assert!(detail.contains(&format!("magi show {target}")));
15739        }
15740    }
15741
15742    #[test]
15743    fn resume_action_ignores_question_checkpoints_in_another_home() {
15744        crate::run::pin_test_home();
15745        let home = tempfile::tempdir().unwrap();
15746        let mut state = run_state(RunStatus::Blocked);
15747        // The private directory reserves this fixture's identity even while
15748        // other tests write questions into the process-wide store.
15749        state.id = format!(
15750            "resume-context-{}",
15751            home.path().file_name().unwrap().to_str().unwrap()
15752        );
15753        state.driver_exited = true;
15754        state.config.graph.review_rounds = 1;
15755        state.reviews = vec![review_round(1)];
15756        state.save_under(home.path()).unwrap();
15757        let task = held_task_with(&state.id);
15758        let answer = action_question(&state.id, resume_action(&state.id));
15759        let mut checkpoint = approval_question(&state.id);
15760        let foreign = Questions::open();
15761        foreign.put(&mut checkpoint).unwrap();
15762        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15763        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15764            RunState::load_under(id, home.path())
15765        });
15766        let matching: Vec<_> = foreign
15767            .list()
15768            .into_iter()
15769            .filter(|q| q.run == state.id && q.status.open())
15770            .collect();
15771        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15772        assert!(
15773            matches!(decision, ActionDecision::Refuse(_)),
15774            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15775            state.id,
15776            home.path().display(),
15777            crate::run::test_home().display()
15778        );
15779        assert_eq!(
15780            refusal,
15781            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15782        );
15783        let local = Questions::at(home.path().join("questions"));
15784        for status in [
15785            ask::QuestionStatus::Open,
15786            ask::QuestionStatus::Answered,
15787            ask::QuestionStatus::Abandoned,
15788        ] {
15789            let mut question = checkpoint.clone();
15790            match status {
15791                ask::QuestionStatus::Open => {}
15792                ask::QuestionStatus::Answered => {
15793                    question
15794                        .answer(ask::Answer::Choice(question.choices[0].clone()))
15795                        .unwrap();
15796                }
15797                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15798            }
15799            local.put(&mut question).unwrap();
15800            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15801                RunState::load_under(id, home.path())
15802            });
15803            if status.open() {
15804                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15805            } else {
15806                assert!(
15807                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15808                    "status={status:?}, decision={decision:?}"
15809                );
15810            }
15811        }
15812    }
15813
15814    #[test]
15815    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15816        let home = tempfile::tempdir().unwrap();
15817        let mut state = run_state(RunStatus::Stalled);
15818        state.id = format!(
15819            "resume-driver-{}",
15820            home.path().file_name().unwrap().to_str().unwrap()
15821        );
15822        state.driver_claimed = Some(false);
15823        state.save_under(home.path()).unwrap();
15824        let task = held_task_with(&state.id);
15825        let question = action_question(&state.id, resume_action(&state.id));
15826        let decide = || {
15827            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15828                RunState::load_under(id, home.path())
15829            })
15830        };
15831        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15832        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15833        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15834        match decide() {
15835            ActionDecision::Refuse(detail) => {
15836                assert!(
15837                    detail.starts_with("run already has a live driver: "),
15838                    "{detail}"
15839                );
15840                assert!(
15841                    detail.contains(&expected_lock.display().to_string()),
15842                    "{detail}"
15843                );
15844            }
15845            other => panic!("expected live driver refusal, got {other:?}"),
15846        }
15847        drop(lease);
15848        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15849    }
15850
15851    #[test]
15852    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15853        let home = tempfile::tempdir().unwrap();
15854        let mut state = run_state(RunStatus::Blocked);
15855        state.driver_exited = true;
15856        state.config.graph.review_rounds = 1;
15857        state.reviews = vec![review_round(1)];
15858        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15859        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15860            let mut saved = state.clone();
15861            match checkpoint {
15862                "publication" => saved.pr_publication_pending = true,
15863                "approval" => {
15864                    saved.land_approval = Some(crate::run::LandApproval {
15865                        question: "approval".into(),
15866                        head: "head".into(),
15867                    })
15868                }
15869                "armed" => saved.land_armed_head = Some("head".into()),
15870                "landing" => saved.status = RunStatus::Landing,
15871                _ => {
15872                    let mut question = ask::Question::new(
15873                        saved.id.clone(),
15874                        "review".into(),
15875                        "review-1".into(),
15876                        "continue?".into(),
15877                        String::new(),
15878                        vec!["continue".into()],
15879                    );
15880                    ask::Questions::at(home.path().join("questions"))
15881                        .put(&mut question)
15882                        .unwrap();
15883                }
15884            }
15885            saved.save_under(home.path()).unwrap();
15886            assert!(
15887                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15888                "{checkpoint}"
15889            );
15890            assert!(
15891                crate::resume::validate(home.path(), &saved.id).is_ok(),
15892                "{checkpoint}"
15893            );
15894        }
15895    }
15896
15897    #[test]
15898    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15899        let mut state = run_state(RunStatus::Blocked);
15900        state.config.graph.review_rounds = 3;
15901        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15902        assert!(exhausted_review_budget(&state));
15903
15904        // One round still unused: resuming can still ask a reviewer something.
15905        state.reviews.pop();
15906        assert!(!exhausted_review_budget(&state));
15907
15908        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
15909        // count: only a `Blocked` run re-enters the review loop on resume.
15910        let mut stalled = run_state(RunStatus::Stalled);
15911        stalled.config.graph.review_rounds = 1;
15912        stalled.reviews = vec![review_round(1)];
15913        assert!(!exhausted_review_budget(&stalled));
15914    }
15915
15916    fn review_round(round: usize) -> crate::run::ReviewRound {
15917        crate::run::ReviewRound {
15918            round,
15919            head: "deadbeef".to_owned(),
15920            verified_head: None,
15921            verified_at: None,
15922            reviews: Vec::new(),
15923            e2e: Vec::new(),
15924            verify_retried: false,
15925            e2e_deferred: false,
15926            e2e_defer_reason: None,
15927            fix: None,
15928            blocking: 0,
15929            answered: 1,
15930            expected: 1,
15931            clean: false,
15932            progressed: true,
15933            vote_split: false,
15934            reconsideration: Vec::new(),
15935            verdict: None,
15936        }
15937    }
15938
15939    #[test]
15940    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15941        let mut run = RunState::new(
15942            PathBuf::from("/repo"),
15943            "main".to_owned(),
15944            "abc1234def".to_owned(),
15945            "add retries".to_owned(),
15946            Config::default(),
15947        );
15948        run.status = RunStatus::Judging;
15949        run.parked = true;
15950        let mut task = Task::new(
15951            "add retries".to_owned(),
15952            "add retries".to_owned(),
15953            PathBuf::from("/repo"),
15954            crate::queue::Source::Human,
15955        );
15956        task.status = TaskStatus::Failed;
15957        task.runs = vec![run.id.clone()];
15958        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15959        assert!(with(&task, &run), "parked after judging is the case");
15960        let mut parked_task = task.clone();
15961        parked_task.status = TaskStatus::Parked;
15962        assert!(with(&parked_task, &run), "the Parked status is the case");
15963
15964        let mut not_parked = run.clone();
15965        not_parked.parked = false;
15966        not_parked.status = RunStatus::Stalled;
15967        assert!(!with(&task, &not_parked), "a stall is the conductor's");
15968
15969        let mut fresh = task.clone();
15970        fresh.fresh_start = true;
15971        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15972
15973        let mut review = task.clone();
15974        review.review_branch = Some("magi/x/A".to_owned());
15975        assert!(!with(&review, &run), "review is ranked before resume");
15976
15977        let mut held = task.clone();
15978        held.status = TaskStatus::Held;
15979        assert!(!with(&held, &run), "a hold stays visible to the conductor");
15980
15981        let mut released = run.clone();
15982        released.released_to = Some("20260901-000000-new1".to_owned());
15983        assert!(!with(&task, &released), "nothing left to resume into");
15984
15985        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15986            "unreadable"
15987        )));
15988    }
15989
15990    #[test]
15991    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15992        let mut released = RunState::new(
15993            PathBuf::from("/repo"),
15994            "main".to_owned(),
15995            "abc1234def".to_owned(),
15996            "add retries".to_owned(),
15997            Config::default(),
15998        );
15999        released.status = RunStatus::Blocked;
16000        assert_eq!(
16001            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
16002            Some(released.id.clone())
16003        );
16004        released.released_to = Some("20260901-000000-new1".to_owned());
16005        assert_eq!(
16006            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
16007            None,
16008            "there is nothing left to resume it into"
16009        );
16010    }
16011
16012    #[test]
16013    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
16014        // Mirrors the failure this exists to close: a task's last run ended
16015        // `Blocked` with the review budget spent, `crate::conduct` chose
16016        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
16017        // evidence), and without this check `attempt` would go on treating
16018        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
16019        // review loop iterates zero times over an already-spent budget, so
16020        // the resumed run settles right back to `Blocked` having asked nobody
16021        // anything, and `Requeue`'s promised fresh competition never happens.
16022        let mut exhausted = RunState::new(
16023            PathBuf::from("/repo"),
16024            "main".to_owned(),
16025            "abc1234def".to_owned(),
16026            "add retries".to_owned(),
16027            Config::default(),
16028        );
16029        exhausted.status = RunStatus::Blocked;
16030        exhausted.config.graph.review_rounds = 1;
16031        exhausted.reviews = vec![review_round(1)];
16032
16033        assert_eq!(
16034            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
16035            None,
16036            "an exhausted `Blocked` run must not be offered as resumable"
16037        );
16038
16039        // A `Blocked` run with rounds still unused is genuinely worth
16040        // resuming, and must still be found.
16041        let mut has_budget_left = RunState::new(
16042            PathBuf::from("/repo"),
16043            "main".to_owned(),
16044            "abc1234def".to_owned(),
16045            "add retries".to_owned(),
16046            Config::default(),
16047        );
16048        has_budget_left.status = RunStatus::Blocked;
16049        has_budget_left.config.graph.review_rounds = 3;
16050        has_budget_left.reviews = vec![review_round(1)];
16051
16052        assert_eq!(
16053            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
16054                Ok(has_budget_left.clone())
16055            }),
16056            Some(has_budget_left.id.clone())
16057        );
16058    }
16059
16060    #[test]
16061    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
16062        let mut run = RunState::new(
16063            PathBuf::from("/repo"),
16064            "main".to_owned(),
16065            "abc1234def".to_owned(),
16066            "add retries".to_owned(),
16067            Config::default(),
16068        );
16069        run.status = RunStatus::Blocked;
16070        run.config.graph.review_rounds = 1;
16071        run.reviews = vec![review_round(1)];
16072        run.pr_publication_pending = true;
16073        assert_eq!(
16074            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
16075            Some(run.id.clone()),
16076            "a spent review budget must not turn a failed publication into a re-competition"
16077        );
16078    }
16079
16080    #[test]
16081    fn retained_attempt_load_ignores_only_missing_run_directories() {
16082        let home = tempfile::tempdir().unwrap();
16083        let mut run = run_state(RunStatus::Ready);
16084        let dir = home.path().join("runs").join(&run.id);
16085        assert!(
16086            load_retained_attempt(home.path(), &run.id)
16087                .unwrap()
16088                .is_none()
16089        );
16090        run.save_under(home.path()).unwrap();
16091        assert_eq!(
16092            load_retained_attempt(home.path(), &run.id)
16093                .unwrap()
16094                .unwrap()
16095                .id,
16096            run.id
16097        );
16098        std::fs::remove_file(dir.join("run.json")).unwrap();
16099        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16100        std::fs::write(dir.join("run.json"), "invalid").unwrap();
16101        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16102        std::fs::remove_dir_all(&dir).unwrap();
16103        std::fs::write(&dir, "not a directory").unwrap();
16104        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16105    }
16106
16107    #[test]
16108    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
16109        let mut task = Task::new(
16110            "recover work".into(),
16111            "recover work".into(),
16112            PathBuf::from("/repo"),
16113            crate::queue::Source::Human,
16114        );
16115        let mut history = std::collections::BTreeMap::new();
16116        for index in 0..8 {
16117            let mut run = run_state(RunStatus::Blocked);
16118            run.id = format!("20260101-000000-{index:04}");
16119            run.base_commit = format!("upstream-{index}");
16120            // Seven empty newer attempts must not erase the old recovery owner.
16121            if index > 0 {
16122                run.candidates.clear();
16123            }
16124            task.runs.extend([run.id.clone(), run.id.clone()]);
16125            history.insert(run.id.clone(), run);
16126            task.requeue();
16127        }
16128        let check = |task: &Task, starter: &Starter, limit| {
16129            retained_attempt_hold(task, starter, limit, |id| Ok(history.get(id).cloned()))
16130        };
16131        task.runs.push("20260101-000001-aaaa".into());
16132        assert!(
16133            check(&task, &Starter::Start, 8)
16134                .unwrap()
16135                .contains("8 unretired")
16136        );
16137        assert!(check(&task, &Starter::Start, 9).is_none());
16138        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
16139        task.release_operator("owner", None);
16140        assert_eq!(task.attempts, 0);
16141        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
16142        assert!(check(&restored, &Starter::Start, 8).is_some());
16143        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
16144        assert!(check(&restored, &Starter::Start, 0).is_none());
16145    }
16146
16147    #[test]
16148    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
16149        let tmp = tempfile::tempdir().unwrap();
16150        let mut task = Task::new(
16151            "recover selected PR".into(),
16152            "preserve implementation".into(),
16153            tmp.path().join("repo"),
16154            crate::queue::Source::Human,
16155        );
16156        let mut failed = run_state(RunStatus::Failed);
16157        failed.id = "20260101-000000-fail".into();
16158        failed.candidates.clear();
16159        failed.prep_complete = Some(false);
16160        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16161        failed.startup = Some(crate::run::Startup {
16162            kind: "pr-recovery".into(),
16163            branch: Some("selected-public-head".into()),
16164            stage: "worktree-setup".into(),
16165            complete: false,
16166            failure: Some("setup modified a tracked file and failed".into()),
16167        });
16168        // Setup may fail before a candidate is recorded; its dirty worktree
16169        // still needs protection and consumes the independent retained bound.
16170        let worktree = failed.worktree_root().join("under-review");
16171        std::fs::create_dir_all(&worktree).unwrap();
16172        let retained_edit = worktree.join("implementation");
16173        std::fs::write(&retained_edit, "retained setup edit").unwrap();
16174        task.record_startup_failure(crate::run::StartupFailure {
16175            run: failed.id.clone(),
16176            stage: "worktree-setup".into(),
16177        });
16178        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
16179        assert!(task.runs.is_empty() && task.passes.is_empty());
16180        assert_eq!(task.attempts, 0);
16181        let starter = Starter::Review("selected-public-head".into());
16182        assert!(
16183            retained_attempt_hold(&task, &starter, 1, |_| Ok(Some(failed.clone())))
16184                .unwrap()
16185                .contains("1 unretired")
16186        );
16187        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(Some(failed.clone()))).is_none());
16188        assert!(
16189            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
16190                .unwrap()
16191                .contains("Cannot verify")
16192        );
16193        assert!(
16194            retained_attempt_hold(&task, &starter, 2, |_| Ok(None))
16195                .unwrap()
16196                .contains("Cannot verify")
16197        );
16198        // Older or mixed writers can link the same reservation in both lists.
16199        let mut mixed = task.clone();
16200        mixed.runs.push(failed.id.clone());
16201        mixed
16202            .startup_failures
16203            .push(task.startup_failures[0].clone());
16204        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(Some(failed.clone()))).is_none());
16205        assert!(
16206            retained_attempt_hold(&mixed, &starter, 2, |_| Ok(None))
16207                .unwrap()
16208                .contains("Cannot verify")
16209        );
16210        failed.retired_to = Some("verified-recovery-owner".into());
16211        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(Some(failed.clone()))).is_none());
16212        assert!(
16213            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
16214                panic!("resuming the existing owner must not allocate a new attempt")
16215            })
16216            .is_none()
16217        );
16218        assert_eq!(
16219            std::fs::read_to_string(retained_edit).unwrap(),
16220            "retained setup edit"
16221        );
16222        assert!(task.runs.is_empty() && task.passes.is_empty());
16223        assert_eq!(task.attempts, 0);
16224    }
16225
16226    #[test]
16227    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
16228        let mut task = Task::new(
16229            "recover work".into(),
16230            "recover work".into(),
16231            PathBuf::from("/repo"),
16232            crate::queue::Source::Human,
16233        );
16234        let mut run = run_state(RunStatus::Superseded);
16235        run.candidates.clear();
16236        task.runs.push(run.id.clone());
16237        assert!(
16238            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_some()
16239        );
16240        run.retired_to = Some("authority".into());
16241        assert!(
16242            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_none()
16243        );
16244        run.retired_to = None;
16245        run.released_to = Some("authority".into());
16246        assert!(
16247            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_none()
16248        );
16249        assert!(
16250            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
16251                .unwrap()
16252                .contains("Cannot verify")
16253        );
16254        // Resuming an existing owner needs no new inventory or worktree budget.
16255        assert!(
16256            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
16257                panic!("resume must not load historical attempts")
16258            })
16259            .is_none()
16260        );
16261    }
16262
16263    #[test]
16264    fn retired_resume_requires_a_valid_same_repository_authority() {
16265        let mut source = run_state(RunStatus::Blocked);
16266        let mut empty = run_state(RunStatus::Blocked);
16267        empty.retired_to = Some(source.id.clone());
16268        let runs = vec![source.id.clone(), empty.id.clone()];
16269        let resolve = |source: &RunState, empty: &RunState| {
16270            unfinished_run_with(&runs, "fixture", |id| {
16271                if id == source.id {
16272                    Ok(source.clone())
16273                } else if id == empty.id {
16274                    Ok(empty.clone())
16275                } else {
16276                    bail!("unreadable authority")
16277                }
16278            })
16279        };
16280        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16281        assert_eq!(
16282            choose_starter(None, false, resolve(&source, &empty).as_deref()),
16283            Starter::Resume(source.id.clone())
16284        );
16285        source.retired_to = Some(empty.id.clone());
16286        assert!(
16287            resolve(&source, &empty).is_none(),
16288            "cycles do not revive obsolete runs"
16289        );
16290        source.retired_to = None;
16291        source.repo = PathBuf::from("/another-repository");
16292        assert!(resolve(&source, &empty).is_none());
16293        source.repo = empty.repo.clone();
16294        source.released_to = Some("later".into());
16295        assert!(resolve(&source, &empty).is_none());
16296        empty.retired_to = Some("unlisted-run".into());
16297        assert!(resolve(&source, &empty).is_none());
16298    }
16299
16300    #[test]
16301    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16302        // A task whose history holds an *older* run that still looks
16303        // resumable (say, a competition `Runner::review` was started
16304        // alongside after that older run went `Stalled`) and a *newest* run
16305        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
16306        // on this task must mean a fresh competition — falling back to the
16307        // stale, superseded `Stalled` run instead would resurrect history
16308        // nothing asked to revisit and silently defeat the requeue.
16309        let mut older_stalled = RunState::new(
16310            PathBuf::from("/repo"),
16311            "main".to_owned(),
16312            "abc1234def".to_owned(),
16313            "add retries".to_owned(),
16314            Config::default(),
16315        );
16316        older_stalled.status = RunStatus::Stalled;
16317
16318        let mut newest_exhausted = RunState::new(
16319            PathBuf::from("/repo"),
16320            "main".to_owned(),
16321            "abc1234def".to_owned(),
16322            "add retries".to_owned(),
16323            Config::default(),
16324        );
16325        newest_exhausted.status = RunStatus::Blocked;
16326        newest_exhausted.config.graph.review_rounds = 1;
16327        newest_exhausted.reviews = vec![review_round(1)];
16328
16329        assert_eq!(
16330            unfinished_run_with(
16331                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16332                "t",
16333                |_| Ok(newest_exhausted.clone())
16334            ),
16335            None,
16336            "the newest run is exhausted, so nothing here is worth resuming - \
16337             least of all the older, already-superseded run"
16338        );
16339    }
16340
16341    #[test]
16342    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16343        assert_eq!(
16344            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16345                Err(anyhow::anyhow!("fixture is absent"))
16346            }),
16347            None
16348        );
16349    }
16350
16351    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16352        let mut q = ask::Question::new(
16353            run.to_owned(),
16354            "implement".to_owned(),
16355            "impl-A".to_owned(),
16356            "continue?".to_owned(),
16357            String::new(),
16358            vec!["resume で続行する".to_owned(), "other".to_owned()],
16359        );
16360        q.actions.insert("resume で続行する".to_owned(), action);
16361        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16362            .unwrap();
16363        q
16364    }
16365
16366    fn held_task_with(run: &str) -> Task {
16367        let mut t = task();
16368        t.runs = vec![run.to_owned()];
16369        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16370        t
16371    }
16372
16373    fn resume_action(run: &str) -> ask::ChoiceAction {
16374        ask::ChoiceAction::Resume { run: run.into() }
16375    }
16376
16377    #[test]
16378    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16379        let home = crate::run::test_home();
16380        for parked in [false, true] {
16381            let mut t = task();
16382            t.start("A".into());
16383            t.start("B".into());
16384            assert_eq!(t.runs, vec!["A", "B"]);
16385            t.start("A".into());
16386            let mut resumed = run_state(RunStatus::Blocked);
16387            resumed.id = "A".into();
16388            resumed.parked = parked;
16389            resumed.driver_exited = true;
16390            t.hold_machine(Some("resumed run stopped".into()));
16391            let q = action_question("A", resume_action("A"));
16392            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16393            assert_eq!(
16394                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16395                    assert_eq!(id, "A");
16396                    Ok(resumed.clone())
16397                }),
16398                ActionDecision::Resume("A".into())
16399            );
16400            assert_eq!(
16401                action_standing(&t, &action_question("B", resume_action("B"))),
16402                ActionStanding::Stale
16403            );
16404            t.release_operator("cli", None);
16405            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16406                assert_eq!(id, "A");
16407                Ok(resumed.clone())
16408            });
16409            assert_eq!(
16410                choose_starter(None, false, unfinished.as_deref()),
16411                Starter::Resume("A".into())
16412            );
16413            assert_eq!(t.runs, vec!["B", "A"]);
16414        }
16415    }
16416
16417    #[test]
16418    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16419        let home = crate::run::test_home();
16420        let mut state = crate::land::tests::repair_state(true, true);
16421        state.status = RunStatus::Landing;
16422        state.parked = true;
16423        state.driver_exited = true;
16424        let mut q = ask::Question::new(
16425            state.id.clone(),
16426            land::APPROVAL_NODE.into(),
16427            "land".into(),
16428            "Merge?".into(),
16429            String::new(),
16430            vec![land::APPROVE.into(), land::HOLD.into()],
16431        );
16432        q.id = state.id.clone();
16433        state.land_approval = Some(crate::run::LandApproval {
16434            question: q.id.clone(),
16435            head: "current-head".into(),
16436        });
16437        assert!(land::upgrade_repair_choice(&mut q, &state));
16438        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16439        let mut task = held_task_with(&state.id);
16440        task.status = TaskStatus::Parked;
16441        assert_eq!(
16442            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16443            ActionDecision::Resume(state.id.clone())
16444        );
16445        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16446        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16447        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16448        assert_eq!(
16449            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16450            ActionDecision::Resume(state.id.clone()),
16451            "a repair answer newer than the manual hold resumes the existing owner"
16452        );
16453        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16454        for answered_at in [q.answered_at, None] {
16455            let mut older = q.clone();
16456            older.answered_at = answered_at;
16457            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| Ok(state.clone()));
16458            let ActionDecision::Refuse(reason) = refused else {
16459                panic!("expected an actionable refusal, got {refused:?}");
16460            };
16461            assert!(reason.contains("later operator decision"));
16462            assert!(reason.contains(&format!("magi task release {}", task.id)));
16463        }
16464        let mut revised = state.clone();
16465        crate::instruction_revision_control::adopt_into_run(
16466            &mut revised,
16467            "cli/revision",
16468            "revision-repair",
16469            "new task",
16470            1,
16471            "current-head",
16472            "pr",
16473        );
16474        task.status = TaskStatus::Queued;
16475        assert_eq!(
16476            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(revised.clone())),
16477            ActionDecision::Stale
16478        );
16479        let mut stop = q.clone();
16480        stop.status = ask::QuestionStatus::Open;
16481        stop.answer = None;
16482        let choice = crate::merge_decision::WITHDRAW;
16483        stop.choices.push(choice.into());
16484        stop.actions.insert(choice.into(), resume_action(&state.id));
16485        stop.answer(ask::Answer::Choice(choice.into())).unwrap();
16486        stop.answered_at = q.answered_at;
16487        assert_eq!(
16488            decide_action(&home, &task, &stop, &PHRASES_EN, |_| Ok(revised)),
16489            ActionDecision::Stale
16490        );
16491        task.status = TaskStatus::Parked;
16492        task.operator_decided_at = None;
16493        let mut superseded = state.clone();
16494        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16495        assert_eq!(
16496            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16497            ActionDecision::Stale
16498        );
16499        for case in 1..4 {
16500            let mut changed = state.clone();
16501            match case {
16502                1 => changed.status = RunStatus::Blocked,
16503                2 => changed.released_to = Some("new-owner".into()),
16504                _ => changed.land_approval.as_mut().unwrap().head.clear(),
16505            }
16506            assert!(matches!(
16507                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16508                ActionDecision::Refuse(_)
16509            ));
16510        }
16511        assert!(matches!(
16512            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16513                "missing owner"
16514            )),
16515            ActionDecision::Refuse(_)
16516        ));
16517        task.runs.push("replacement".into());
16518        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16519        assert_eq!(
16520            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16521                "old owner must not load"
16522            )),
16523            ActionDecision::Stale
16524        );
16525    }
16526
16527    #[test]
16528    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16529        let mut state = crate::land::tests::repair_state(true, true);
16530        state.status = RunStatus::Landing;
16531        state.parked = true;
16532        state.driver_exited = true;
16533        let mut q = ask::Question::new(
16534            state.id.clone(),
16535            land::APPROVAL_NODE.into(),
16536            "land".into(),
16537            "Merge?".into(),
16538            String::new(),
16539            vec![land::APPROVE.into(), land::HOLD.into()],
16540        );
16541        q.id = state.id.clone();
16542        state.land_approval = Some(crate::run::LandApproval {
16543            question: q.id.clone(),
16544            head: "current-head".into(),
16545        });
16546        state.save().unwrap();
16547        land::upgrade_repair_choice(&mut q, &state);
16548        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16549        Questions::open().put(&mut q).unwrap();
16550        let tmp = tempfile::tempdir().unwrap();
16551        let queue = Queue::at(tmp.path().join("queue"));
16552        let mut task = held_task_with(&state.id);
16553        task.status = TaskStatus::Parked;
16554        queue.put(&mut task).unwrap();
16555        let empty = Arc::new(tokio::sync::Semaphore::new(0));
16556        let free = Arc::new(tokio::sync::Semaphore::new(1));
16557        assert!(matches!(
16558            claim_dispatch(&queue, &task, false, &empty, &free),
16559            Err(SkipReason::OrdinaryCapacity)
16560        ));
16561        assert!(matches!(
16562            claim_dispatch(&queue, &task, true, &free, &free),
16563            Err(SkipReason::CoolingDown)
16564        ));
16565        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16566        assert!(claim.permit.is_some());
16567        assert!(matches!(
16568            claim_dispatch(&queue, &task, false, &free, &free),
16569            Err(SkipReason::ClaimUnavailable)
16570        ));
16571        drop(claim);
16572        Questions::open()
16573            .update(&q.id, |q| {
16574                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16575                Ok(())
16576            })
16577            .unwrap();
16578        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16579        assert!(claim.permit.is_none());
16580        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16581    }
16582
16583    #[test]
16584    fn decide_action_resumes_only_the_latest_resumable_run() {
16585        let home = crate::run::test_home();
16586        let t = held_task_with("r1");
16587        let q = action_question("r1", resume_action("r1"));
16588        let load = |s: RunState| move |_: &str| Ok(s);
16589        assert_eq!(
16590            decide_action(
16591                &home,
16592                &t,
16593                &q,
16594                &PHRASES_EN,
16595                load(run_state(RunStatus::Blocked))
16596            ),
16597            ActionDecision::Resume("r1".into())
16598        );
16599        // Not the latest run of the task.
16600        let q_other = action_question("r1", resume_action("r0"));
16601        assert!(matches!(
16602            decide_action(
16603                &home,
16604                &t,
16605                &q_other,
16606                &PHRASES_EN,
16607                load(run_state(RunStatus::Blocked))
16608            ),
16609            ActionDecision::Refuse(_)
16610        ));
16611        // A finished run cannot make progress.
16612        assert!(matches!(
16613            decide_action(
16614                &home,
16615                &t,
16616                &q,
16617                &PHRASES_EN,
16618                load(run_state(RunStatus::Ready))
16619            ),
16620            ActionDecision::Refuse(_)
16621        ));
16622        // A released one either.
16623        let mut released = run_state(RunStatus::Blocked);
16624        released.released_to = Some("elsewhere".into());
16625        assert!(matches!(
16626            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16627            ActionDecision::Refuse(_)
16628        ));
16629        // Unreadable state is a refusal, never a fresh competition.
16630        assert!(matches!(
16631            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16632            ActionDecision::Refuse(_)
16633        ));
16634    }
16635
16636    #[test]
16637    fn decide_action_ignores_a_question_about_an_earlier_run() {
16638        let home = crate::run::test_home();
16639        let mut t = held_task_with("r1");
16640        t.runs.push("r2".to_owned());
16641        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16642        assert_eq!(
16643            decide_action(
16644                &home,
16645                &t,
16646                &action_question("r1", ask::ChoiceAction::Done),
16647                &PHRASES_EN,
16648                never
16649            ),
16650            ActionDecision::Stale
16651        );
16652    }
16653
16654    #[test]
16655    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16656        let home = crate::run::test_home();
16657        let mut t = held_task_with("r1");
16658        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16659        assert_eq!(
16660            decide_action(
16661                &home,
16662                &t,
16663                &action_question("r1", ask::ChoiceAction::Requeue),
16664                &PHRASES_EN,
16665                never
16666            ),
16667            ActionDecision::Requeue
16668        );
16669        let done_q = action_question("r1", ask::ChoiceAction::Done);
16670        assert_eq!(
16671            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16672            ActionDecision::Done
16673        );
16674        t.mark_action_applied(&done_q.id);
16675        assert_eq!(
16676            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16677            ActionDecision::Skip
16678        );
16679
16680        // A plain answer (no action for that label) does nothing.
16681        let mut plain = action_question("r1", ask::ChoiceAction::Done);
16682        plain.actions.clear();
16683        assert_eq!(
16684            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16685            ActionDecision::Skip
16686        );
16687        // A running task is left alone.
16688        let mut running = held_task_with("r1");
16689        running.status = TaskStatus::Running;
16690        assert_eq!(
16691            decide_action(
16692                &home,
16693                &running,
16694                &action_question("r1", ask::ChoiceAction::Done),
16695                &PHRASES_EN,
16696                never
16697            ),
16698            ActionDecision::Skip
16699        );
16700    }
16701
16702    #[test]
16703    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16704        crate::run::pin_test_home();
16705        for legacy in [false, true] {
16706            let dir = tempfile::tempdir().unwrap();
16707            let queue = Queue::at(dir.path().join("queue"));
16708            let questions = Questions::at(dir.path().join("questions"));
16709            let run = "20260101-000000-hold";
16710            let mut task = held_task_with(run);
16711            task.status = TaskStatus::Parked;
16712            let mut q = ask::Question::new(
16713                run.into(),
16714                land::APPROVAL_NODE.into(),
16715                "land".into(),
16716                "Repair?".into(),
16717                String::new(),
16718                vec![land::REPAIR.into()],
16719            );
16720            q.actions.insert(land::REPAIR.into(), resume_action(run));
16721            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16722            // Deterministically order the answer before the actual manual hold.
16723            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16724            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16725            questions.put(&mut q).unwrap();
16726            task.hold_manual(Some("Keep this PR paused".into()));
16727            if legacy {
16728                task.hold_source = None;
16729            }
16730            queue.put(&mut task).unwrap();
16731
16732            apply_task_choice_actions(&queue, &questions, dir.path());
16733            let after = queue.get(&task.id).unwrap();
16734            assert!(after.operator_held());
16735            assert_eq!(after.hold_source, task.hold_source);
16736            assert_eq!(after.operator_decided_at, task.operator_decided_at);
16737            assert_eq!(after.runs, task.runs);
16738            assert_eq!(after.instruction, task.instruction);
16739            assert!(after.resume_override.is_none());
16740            assert!(after.action_applied(&q.id));
16741            let reason = after.hold_reason.as_deref().unwrap();
16742            assert!(reason.starts_with("Keep this PR paused"));
16743            assert!(reason.contains("later operator decision"));
16744            assert!(reason.contains(&format!("magi task release {}", task.id)));
16745
16746            for recovery in [
16747                crate::conduct::Recovery::Review,
16748                crate::conduct::Recovery::Requeue,
16749            ] {
16750                crate::conduct::apply(
16751                    &queue,
16752                    &questions,
16753                    &crate::conduct::Verdict {
16754                        decisions: vec![crate::conduct::Decision {
16755                            id: task.id.clone(),
16756                            recovery: Some(recovery),
16757                            ..Default::default()
16758                        }],
16759                    },
16760                )
16761                .unwrap();
16762            }
16763            // Reconciliation is idempotent, and automatic recovery cannot
16764            // reopen this owner after it observes the rejected repair answer.
16765            apply_task_choice_actions(&queue, &questions, dir.path());
16766            let still_held = queue.get(&task.id).unwrap();
16767            assert!(still_held.operator_held());
16768            assert_eq!(still_held.hold_reason, after.hold_reason);
16769            assert_eq!(still_held.runs, task.runs);
16770            assert!(still_held.review_branch.is_none());
16771            assert!(!still_held.fresh_start);
16772            assert!(queue.next_runnable().is_none());
16773        }
16774    }
16775
16776    #[test]
16777    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16778        for held in [false, true] {
16779            for retry in [false, true] {
16780                let dir = tempfile::tempdir().unwrap();
16781                let queue = Queue::at(dir.path().join("queue"));
16782                let questions = Questions::at(dir.path().join("questions"));
16783                let home = dir.path().join("home");
16784                let mut t = task();
16785                if held {
16786                    t.hold_machine(Some("driver state unknown".into()));
16787                }
16788                queue.put(&mut t).unwrap();
16789                let verdict = serde_json::from_value(serde_json::json!({
16790                    "decisions": [{
16791                        "id": t.id,
16792                        "question": "Driver state unknown; retry the checks or hold?",
16793                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16794                        "actions": {
16795                            "daemon: recheck and retry": {"do": "requeue"},
16796                            "daemon: hold the task": {"do": "hold"}
16797                        }
16798                    }]
16799                }))
16800                .unwrap();
16801                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16802                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16803                let mut q = questions.list().pop().unwrap();
16804                let choice = if retry {
16805                    "daemon: recheck and retry"
16806                } else {
16807                    "daemon: hold the task"
16808                };
16809                assert_eq!(q.actions.len(), 2);
16810                q.answer(ask::Answer::Choice(choice.into())).unwrap();
16811                questions.put(&mut q).unwrap();
16812
16813                // A Web answer does not remove the deputy's fresh lease.
16814                questions.beat(&q.id, ask::WaiterKind::Deputy);
16815                for _ in 0..2 {
16816                    resolve_blockers(&queue, &questions);
16817                    apply_task_choice_actions(&queue, &questions, &home);
16818                    let waiting = queue.get(&t.id).unwrap();
16819                    assert_eq!(waiting.status, TaskStatus::Blocked);
16820                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
16821                    assert!(waiting.answers.is_empty());
16822                    assert!(!waiting.action_applied(&q.id));
16823                    assert!(runnable(&queue).is_empty());
16824                    let free = Arc::new(tokio::sync::Semaphore::new(1));
16825                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16826                }
16827                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16828
16829                // Releasing the blocker and applying the operation share one save.
16830                resolve_blockers(&queue, &questions);
16831                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16832                apply_task_choice_actions(&queue, &questions, &home);
16833                let after = queue.get(&t.id).unwrap();
16834                assert_eq!(
16835                    after.status,
16836                    if retry {
16837                        TaskStatus::Queued
16838                    } else {
16839                        TaskStatus::Held
16840                    }
16841                );
16842                assert!(after.action_applied(&q.id));
16843                assert_eq!(after.operator_held(), !retry);
16844                assert_eq!(after.answers.len(), 1);
16845
16846                // A later operator decision must not replay this answer.
16847                let mut changed = after;
16848                if retry {
16849                    changed.hold_manual(Some("later hold".into()));
16850                } else {
16851                    changed.release_operator("test", None);
16852                }
16853                let expected = changed.status;
16854                queue.put(&mut changed).unwrap();
16855                apply_task_choice_actions(&queue, &questions, &home);
16856                assert_eq!(queue.get(&t.id).unwrap().status, expected);
16857            }
16858        }
16859    }
16860
16861    #[test]
16862    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16863        let dir = tempfile::tempdir().unwrap();
16864        let queue = Queue::at(dir.path().join("queue"));
16865        let questions = Questions::at(dir.path().join("questions"));
16866        let home = dir.path().join("home");
16867        let mut state = run_state(RunStatus::Blocked);
16868        state.id = "20260101-000000-act1".to_owned();
16869        state.save_under(&home).unwrap();
16870
16871        let mut t = held_task_with(&state.id);
16872        queue.put(&mut t).unwrap();
16873        let mut q = action_question(&state.id, resume_action(&state.id));
16874        questions.put(&mut q).unwrap();
16875
16876        apply_task_choice_actions(&queue, &questions, &home);
16877        let after = queue.get(&t.id).unwrap();
16878        assert_eq!(after.status, TaskStatus::Queued);
16879        assert!(!after.fresh_start);
16880        assert!(after.action_applied(&q.id));
16881        let pin = after.resume_override.clone().unwrap();
16882        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16883        assert!(pin.forced);
16884
16885        // Held again later: the same answer does not release it a second time.
16886        let mut again = queue.get(&t.id).unwrap();
16887        again.hold_machine(Some("later".into()));
16888        queue.put(&mut again).unwrap();
16889        apply_task_choice_actions(&queue, &questions, &home);
16890        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16891    }
16892
16893    #[test]
16894    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16895        let dir = tempfile::tempdir().unwrap();
16896        let home = dir.path();
16897        let queue = Queue::at(home.join("queue"));
16898        let questions = Questions::at(home.join("questions"));
16899        let mut state = run_state(RunStatus::Blocked);
16900        state.save_under(home).unwrap();
16901        let mut task = held_task_with(&state.id);
16902        queue.put(&mut task).unwrap();
16903        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16904        questions.put(&mut question).unwrap();
16905
16906        apply_task_choice_actions(&queue, &questions, home);
16907
16908        let after = queue.get(&task.id).unwrap();
16909        assert_eq!(after.status, TaskStatus::Held);
16910        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16911        assert_eq!(after.runs, task.runs);
16912        assert!(after.completion_history.is_empty());
16913        assert!(!after.decision_effects.contains_key(&question.id));
16914        assert_eq!(
16915            RunState::load_under(&state.id, home).unwrap().status,
16916            RunStatus::Blocked
16917        );
16918    }
16919
16920    #[test]
16921    fn a_delivered_answer_is_still_acted_on_exactly_once() {
16922        let dir = tempfile::tempdir().unwrap();
16923        let queue = Queue::at(dir.path().join("queue"));
16924        let questions = Questions::at(dir.path().join("questions"));
16925        let home = dir.path().join("home");
16926        let mut state = run_state(RunStatus::Blocked);
16927        state.id = "20260101-000000-act2".to_owned();
16928        state.save_under(&home).unwrap();
16929
16930        let mut t = held_task_with(&state.id);
16931        queue.put(&mut t).unwrap();
16932        let mut q = action_question(&state.id, resume_action(&state.id));
16933        q.answer_delivered = true;
16934        questions.put(&mut q).unwrap();
16935
16936        // Delivered, and the agent then died: the task is still held, so the
16937        // chosen action applies.
16938        apply_task_choice_actions(&queue, &questions, &home);
16939        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16940        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16941
16942        // Held again: the same answer does nothing a second time.
16943        let mut again = queue.get(&t.id).unwrap();
16944        again.hold_machine(Some("later".into()));
16945        queue.put(&mut again).unwrap();
16946        apply_task_choice_actions(&queue, &questions, &home);
16947        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16948    }
16949
16950    #[test]
16951    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16952        let dir = tempfile::tempdir().unwrap();
16953        let queue = Queue::at(dir.path().join("queue"));
16954        let questions = Questions::at(dir.path().join("questions"));
16955        let home = dir.path().join("home");
16956        let mut state = run_state(RunStatus::Blocked);
16957        state.id = "20260101-000000-act3".to_owned();
16958        state.save_under(&home).unwrap();
16959        let mut t = held_task_with(&state.id);
16960        queue.put(&mut t).unwrap();
16961        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16962        questions.put(&mut q).unwrap();
16963
16964        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16965        apply_task_choice_actions(&queue, &questions, &home);
16966        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16967
16968        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16969        apply_task_choice_actions(&queue, &questions, &home);
16970        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16971    }
16972
16973    #[test]
16974    fn action_standing_tells_the_reasons_apart() {
16975        let mut t = held_task_with("r1");
16976        let q = action_question("r1", ask::ChoiceAction::Requeue);
16977        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16978        let mut plain = q.clone();
16979        plain.actions.clear();
16980        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16981
16982        // Applied wins over everything, even a running task.
16983        t.mark_action_applied(&q.id);
16984        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16985
16986        // A newer attempt running: the old question is Stale, not Busy.
16987        let mut t = held_task_with("r1");
16988        t.start("r2".to_owned());
16989        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16990        // The same question about the latest run just waits.
16991        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16992        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16993        t.status = TaskStatus::Blocked;
16994        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16995
16996        // A conductor question is keyed by the task, never stale.
16997        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16998        c.node = crate::conduct::NODE.to_owned();
16999        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
17000        assert!(!ActionStanding::Busy.daemon_owns());
17001    }
17002
17003    #[test]
17004    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
17005        let dir = tempfile::tempdir().unwrap();
17006        let queue = Queue::at(dir.path().join("queue"));
17007        let questions = Questions::at(dir.path().join("questions"));
17008        let home = dir.path().join("home");
17009        // Execution finished before task settlement; Done is not a discard.
17010        let mut state = run_state(RunStatus::Merged);
17011        state.merge = Some(crate::run::MergeOutcome {
17012            mode: MergeMode::Pr,
17013            ok: true,
17014            detail: "confirmed merge".into(),
17015            empty: false,
17016        });
17017        state.id = "20260101-000000-act4".to_owned();
17018        state.save_under(&home).unwrap();
17019        let mut t = held_task_with(&state.id);
17020        t.status = TaskStatus::Running;
17021        queue.put(&mut t).unwrap();
17022        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
17023        q.cwd = Some(dir.path().display().to_string());
17024        questions.put(&mut q).unwrap();
17025
17026        // While the task runs the daemon will not act, so the waiter still
17027        // delivers the word to the dead asker's seat ...
17028        let running = queue.get(&t.id).unwrap();
17029        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
17030        assert!(matches!(
17031            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
17032            crate::waiter::Action::Deliver(_)
17033        ));
17034        // ... and the daemon waits while the task runs, then applies once.
17035        apply_task_choice_actions(&queue, &questions, &home);
17036        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
17037        let mut back = queue.get(&t.id).unwrap();
17038        back.hold_machine(Some("later".into()));
17039        queue.put(&mut back).unwrap();
17040        apply_task_choice_actions(&queue, &questions, &home);
17041        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
17042        let mut again = queue.get(&t.id).unwrap();
17043        again.hold_machine(Some("again".into()));
17044        queue.put(&mut again).unwrap();
17045        apply_task_choice_actions(&queue, &questions, &home);
17046        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
17047    }
17048
17049    #[test]
17050    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
17051     {
17052        let dir = tempfile::tempdir().unwrap();
17053        let home = dir.path();
17054        let queue = Queue::at(home.join("queue"));
17055        let mut state = run_state(RunStatus::Blocked);
17056        state.id = "20261125-084544-669a".to_owned();
17057        state.driver_exited = true;
17058        state.driver_pid = None;
17059        state.driver_started_at = None;
17060        state.save_under(home).unwrap();
17061
17062        let mut t = held_task_with(&state.id);
17063        queue.put(&mut t).unwrap();
17064
17065        // Simulate a task worker that finished and was archived to results/,
17066        // while daemon.json still has a fresh heartbeat referencing that worker.
17067        let worker_id = "fc769e65-0000-4000-8000-000000000001";
17068        let retained_dir = home.join("workers").join("results").join(worker_id);
17069        std::fs::create_dir_all(&retained_dir).unwrap();
17070        let finished_job = crate::worker::Job {
17071            id: worker_id.to_owned(),
17072            sequence: 1,
17073            kind: "task".to_owned(),
17074            key: format!("task:{}", t.id),
17075            payload: serde_json::json!({
17076                "queue": home.join("queue"),
17077                "task": t.id,
17078                "opts": Opts::default(),
17079                "standalone": false,
17080            }),
17081            generation: "a".repeat(64),
17082            version: Some("0.260.0".to_owned()),
17083            status: crate::worker::Status::Finished,
17084            result: Some("completed".to_owned()),
17085            pid: Some(37456),
17086            created_at: 1,
17087            finished_at: Some(2),
17088        };
17089        std::fs::write(
17090            retained_dir.join("job.json"),
17091            serde_json::to_vec(&finished_job).unwrap(),
17092        )
17093        .unwrap();
17094
17095        let now = Timestamp::now();
17096        let mut status = Status::new();
17097        status.updated_at = now;
17098        status.current = vec![Current {
17099            worker: Some(worker_id.to_owned()),
17100            task: t.id.clone(),
17101            run: state.id.clone(),
17102        }];
17103        write_status_to(&home.join("daemon.json"), &status).unwrap();
17104
17105        assert!(
17106            claim_for_run(home, &state.id, now).is_none(),
17107            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
17108        );
17109        assert!(crate::resume::validate(home, &state.id).is_ok());
17110
17111        // Legacy heartbeat without worker id remains protected.
17112        status.current = vec![Current {
17113            worker: None,
17114            task: t.id.clone(),
17115            run: state.id.clone(),
17116        }];
17117        write_status_to(&home.join("daemon.json"), &status).unwrap();
17118        let legacy_err = crate::resume::validate(home, &state.id)
17119            .unwrap_err()
17120            .to_string();
17121        assert!(
17122            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17123            "{legacy_err}"
17124        );
17125        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
17126
17127        // Heartbeat naming a missing/unreadable worker record remains protected.
17128        let missing_id = "fc769e65-0000-4000-8000-000000000002";
17129        status.current = vec![Current {
17130            worker: Some(missing_id.to_owned()),
17131            task: t.id.clone(),
17132            run: state.id.clone(),
17133        }];
17134        write_status_to(&home.join("daemon.json"), &status).unwrap();
17135        let missing_err = crate::resume::validate(home, &state.id)
17136            .unwrap_err()
17137            .to_string();
17138        assert!(
17139            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17140            "{missing_err}"
17141        );
17142        assert!(missing_err.contains(missing_id), "{missing_err}");
17143        assert!(missing_err.contains("status=unknown"), "{missing_err}");
17144
17145        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
17146        // still remains protected conservatively until fenced to a terminal status.
17147        let running_id = "fc769e65-0000-4000-8000-000000000003";
17148        let running_dir = home.join("workers").join("jobs").join(running_id);
17149        std::fs::create_dir_all(&running_dir).unwrap();
17150        let running_job = crate::worker::Job {
17151            id: running_id.to_owned(),
17152            status: crate::worker::Status::Running,
17153            pid: Some(42424),
17154            finished_at: None,
17155            result: None,
17156            ..finished_job
17157        };
17158        std::fs::write(
17159            running_dir.join("job.json"),
17160            serde_json::to_vec(&running_job).unwrap(),
17161        )
17162        .unwrap();
17163        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
17164        status.current = vec![Current {
17165            worker: Some(running_id.to_owned()),
17166            task: t.id.clone(),
17167            run: state.id.clone(),
17168        }];
17169        write_status_to(&home.join("daemon.json"), &status).unwrap();
17170        let running_err = crate::resume::validate(home, &state.id)
17171            .unwrap_err()
17172            .to_string();
17173        assert!(
17174            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17175            "{running_err}"
17176        );
17177        assert!(running_err.contains(running_id), "{running_err}");
17178        assert!(running_err.contains("pid=42424"), "{running_err}");
17179        assert!(running_err.contains("status=running"), "{running_err}");
17180    }
17181
17182    #[test]
17183    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
17184        let dir = tempfile::tempdir().unwrap();
17185        let home = dir.path();
17186        let queue = Queue::at(home.join("queue"));
17187        let mut state = run_state(RunStatus::Blocked);
17188        state.id = "20261125-090000-evid".to_owned();
17189        state.driver_exited = true;
17190        state.save_under(home).unwrap();
17191        let mut t = held_task_with(&state.id);
17192        queue.put(&mut t).unwrap();
17193
17194        // 1. Live task worker holding live.lock.
17195        let payload = serde_json::json!({
17196            "queue": home.join("queue"),
17197            "task": t.id,
17198            "opts": Opts::default(),
17199            "standalone": false,
17200        });
17201        let (job, lease) =
17202            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
17203        let worker_err = crate::resume::validate(home, &state.id)
17204            .unwrap_err()
17205            .to_string();
17206        assert!(
17207            worker_err.starts_with("run already has a live driver: worker claim"),
17208            "{worker_err}"
17209        );
17210        assert!(worker_err.contains(&job.id), "{worker_err}");
17211        assert!(
17212            worker_err.contains(&format!("pid={}", std::process::id())),
17213            "{worker_err}"
17214        );
17215        assert!(worker_err.contains("status=running"), "{worker_err}");
17216        assert!(worker_err.contains("live.lock held"), "{worker_err}");
17217        drop(lease);
17218        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
17219
17220        // 2. Unfenced Starting worker reservation.
17221        let starting_id = "fc769e65-0000-4000-8000-000000000010";
17222        let starting_dir = home.join("workers").join("jobs").join(starting_id);
17223        std::fs::create_dir_all(&starting_dir).unwrap();
17224        let starting_job = crate::worker::Job {
17225            id: starting_id.to_owned(),
17226            sequence: 2,
17227            kind: "task".to_owned(),
17228            key: format!("task:{}", t.id),
17229            payload: serde_json::json!({
17230                "queue": home.join("queue"),
17231                "task": t.id,
17232                "opts": Opts::default(),
17233                "standalone": false,
17234            }),
17235            generation: "a".repeat(64),
17236            version: None,
17237            status: crate::worker::Status::Starting,
17238            result: None,
17239            pid: None,
17240            created_at: 1,
17241            finished_at: None,
17242        };
17243        std::fs::write(
17244            starting_dir.join("job.json"),
17245            serde_json::to_vec(&starting_job).unwrap(),
17246        )
17247        .unwrap();
17248        let starting_err = crate::resume::validate(home, &state.id)
17249            .unwrap_err()
17250            .to_string();
17251        assert!(
17252            starting_err.starts_with("run already has a live driver: worker claim"),
17253            "{starting_err}"
17254        );
17255        assert!(starting_err.contains(starting_id), "{starting_err}");
17256        assert!(starting_err.contains("status=starting"), "{starting_err}");
17257        assert!(
17258            starting_err.contains("unfenced starting reservation"),
17259            "{starting_err}"
17260        );
17261        std::fs::remove_dir_all(&starting_dir).unwrap();
17262
17263        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
17264        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
17265        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
17266        std::fs::create_dir_all(&corrupt_dir).unwrap();
17267        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
17268        let store_err = crate::resume::validate(home, &state.id)
17269            .unwrap_err()
17270            .to_string();
17271        assert!(
17272            store_err.starts_with(
17273                "run already has a live driver: worker store observation failed (conservative protection):"
17274            ),
17275            "{store_err}"
17276        );
17277        assert!(store_err.contains(corrupt_id), "{store_err}");
17278        std::fs::remove_dir_all(&corrupt_dir).unwrap();
17279
17280        // 4. Held execution lease (driver.lock path).
17281        state.driver_exited = false;
17282        state.driver_claimed = Some(false);
17283        state.driver_pid = None;
17284        state.driver_started_at = None;
17285        state.save_under(home).unwrap();
17286        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
17287        let lease_err = crate::resume::validate(home, &state.id)
17288            .unwrap_err()
17289            .to_string();
17290        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
17291        assert!(
17292            lease_err.starts_with("run already has a live driver: execution lease held"),
17293            "{lease_err}"
17294        );
17295        assert!(
17296            lease_err.contains(&lock_path.display().to_string()),
17297            "{lease_err}"
17298        );
17299        drop(exec_lease);
17300
17301        // 5. Live process identity (pid + identity).
17302        let pid = std::process::id();
17303        let identity = crate::proc::process_started_at(pid).expect("current process identity");
17304        state.driver_claimed = None;
17305        state.driver_pid = Some(pid);
17306        state.driver_started_at = Some(identity.clone());
17307        state.save_under(home).unwrap();
17308        let pid_err = crate::resume::validate(home, &state.id)
17309            .unwrap_err()
17310            .to_string();
17311        assert!(
17312            pid_err.starts_with("run already has a live driver: live driver process"),
17313            "{pid_err}"
17314        );
17315        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17316        assert!(
17317            pid_err.contains(&format!("identity={identity}")),
17318            "{pid_err}"
17319        );
17320
17321        // decide_action uses the exact same refusal format for process identity too.
17322        let question = action_question(&state.id, resume_action(&state.id));
17323        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17324            RunState::load_under(id, home)
17325        });
17326        assert_eq!(decision, ActionDecision::Refuse(pid_err));
17327    }
17328}