magi/daemon.rs
1//! The unattended loop: take the next task, run the graph, record what
2//! happened, take the next one.
3//!
4//! This is what turns magi from a command a human types into something an
5//! agent can hand work to. [`crate::queue`] is the mailbox; this module is the
6//! thing that empties it. Nothing here decides *how* a task is implemented —
7//! that is [`crate::graph`] — it only decides which task runs next, and what a
8//! finished run means for the task that produced it.
9//!
10//! # One run at a time, on purpose
11//!
12//! There is no `--jobs` flag and there will not be one. A single run is
13//! already internally parallel: candidates implement concurrently and judges
14//! rank concurrently, so the machine is not idle while one task is in flight.
15//! The real constraint is not CPU but the agent CLIs' quota, and two graphs at
16//! once doubles the burn rate on exactly the resource whose exhaustion produces
17//! [`RunStatus::Stalled`]. Serialising the loop is what keeps a full backlog
18//! from converting the whole day's quota into a pile of untrustworthy verdicts.
19//!
20//! # A crash is legible, and the loop notices on its own
21//!
22//! The task is written as [`crate::queue::TaskStatus::Running`], with its run
23//! id, *before* the graph starts, and is only rewritten once the run reaches a
24//! terminal status. A daemon killed mid-run therefore leaves the task
25//! `Running` and pointing at the run that was in flight. The alternative —
26//! reverting the task to `Queued` on the way out — would hide the abandoned
27//! run and re-spend its quota on the next poll.
28//!
29//! A task left `Running` forever is not the point, though:
30//! [`crate::queue::TaskStatus::runnable`] never offers it again, so a daemon
31//! that died mid-run would otherwise strand its task for good.
32//! [`reclaim_orphaned_running`] runs on every poll and settles exactly the
33//! tasks no live process is actually driving — proven by [`Queue::claim`]
34//! succeeding rather than by a staleness guess — against whatever their last
35//! run actually became, through the same [`settle`] a live finish uses. A run
36//! that genuinely cannot be read still holds its task for a human; the run's
37//! own report explains how far it got.
38//!
39//! # Retries are bounded
40//!
41//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
42//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
43//! exception is a run that ended `Stalled`: the panel collapsed because the
44//! agent CLIs hit their quota, which is a fact about the machine and not about
45//! the task, so it must not spend an attempt. Without that exception a quota
46//! outage would quietly hold the entire backlog, and the operator would come
47//! back to a reset quota and nothing left that the loop is willing to run.
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
72pub const SCHEMA: u32 = 1;
73
74/// How often the status file is refreshed. A reader treats a status file older
75/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
76/// that a busy daemon is never mistaken for a dead one.
77pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79/// How old a heartbeat may be before a reader calls the daemon dead. Six
80/// missed beats: long enough to survive a slow filesystem, short enough that
81/// a crashed daemon is not still reported as running a task.
82///
83/// The single threshold every reader shares — the web UI's `/api/health` and
84/// `magi doctor` both call [`Reading::running`] rather than each comparing
85/// against their own copy of this number, so a crashed daemon cannot look
86/// alive on one screen and dead on another.
87pub const STALE_SECS: i64 = 30;
88
89/// Default queue poll interval.
90pub const POLL: Duration = Duration::from_secs(5);
91
92/// How old a claim has to be before startup sweeps it. Longer than any run
93/// this graph plausibly takes, so a sweep cannot pull a task out from under a
94/// daemon that is merely slow.
95pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
98/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
99///
100/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
101/// poll, by attempting the task's own claim: a dead pid is proof enough for
102/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
103/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
104/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
105/// age instead, since there is nothing else to check (see
106/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
107/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
108/// task `running` — see
109/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
110/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
111/// conductor well before the mechanical six-hour sweep would, and thirty
112/// minutes is comfortably below `STALE_CLAIM` while still being generous
113/// enough that a task merely late to publish its first [`HEARTBEAT`] is
114/// never mistaken for abandoned.
115pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117/// What the loop is working on, for the status file.
118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 /// Task id being run.
122 pub task: String,
123 /// Run id the task produced.
124 pub run: String,
125}
126
127/// The daemon's liveness, published to `<home>/daemon.json`.
128///
129/// This is the only interface between the loop and the web UI, which is why it
130/// carries `updated_at` as well as `started_at`: a reader cannot tell a
131/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
132/// can compare the heartbeat against the clock.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 /// On-disk format version.
136 pub schema: u32,
137 /// Process id, so a human can find or kill the daemon.
138 pub pid: u32,
139 /// When this process started.
140 pub started_at: Timestamp,
141 /// Last heartbeat.
142 pub updated_at: Timestamp,
143 /// True when the queue has nothing runnable.
144 pub idle: bool,
145 /// Every task and run currently in flight. More than one entry means the
146 /// loop is driving more than one run at once — see
147 /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
148 /// nothing is running, so a reader never has to treat "no field" and "an
149 /// empty list" as two different kinds of idle.
150 pub current: Vec<Current>,
151 /// Tasks that reached a terminal status in this process.
152 pub completed: usize,
153 /// Queue polls since start, so a wedged loop shows up as a frozen count.
154 pub polls: u64,
155}
156
157impl Status {
158 /// A fresh, idle status for this process.
159 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181/// How the loop should behave.
182#[derive(Debug, Clone)]
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
221/// How many runs a plain `usize` from config may drive concurrently, floored
222/// at one. A `0` in a config file would otherwise stall the loop entirely -
223/// no runnable task could ever start - which is never what an operator who
224/// wrote `0` meant.
225fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229/// Where the status file lives.
230#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235/// Publish the status file for this process.
236pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240/// Publish a status to an explicit path.
241///
242/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
243/// on every health poll and must never see a half-written one.
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255/// Delete the status file. Called on the way out so a clean exit reads as
256/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
257pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261/// Delete a status file at an explicit path, so the loop's teardown and
262/// [`clear_status`] cannot drift apart: the loop is handed the path it
263/// published to, and a test can watch a temp file disappear.
264fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268/// A cooperative stop, shared with whoever asked the loop to run.
269///
270/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
271/// Ctrl-C listener and the web UI keep others, and every clone points at the
272/// same flag. There is no channel because there is nothing to send — the only
273/// message is "stop", it is idempotent, and a flag cannot be missed by a
274/// receiver that was not listening yet.
275///
276/// The handle also answers the question the operator's screen asks next: a
277/// stop does not take effect until the run in flight has finished, so
278/// [`Stop::finishing`] reports "asked to stop, still working" rather than
279/// leaving a caller to infer it from a heartbeat and hope.
280#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 /// Set once, never cleared: a stop is not something an operator takes back
283 /// half way through, and a clearable flag would let a start racing a stop
284 /// resurrect a loop that is already unwinding.
285 stopped: Arc<AtomicBool>,
286 /// How many runs are in flight, so `finishing` can distinguish a stop
287 /// that has landed from one that is waiting on `execute`. A count, not a
288 /// flag, because more than one run can be in flight at once - see
289 /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
290 /// finish is the one that should turn "finishing" off.
291 busy: Arc<std::sync::atomic::AtomicUsize>,
292 /// Wakes the idle wait. Without this a stop would not be seen until the
293 /// poll interval elapsed, and an operator tapping stop on a phone would
294 /// watch a button do nothing for five seconds.
295 wake: Arc<Notify>,
296 /// Handed to the run in flight, so a stop can also mean "park at the next
297 /// node boundary" instead of "finish the whole competition first".
298 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 /// A stop nobody has asked for yet.
303 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 /// Ask the loop to stop. Idempotent, and safe to call before the loop
309 /// starts: the flag is checked before the first poll.
310 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 // `notify_one` rather than `notify_waiters` because the loop may not be
313 // parked yet: this stores a permit, so a wait that registers a moment
314 // later returns at once instead of sleeping out the whole interval.
315 self.wake.notify_one();
316 }
317
318 /// Has a stop been asked for?
319 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 /// Has a stop been asked for that has not taken effect yet, because a run
325 /// is still in flight?
326 ///
327 /// This is the state a screen has to be able to show. A stop never abandons
328 /// a run — see [`serve_until`] — so between the tap and the loop's return
329 /// there is a window of tens of minutes in which "running" and "stopped"
330 /// are both misleading answers.
331 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 /// Ask the loop to stop *and* the run in flight to park at its next node
337 /// boundary.
338 ///
339 /// The plain [`Stop::stop`] never abandons a run, which is right when the
340 /// operator only wants the queue to drain: a competition is tens of
341 /// minutes and its worktrees are paid for. But an operator who wants to
342 /// replace the binary cannot wait out a run that has an hour left, and
343 /// killing the process loses whatever the seats in flight had not written.
344 /// Parking costs at most the node in progress and leaves the run
345 /// resumable.
346 pub fn park(&self) {
347 self.pause.park();
348 self.stop();
349 }
350
351 /// Has a park been asked for?
352 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 /// The pause handle to give a runner.
358 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 /// Is any run in flight right now?
364 ///
365 /// `finishing` answers "a stop is waiting on a run", which is false until
366 /// someone asks to stop. An upgrade needs the plain question, because it
367 /// is about to be the one asking.
368 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 /// Mark one more run as in flight, for [`Stop::finishing`].
374 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 /// Mark one run as finished. The last one out is what makes
379 /// [`Stop::busy_now`] false again.
380 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 /// Wait out one poll interval, returning early once a stop is asked for.
385 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393/// The daemon's published state, read permissively.
394///
395/// This mirrors [`Status`], but is a separate declaration on purpose: every
396/// field defaults, so a status file from an older or newer magi still yields
397/// a usable reading — one this build has never heard of — instead of a parse
398/// error that hides the daemon entirely.
399#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 /// Format version the daemon claims.
403 pub schema: u32,
404 /// Daemon process id, for an operator who wants to stop it.
405 pub pid: Option<u32>,
406 /// When that process started.
407 pub started_at: Option<Timestamp>,
408 /// Last heartbeat. Absent means the file is unusable, hence not running.
409 pub updated_at: Option<Timestamp>,
410 /// True when the queue had nothing runnable at the last poll.
411 pub idle: bool,
412 /// What the daemon is working on. Empty means idle; more than one entry
413 /// means more than one run is in flight at once.
414 ///
415 /// `deserialize_with` rather than the plain derive: a daemon started
416 /// before this field became a list is still out there writing the old
417 /// shape — a single `{"task":...,"run":...}` object, or its absence —
418 /// on every heartbeat until it is restarted, and a live process reading
419 /// that file during the rollout must still see it as running rather than
420 /// as absent. A bare type change here would fail the whole struct's
421 /// deserialization on a type mismatch, defeating the permissiveness this
422 /// type exists for.
423 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 /// Tasks this daemon process has finished.
426 pub completed: u64,
427 /// Queue polls this daemon process has made.
428 pub polls: u64,
429}
430
431/// Accept the old single-`Current`-or-absent shape as well as the current
432/// list, so a reader never has to know which build wrote the file.
433fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 /// Seconds since the last heartbeat, or `None` when there has never been
453 /// one.
454 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 /// Whether the loop counts as running: a heartbeat no older than
461 /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
462 /// progress hours after the daemon that owned it was killed.
463 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
470/// usable there.
471///
472/// Missing, half-written and unparseable all collapse to `None`, because the
473/// only question a reader asks is whether a daemon is alive, and a file it
474/// cannot read is not evidence that one is.
475#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481/// Every run a live daemon is working on right now.
482///
483/// One definition of liveness, because deleting a task and deleting a run are
484/// both gated on it from both the CLI and the web UI - four callers that must
485/// never disagree about whether the same thing is in flight. A stale heartbeat
486/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
487/// left at `running` or a run left at `implementing` by a killed daemon is a
488/// leftover record rather than work in progress. More than one entry once
489/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
490/// after "the one thing in flight" wants [`is_working_on`] or
491/// [`is_working_on_task`], not this directly.
492#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500/// Whether a live daemon is working on this run at this moment.
501#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506/// Whether a live daemon is working on a run whose short id is this one.
507///
508/// For a worktree that has no run record to compare against at all -
509/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
510/// id is not available to hand to [`is_working_on`]. The short id is: a run's
511/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
512/// and it is exactly the gap between the daemon claiming a task and
513/// `RunState::new` saving the first `run.json` that this exists to protect -
514/// a run genuinely in flight but invisible to a scan of `runs/`.
515#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522/// Whether a live daemon is working on this task at this moment.
523#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528/// Remove claim files whose owner is provably dead, or that have simply
529/// outlived `older_than`, and return the task ids swept.
530///
531/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
532/// destructor, and the orphaned `.lock` file would make its task permanently
533/// unclaimable — the backlog would stop for good at exactly the task that was
534/// in flight when the machine went down.
535///
536/// The pid recorded in the lock is the authority whenever it can be read at
537/// all; age is only a fallback for when it cannot be.
538///
539/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
540/// full stop — dead sweeps the lock immediately, regardless of age; alive
541/// protects it, regardless of age. This is what lets a lock be reclaimed in
542/// seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
543/// before this daemon even started, next to a `queued` task, no longer has
544/// to sit for six hours before anything notices its owner is gone.
545/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
546/// falls back to `older_than`, since there is nothing else to check.
547///
548/// Age must never override a *positive* liveness confirmation. `sweep`
549/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
550/// see [`InFlightGuard`] — not only between them the way a single sequential
551/// loop once did, so a run that legitimately runs longer than `older_than`
552/// (a multi-round review, a long land wait carried across several resumed
553/// attempts) still has this very process's own live pid sitting in its own
554/// lock file on every later sweep. Deciding by age alone in that case would
555/// delete this daemon's own still-valid claim on its own in-flight task,
556/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
557/// to a second attempt — two `Runner`s writing the same `run.json` and the
558/// same worktree at once. `pid_alive` answering "alive" for anything it
559/// cannot determine (a live process, a pid this build cannot check, one
560/// under another account) is exactly what keeps that path from ever
561/// firing on a guess.
562///
563/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
564/// output unreadable must not be license to guess, and the risk of an
565/// unparseable lock outliving a genuinely dead owner is bounded by an order
566/// of magnitude above any plausible run rather than by a positive check.
567///
568/// Runs on every poll, not only at startup — a daemon up for days must keep
569/// noticing a lock some other, now-dead, daemon left behind just as readily
570/// as one it trips over on the way up.
571pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575/// [`sweep_stale_claims`] with its process-query boundary supplied by the
576/// caller. This keeps the lock policy testable where process listing is
577/// unavailable, while production still uses the platform query above.
578fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 // This process wrote it and is asking the question right
595 // now, so it is definitionally still alive - settled without
596 // spawning a helper process at all.
597 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
618/// no live daemon's heartbeat naming it? Deterministic — no model call, and
619/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
620/// shown.
621fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627/// Every task [`is_stalled`] right now — "止まったタスク" in
628/// `crate::conduct`'s vocabulary.
629fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
638/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
639/// `Failed`-and-so-also-runnable: a task that already attempted and lost
640/// belongs in [`finished_tasks`], where the question is a recovery, not a
641/// dependency.
642fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
651/// タスク" in `crate::conduct`'s vocabulary.
652fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660/// Deterministically resolve `Task::blocked_by`: a dependency task that
661/// reached `Done`, or a question that was answered, is removed — no model
662/// involved, on every poll. An answered question's content is copied onto
663/// the task ([`Task::record_answer`]) before its id is dropped, so it
664/// reaches the next `crate::conduct` prompt and the next run's instruction
665/// (see [`instruction_for`]) rather than only clearing the block.
666///
667/// A `blocked_by` id that names neither an existing task nor an existing
668/// question - `magi task rm` (or an operator by hand) deleted it while this
669/// task was still waiting - is caught before any of that: it can never
670/// become `Done` or `Answered`, so the ordinary loop below would otherwise
671/// leave the task `blocked` forever with nothing to notice. Such a task is
672/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
673/// which puts it in front of `crate::triage::run_once`'s own walk the next
674/// time it runs - see that module's doc for why the choice is "ask a human",
675/// never "assume the missing dependency was satisfied and unblock anyway".
676fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
691 if !missing.is_empty() {
692 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason(
693 &task.blocked_by,
694 &missing,
695 )));
696 record(queue, &mut task);
697 continue;
698 }
699 let mut changed = false;
700 for id in task.blocked_by.clone() {
701 if let Ok(dep) = queue.get(&id) {
702 if dep.status == TaskStatus::Done {
703 task.unblock(&id);
704 changed = true;
705 }
706 continue;
707 }
708 if let Ok(q) = questions.get(&id)
709 && q.status == ask::QuestionStatus::Answered
710 {
711 let answer = match &q.answer {
712 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
713 None => String::new(),
714 };
715 task.record_answer(q.summary.clone(), answer);
716 task.unblock(&id);
717 changed = true;
718 }
719 }
720 if changed {
721 record(queue, &mut task);
722 }
723 }
724}
725
726/// Retire an unanswered conductor question after its task no longer refers to
727/// it. Conductor questions use the task id in `Question::run`, so run-based
728/// cleanup cannot observe a manual release or completion.
729///
730/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
731/// own question also carries a `run`, and a run id that happens to collide
732/// with some task's id is not this loop's business — only a conductor
733/// question actually uses the task id that way. One `Questions::list()` scan
734/// is taken up front and matched against the in-memory task set, rather than
735/// calling `Questions::open_for` (a full disk scan on its own) once per task.
736fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
737 let tasks = queue.list();
738 let by_id: std::collections::BTreeMap<&str, &Task> =
739 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
740 let referenced: std::collections::BTreeSet<&str> = tasks
741 .iter()
742 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
743 .collect();
744
745 for mut question in questions.list() {
746 if !question.status.open() || question.node != crate::conduct::NODE {
747 continue;
748 }
749 // Keep questions a task still names, including when the reference
750 // moved to a dependent task.
751 if referenced.contains(question.id.as_str()) {
752 continue;
753 }
754 let Some(task) = by_id.get(question.run.as_str()) else {
755 continue;
756 };
757 question.abandon(format!(
758 "task {} no longer waits for this answer",
759 task.short()
760 ));
761 if let Err(e) = questions.put(&mut question) {
762 tracing::warn!(
763 "could not retire question {} for task {}: {e:#}",
764 question.short(),
765 task.short()
766 );
767 }
768 }
769}
770
771/// What a finished run tells the queue about the task it came from.
772///
773/// A struct rather than a fourth and fifth boolean argument: the two flags
774/// answer different questions about the same run, and a call site passing
775/// `(…, true, false)` is one transposition away from refunding attempts
776/// forever.
777#[derive(Debug, Clone, Copy)]
778pub struct Verdict {
779 /// Where the graph stopped.
780 pub status: RunStatus,
781 /// The run opened a pull request.
782 pub left_pr: bool,
783 /// At least one seat was lost to a rate limit.
784 pub quota_hit: bool,
785 /// The run parked at a node boundary because it was asked to.
786 pub parked: bool,
787 /// The run never produced a single candidate a judge could look at.
788 ///
789 /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
790 /// still have another candidate worth judging, in which case the loss was
791 /// not the reason nothing came of the run. This is `true` only when the
792 /// implement wave ended with nothing viable at all.
793 pub no_viable_candidates: bool,
794}
795
796/// Record a finished run against the task it came from.
797///
798/// Kept pure and separate from the loop because this mapping *is* the retry
799/// policy, and a policy that can only be exercised by spawning a graph is a
800/// policy nobody checks. The table:
801///
802/// | run status | task becomes | attempt spent |
803/// |---------------------------------------|---------------------|---------------|
804/// | parked at a boundary | `Failed` (requeued) | **no** |
805/// | `Merged`, `Ready` | `Done` | yes |
806/// | `Stalled`, quota hit | `Failed` (requeued) | **no** |
807/// | `Failed`, quota hit, no viable cand. | `Failed` (requeued) | **no** |
808/// | `Stalled`, no quota | `Failed`, or `Held` | yes |
809/// | `Blocked` with a PR | `Held` | yes |
810/// | `Blocked`, `Failed` otherwise | `Failed`, or `Held` | yes |
811/// | `VerifiedNoop` | `Held` | yes |
812/// | anything non-terminal | `Failed`, or `Held` | yes |
813///
814/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
815/// deliberately: every candidate agreeing there is nothing to write is not a
816/// machine fact about a rate limit, it is an unverified claim about the
817/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
818/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
819/// claim could be wrong (a misread instruction, a stale check), and closing
820/// the task automatically on an implementer's say-so would be the exact
821/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
822/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
823/// above, which settles through the same [`Task::handed_off`]: `Held` is not
824/// `Failed`-and-requeued, so nothing retries this task on the same unverified
825/// claim regardless of whether the one already-spent attempt is refunded, and
826/// [`Task::release`] resets the count to zero anyway the moment a human looks
827/// at the evidence and lets it run again.
828///
829/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
830/// twice, together. A quorum lost to rate limits is a property of the machine
831/// and not of the task, so the attempt is refunded and a reset quota picks
832/// the work up where it stopped — and that is just as true when every
833/// implement seat lost the same race and `after_implement` bails with nothing
834/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
835/// machine fact. The `no_viable_candidates` guard is what keeps that row
836/// narrow: a `Failed` run that produced a real candidate which then lost for
837/// some other reason still spends the attempt, exactly like the quorum lost
838/// to judges that answered with the wrong shape is ordinary flakiness, and
839/// refunding *that* takes the bound off the retry loop entirely: run e633
840/// stalled with `quota: []` after two judges wrote unusable JSON, was
841/// refunded, and the next attempt paid for a fresh hour-long implement wave
842/// before it could fail the same way. `max_attempts` exists precisely so
843/// that cannot repeat forever.
844///
845/// A non-terminal status means `execute` returned while the graph was still
846/// mid-flight, which is a bug rather than a verdict; it is treated as a
847/// failure so that a task cannot loop on it either.
848///
849/// `left_pr` splits the `Blocked` row, and it is the difference between a run
850/// that failed and a run that finished into a gate. See [`Task::handed_off`].
851pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
852 // A parked run is the operator's own doing, and its work is intact on
853 // disk. The task goes back in line with its attempt refunded so the next
854 // loop resumes the same run - which `one_task` prefers over competing
855 // again - and so that swapping the binary a few times cannot exhaust a
856 // budget meant for agents that actually misbehaved.
857 if verdict.parked {
858 task.stall(detail);
859 return;
860 }
861 match verdict.status {
862 RunStatus::Merged | RunStatus::Ready => task.succeed(),
863 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
864 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
865 task.stall(detail)
866 }
867 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
868 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
869 RunStatus::Blocked => task.fail(detail, max_attempts),
870 RunStatus::VerifiedNoop => task.handed_off(detail),
871 other => task.fail(
872 format!(
873 "the graph stopped at `{}` without reaching a terminal status: {detail}",
874 label(other)
875 ),
876 max_attempts,
877 ),
878 }
879}
880
881/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
882/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
883/// itself has actually finished *and* its own last attempt is provably why:
884/// this loads that run and requires `Merged`/`Ready` before touching
885/// anything earlier in `runs`, since `Task::succeed` can also be called
886/// directly on a task whose last attempt never landed at all.
887///
888/// Called right after whatever call set `task.status` to
889/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
890/// `reclaim`'s, but also every other place a task can be closed by hand
891/// without the loop ever settling it itself: `magi task done`
892/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
893/// (`web::queue_done`). Closing a task by hand — after confirming a manual
894/// GitHub merge, say, exactly the workflow this repository's own
895/// "Landing a run's winner by hand" documents — is just as much "this task's
896/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
897/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
898/// forever, which is the exact backlog this status exists to clear. `pub`
899/// for those two out-of-module callers; everything else about this stays
900/// internal bookkeeping.
901///
902/// A run something is still actually driving is left alone: a
903/// task cannot be `Done` while one of its *own* attempts is still in flight,
904/// so a live one at this point can only be an unrelated process — a manual
905/// `--resume` of this old, now-moot run — and rewriting under it would just
906/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
907/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
908/// pair `run_report`/`run_detail` use for the same question elsewhere:
909/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
910/// --resume` invoked by hand outside it, which `liveness` also checks via
911/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
912/// (already terminal in some other way, or itself mid-run) is left untouched
913/// too.
914///
915/// Best-effort, like the rest of this module's bookkeeping: a load or save
916/// failure here is a `tracing::warn`, not a failed settle, and the next time
917/// this same task's completion is recorded — or a daemon restart replays
918/// `reclaim_orphaned_running` — is another chance to catch up. There is no
919/// separate reconciliation pass; if that gap ever matters in practice, one
920/// can be added then.
921///
922/// `home` is a parameter, not the process-global [`crate::run::home`], for
923/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
924/// calls this with `ui.home`, which is `crate::run::home()` in a real
925/// process but a fixture's own directory under test — falling through to
926/// the global there would read and write through whichever home some other
927/// test in the same binary happened to pin into that `OnceLock` first, not
928/// the run this call actually means.
929pub fn supersede_prior_runs(task: &Task, home: &Path) {
930 let now = Timestamp::now();
931 // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
932 // right behind a `Merged`/`Ready` verdict) from one set directly by
933 // `magi task done`/its web equivalent/the conductor on a task whose last
934 // recorded attempt never actually landed - that requires reading the
935 // run itself, which is exactly what this does before trusting anything
936 // in `runs` is safe to relabel.
937 let last_run_succeeded = task
938 .runs
939 .last()
940 .and_then(|id| RunState::load_under(id, home).ok())
941 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
942 for id in task.superseded_attempts(last_run_succeeded) {
943 let mut state = match RunState::load_under(id, home) {
944 Ok(s) => s,
945 Err(e) => {
946 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
947 continue;
948 }
949 };
950 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
951 continue;
952 }
953 let daemon_claims = is_working_on(home, id, now);
954 if state.liveness(daemon_claims) == Liveness::Live {
955 continue;
956 }
957 state.status = RunStatus::Superseded;
958 if let Err(e) = state.save_under(home) {
959 tracing::warn!("could not mark run {id} superseded: {e:#}");
960 }
961 }
962}
963
964/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
965/// finish the moment it was called, because one of its earlier attempts was
966/// still live then - a `magi run --resume` invoked by hand on an old run,
967/// most likely.
968///
969/// That skip is correct at the time (rewriting under a run something is
970/// still actively saving would just be undone), but a task only ever
971/// reaches `Done` once, so without this nothing would ever look at it
972/// again: if that manual process later ends anywhere other than
973/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
974/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
975/// backlog this status exists to clear. Called on the same idle-only
976/// cadence as [`janitor`], next to it rather than folded into it: this
977/// walks `queue` and `janitor` never otherwise needs one.
978///
979/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
980/// more than one attempt, every pass: each call is a handful of local file
981/// reads bounded by that task's own attempt count, the same order of cost
982/// [`clean::fold_due`] already pays scanning every run on disk on the same
983/// cadence, and a task already fully resolved costs one failed liveness
984/// check turned no-op the moment its lingering attempt is no longer live.
985fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
986 for task in queue.list() {
987 if task.status != TaskStatus::Done || task.runs.len() < 2 {
988 continue;
989 }
990 supersede_prior_runs(&task, home);
991 }
992}
993
994/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
995/// task ends up held.
996///
997/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
998/// dead daemon never got back to) share this, so the two cannot drift into
999/// disagreeing about which held tasks get a diagnostic.
1000fn settle_and_diagnose(
1001 task: &mut Task,
1002 verdict: Verdict,
1003 detail: &str,
1004 max_attempts: usize,
1005 state: &RunState,
1006) {
1007 settle(task, verdict, detail, max_attempts);
1008 if task.status == TaskStatus::Held {
1009 task.diagnostic = diagnostic(state);
1010 note_open_question(task, &state.id);
1011 }
1012}
1013
1014/// If `task` is held with a `magi ask` question still open on `run`, name the
1015/// question in [`Task::hold_reason`] rather than leaving the hold reading
1016/// only [`describe`]'s run summary.
1017///
1018/// This is the shape task 20260928-191407-05fd left underspecified: an
1019/// implementer settled a verified no-op and filed a question for the
1020/// operator, and the hold that followed said nothing about the question
1021/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1022/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1023/// marker) and must keep seeing it unchanged.
1024///
1025/// Best-effort: an unreadable question store must not stop a run from
1026/// settling, so this is a no-op rather than a propagated error when
1027/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1028fn note_open_question(task: &mut Task, run: &str) {
1029 let Some(home) = crate::run::try_home() else {
1030 return;
1031 };
1032 let open = Questions::at(home.join("questions")).open_for(run);
1033 let Some(q) = open.first() else {
1034 return;
1035 };
1036 let base = task.hold_reason.clone().unwrap_or_default();
1037 task.hold_reason = Some(format!(
1038 "{base} - waiting for operator answer to question {}",
1039 q.short()
1040 ));
1041}
1042
1043/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1044/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1045/// by some other means entirely, like a manual `magi run` resume that
1046/// finishes the graph outside the queue's bookkeeping.
1047///
1048/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1049/// `settle` is separate from `attempt`: a task recovered this way must land
1050/// exactly where a live daemon would have put it — the same policy table,
1051/// not a second one that quietly drifts from it — and that is only checkable
1052/// without spawning a real run.
1053fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
1054 match last_run {
1055 Some(state) => {
1056 let verdict = Verdict {
1057 status: state.status,
1058 left_pr: state.pr.is_some(),
1059 quota_hit: !state.quota.is_empty(),
1060 parked: state.parked,
1061 no_viable_candidates: state.viable().is_empty(),
1062 };
1063 let detail = format!(
1064 "recovered a `running` task whose daemon never recorded the outcome: {}",
1065 describe(&state)
1066 );
1067 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1068 }
1069 None => {
1070 let why = "task was `running` with no live daemon and no readable \
1071 run to recover; held for a human to check what happened";
1072 task.last_error = Some(why.to_owned());
1073 // The phone shows `hold_reason`, so a task held by the machine
1074 // says why there too and not only in `last_error`.
1075 task.hold_machine(Some(why.to_owned()));
1076 }
1077 }
1078}
1079
1080/// Find every task left at `running` that no live process is actually
1081/// driving, and settle each one against whatever its last run became.
1082///
1083/// # Why a claim is proof, not a guess
1084///
1085/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1086/// `running`, and the guard is held for the task's whole time in that status:
1087/// `attempt` does not return, and the loop does not move past the scope
1088/// holding the claim, until the run has settled. So a `running` task whose
1089/// lock is gone cannot have a live owner — this process or any other —
1090/// without needing a staleness threshold or a pid check the way
1091/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1092/// task that never got as far as `running` at all. Taking the claim here is
1093/// the whole test: it either fails, because something really does hold it
1094/// and the task is left alone, or it succeeds, which is the proof — and it is
1095/// kept for the rest of the decision so nothing else can start a competing
1096/// run while this one is being written.
1097///
1098/// Called on every poll, not only at startup, for the reason
1099/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1100/// keep noticing this, not only on the one morning it happened to restart.
1101fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1102 let mut reclaimed = Vec::new();
1103 for listed in queue.list() {
1104 if listed.status != TaskStatus::Running {
1105 continue;
1106 }
1107 let Ok(_claim) = queue.claim(&listed.id) else {
1108 continue;
1109 };
1110 // Re-read under the claim: a release or an edit landed by a human
1111 // between the listing above and the claim just taken must not be
1112 // clobbered by a decision based on the stale copy.
1113 let Ok(mut task) = queue.get(&listed.id) else {
1114 continue;
1115 };
1116 if task.status != TaskStatus::Running {
1117 continue;
1118 }
1119 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1120 // `execute` normally abandons a run's own open questions the moment
1121 // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1122 // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1123 // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1124 // with the question still `open`, because the process died before
1125 // reaching that call. `reclaim` itself stays pure on purpose (see its
1126 // own doc), so the same cleanup runs here instead, against the run
1127 // this reclaim is already reading. `settle_run` costs nothing when
1128 // `execute` already got there first.
1129 if let Some(state) = &last_run
1130 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1131 {
1132 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1133 }
1134 reclaim(&mut task, last_run, max_attempts);
1135 if task.status == TaskStatus::Done {
1136 supersede_prior_runs(&task, &crate::run::home());
1137 }
1138 record(queue, &mut task);
1139 reclaimed.push(task.id.clone());
1140 }
1141 reclaimed
1142}
1143
1144/// Find every run whose `run.json` is provably dead — every seat it still
1145/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1146/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1147/// not merely "no daemon claims it" — and fail it, clearing the leftover
1148/// active seats so the run stops reading as `implementing` (or whichever
1149/// node) forever.
1150///
1151/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1152/// `running`, using whatever `run.json` already says — but nothing in that
1153/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1154/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1155/// never got back to sits exactly where it was left: `active` full of seats
1156/// nobody will ever answer for, `status` stuck on whatever node was in
1157/// flight. `magi show` already tells an operator this in prose (`no live
1158/// daemon claims this run right now`); this is what makes that fact durable
1159/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1160/// stay stuck once nothing is driving it.
1161///
1162/// Runs on every poll, not only at startup, for the reason
1163/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1164/// daemon up for days must keep noticing a run some other, now-dead, daemon
1165/// left behind just as readily as one it trips over on the way up.
1166///
1167/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1168/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1169/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1170/// `runs` directory instead: `home` here is a parameter precisely so a test
1171/// can point it away from the operator's real history (see [`drive`]'s own
1172/// doc), and a scan that fell through to the global home anyway would walk
1173/// whichever directory some *other* process or test pinned into that
1174/// `OnceLock` first — mutating runs this call was never handed.
1175fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1176 reclaim_abandoned_runs_with(
1177 home,
1178 now,
1179 crate::proc::pid_status,
1180 crate::proc::process_started_at,
1181 )
1182}
1183
1184/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1185/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1186/// for the identical reason: this sweep's real damage (wiping a run's active
1187/// seats and failing it) has to be provable against an injected answer in a
1188/// test, not just the real process table.
1189fn reclaim_abandoned_runs_with<F, G>(
1190 home: &Path,
1191 now: Timestamp,
1192 query: F,
1193 identity: G,
1194) -> Vec<String>
1195where
1196 F: Fn(u32) -> Option<bool>,
1197 G: Fn(u32) -> Option<String>,
1198{
1199 let mut abandoned = Vec::new();
1200 for entry in std::fs::read_dir(home.join("runs"))
1201 .into_iter()
1202 .flatten()
1203 .flatten()
1204 {
1205 let id = entry.file_name().to_string_lossy().into_owned();
1206 if !crate::run::is_run_id(&id) {
1207 continue;
1208 }
1209 // Unreadable is `clean::fold_due`'s problem, not this one's — see
1210 // that module's docs for why a run this cannot parse is left alone
1211 // rather than guessed at. A different schema number is not that: this
1212 // touches only `status` and `active`, never a field whose meaning a
1213 // schema bump changed, so an old record's values serve this exactly
1214 // as well as a current one's (see `clean::read_state`'s own doc for
1215 // the same reasoning applied to folding).
1216 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1217 continue;
1218 };
1219 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1220 continue;
1221 };
1222 if state.status.done() || !state.active_all_overrun(now) {
1223 continue;
1224 }
1225 // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1226 // it", which is also the normal, healthy shape of a manual `magi
1227 // run` / `magi review` sharing this same home — this scan walks
1228 // every run on disk, not only ones this daemon itself started. Such
1229 // a run's active seats can legitimately sit past their own timeout
1230 // for a little while (the CLI finishing up, its result still being
1231 // collected) without the process driving it having died. `liveness`
1232 // is what actually tells the two apart, by corroborating
1233 // `driver_pid` against the process it names — see its own doc. Only
1234 // its strongest, provable answer licenses wiping this run's active
1235 // seats and failing it out from under whatever is still running it.
1236 let daemon_claims = is_working_on(home, &id, now);
1237 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1238 continue;
1239 }
1240 state.abandon("daemon");
1241 if let Err(e) = state.save_under(home) {
1242 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1243 continue;
1244 }
1245 // This run never passes through `Runner::execute` again, so its end
1246 // is announced here.
1247 if let Some(notice) = notices::run_ended(&state) {
1248 notices::raise_in(home, notice);
1249 }
1250 // The seat that asked is gone for good now, exactly like any other
1251 // door `graph::Runner::settle_questions` closes the moment `status`
1252 // lands somewhere non-resumable - see that method's own doc. Nothing
1253 // else reaches this one before the next `janitor()` startup pass
1254 // (`clean::abandon_settled_questions`), and a daemon that stays up
1255 // for days must not leave an open question badging the operator
1256 // until it happens to restart.
1257 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1258 tracing::warn!("abandon questions for {id}: {e:#}");
1259 }
1260 abandoned.push(id);
1261 }
1262 abandoned
1263}
1264
1265/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1266///
1267/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1268/// sets, so there is one loop body rather than two that drift apart the first
1269/// time the retry policy changes on only one of them.
1270pub async fn serve(opts: Opts) -> Result<()> {
1271 serve_until(opts, Stop::new()).await
1272}
1273
1274/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1275///
1276/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1277/// mid-node leaves worktrees, branches and agent sessions behind, and every
1278/// agent call already paid for is lost; finishing the run costs the operator a
1279/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1280/// current `execute` runs to its terminal status, the task's outcome is
1281/// recorded, and only then does the loop return. That window is what
1282/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1283/// still has a second Ctrl-C, which the runtime turns into a process kill —
1284/// and the task left `Running` then tells the next daemon, and the next human,
1285/// where to look.
1286///
1287/// While the queue is empty the stop is honoured within one wakeup rather than
1288/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1289/// caller that taps stop does not sit through the remainder of a sleep.
1290pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1291 let signal = {
1292 let stop = stop.clone();
1293 tokio::spawn(async move {
1294 if tokio::signal::ctrl_c().await.is_ok() {
1295 stop.stop();
1296 tracing::info!("shutdown requested; a run in flight will be finished first");
1297 }
1298 })
1299 };
1300
1301 let worktrees_root = opts
1302 .worktrees_root
1303 .clone()
1304 .unwrap_or_else(crate::run::default_worktree_root);
1305 let outcome = drive(
1306 &opts,
1307 &Queue::open(),
1308 &status_path(),
1309 &crate::run::home(),
1310 &worktrees_root,
1311 &stop,
1312 )
1313 .await;
1314
1315 signal.abort();
1316 outcome
1317}
1318
1319/// The loop proper: setup, poll, teardown, with the queue and the status file
1320/// supplied rather than discovered.
1321///
1322/// All three of `home`, `worktrees_root` and the queue/status paths are
1323/// parameters rather than resolved here, for the same reason:
1324/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1325/// so a unit test that pinned it would fight every other test in the binary,
1326/// and a loop that resolved its own worktree bay could only be exercised
1327/// against the operator's real `~/wt/<repo>` - publishing over a live
1328/// daemon's status file, claiming tasks out of a live backlog, and, since
1329/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1330/// whatever the operator actually has on disk.
1331async fn drive(
1332 opts: &Opts,
1333 queue: &Queue,
1334 status_file: &Path,
1335 home: &Path,
1336 worktrees_root: &Path,
1337 stop: &Stop,
1338) -> Result<()> {
1339 // The status file is a *snapshot*, not a stream of events: a reader only
1340 // ever wants the latest values, and every tick rewrites the whole file
1341 // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1342 // while an mpsc channel would force the loop to re-send unchanged fields on
1343 // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1344 // for no gain. The lock is only ever held across a field assignment, never
1345 // across an await.
1346 let status = Arc::new(Mutex::new(Status::new()));
1347 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1348 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1349
1350 // Read once at startup, not per task: how many runs this loop drives at
1351 // once is a property of the machine running it, not of whichever
1352 // repository a given task happens to name - see
1353 // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1354 // fact in the same sense the agent roster is.
1355 let daemon_cfg = prepare(&opts.repo, opts)
1356 .map(|c| c.daemon)
1357 .unwrap_or_default();
1358 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1359
1360 tracing::info!(
1361 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1362 queue.root().display(),
1363 opts.poll.as_secs(),
1364 opts.max_attempts,
1365 concurrency,
1366 if daemon_cfg.pause_for_interrupts {
1367 ", interrupts enabled"
1368 } else {
1369 ""
1370 }
1371 );
1372
1373 // `--once` drains an already-idle queue without reaching the idle wait,
1374 // but must still perform the startup cleanup.
1375 janitor(&opts.repo, opts, home, worktrees_root).await;
1376 resweep_superseded_attempts(queue, home);
1377
1378 let outcome = poll(
1379 opts,
1380 queue,
1381 &status,
1382 home,
1383 worktrees_root,
1384 stop,
1385 DispatchLimits {
1386 max_concurrent: concurrency,
1387 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1388 },
1389 )
1390 .await;
1391
1392 beat.abort();
1393 clear_status_at(status_file);
1394 outcome
1395}
1396
1397/// Refresh the status file on a fixed tick.
1398///
1399/// Separate from the loop because a run takes tens of minutes: a status file
1400/// written only between tasks would look stale for the whole of every run, and
1401/// a reader would report the daemon dead exactly while it was busiest.
1402async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1403 loop {
1404 tokio::time::sleep(HEARTBEAT).await;
1405 let snapshot = {
1406 let mut guard = lock(&status);
1407 guard.updated_at = Timestamp::now();
1408 guard.clone()
1409 };
1410 if let Err(e) = write_status_to(&path, &snapshot) {
1411 // A failed heartbeat must not take the daemon down: the loop is the
1412 // product, the status file is only the window onto it.
1413 tracing::warn!("could not refresh the daemon status file: {e:#}");
1414 }
1415 }
1416}
1417
1418/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1419/// if so, whether that wait is over.
1420#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1421enum LandResume {
1422 /// The task's last run is not parked on a land approval; schedule it
1423 /// like any other candidate.
1424 NotLanding,
1425 /// Parked in `land`, waiting on a question nobody has answered yet.
1426 /// Left alone: attempting it now would only re-observe the same pull
1427 /// request and park again, spending a `gh` call on a decision that has
1428 /// not changed since the last time this was checked.
1429 StillWaiting,
1430 /// Parked in `land`, and the question is settled - answered or
1431 /// abandoned. Resuming this is the one kind of candidate that must not
1432 /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1433 Ready,
1434}
1435
1436/// Classify a runnable candidate by whether it is parked on a land-merge
1437/// approval. Read-only - no claim taken, nothing written - so it is cheap
1438/// enough to call on every candidate, every poll.
1439fn land_resume_state(task: &Task) -> LandResume {
1440 let Some(run_id) = task.runs.last() else {
1441 return LandResume::NotLanding;
1442 };
1443 let Ok(state) = RunState::load(run_id) else {
1444 return LandResume::NotLanding;
1445 };
1446 if state.status != RunStatus::Landing || !state.parked {
1447 return LandResume::NotLanding;
1448 }
1449 let store = ask::Questions::open();
1450 let waiting = store
1451 .list()
1452 .into_iter()
1453 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1454 .max_by(|a, b| a.id.cmp(&b.id));
1455 let Some(mut q) = waiting else {
1456 return LandResume::Ready;
1457 };
1458 if !q.status.open() {
1459 return LandResume::Ready;
1460 }
1461 // `ask::ask_and_wait`'s own deadline is what used to retire a question
1462 // nobody ever answered; land's approval bypasses that wait entirely (see
1463 // `land::approval_gate`), so the same deadline has to be enforced here
1464 // instead, or `graph.answer_timeout` silently stops meaning anything for
1465 // a land approval and a run can sit `StillWaiting` forever with nobody
1466 // told to look at it.
1467 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1468 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1469 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1470 q.abandon(format!(
1471 "no answer within {}s of asking",
1472 timeout.as_secs().max(1)
1473 ));
1474 // If this can't be persisted, do not treat the wait as settled on a
1475 // guess: fall through and try again next poll.
1476 if store.put(&mut q).is_ok() {
1477 return LandResume::Ready;
1478 }
1479 }
1480 LandResume::StillWaiting
1481}
1482
1483/// How often the loop rechecks for new work while something it already
1484/// started is still running, rather than sleeping out the whole
1485/// [`Opts::poll`] interval.
1486///
1487/// Short on purpose: this is what lets a land-merge approval that comes back
1488/// while another task is mid-competition be noticed and resumed within a
1489/// fraction of a second, not within the next multi-second poll.
1490const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1491
1492/// How often [`poll`] rechecks the shared build cache against its cap at a
1493/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
1494/// waiting for the queue to run dry.
1495///
1496/// A queue that never empties means the `janitor` call at the bottom of this
1497/// loop's fully-idle branch can go unreached for as long as the backlog
1498/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
1499/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
1500/// 81.8 GiB an idle-only check let it reach before this existed, and it is
1501/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
1502/// backlog of short tasks does not pay for that walk on every poll.
1503const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1504
1505/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1506/// in `Status::current` - on drop, so both are released even if the attempt
1507/// panics rather than returning.
1508///
1509/// A `Drop` impl rather than statements written after the `.await` it
1510/// guards: a panic unwinds straight past code placed "after" a call, and
1511/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1512/// that ruling a panic out there is not a bet this loop can make. Without
1513/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1514/// forever - the idle branch in [`poll`], and with it the janitor, would
1515/// never run again - and a ghost entry in `Status::current` naming a task
1516/// nothing is still working on.
1517struct InFlightGuard<'a> {
1518 status: &'a Arc<Mutex<Status>>,
1519 stop: &'a Stop,
1520 task_id: &'a str,
1521}
1522
1523impl Drop for InFlightGuard<'_> {
1524 fn drop(&mut self) {
1525 lock(self.status).current.retain(|c| c.task != self.task_id);
1526 self.stop.exit();
1527 }
1528}
1529
1530/// State of [`poll`]'s own interrupt-scheduling sequence - see
1531/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
1532/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
1533/// both kept free of `Task`'s non-identity fields on purpose: every decision
1534/// here turns only on task ids and which ones are in flight, so the "never
1535/// more than one run at once" and "exactly one resume" invariants can be
1536/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
1537/// queue - which is exactly the coverage this feature's first two attempts
1538/// were missing.
1539///
1540/// Deliberately in-memory only, not written to disk anywhere: a daemon
1541/// restart mid-sequence loses track of which run it had asked to park and
1542/// which task was meant to run first, and simply falls back to `Idle` -
1543/// see [`drive`]'s own setup. The parked run itself is not lost - it is
1544/// sitting in the queue exactly like any other resumable, interrupted task,
1545/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
1546/// just resumes on the ordinary priority order rather than guaranteed to go
1547/// first. Giving that guarantee a crash-proof memory would mean a new queue
1548/// field and a recovery ordering to go with it, which is exactly the
1549/// complexity this feature's constraints rule out for the one property that
1550/// actually matters: at most one run, ever, at once.
1551#[derive(Debug, Clone, PartialEq, Eq)]
1552enum Interrupt {
1553 /// No interrupt sequence in progress. Ordinary dispatch applies.
1554 Idle,
1555 /// `interrupt_task` is runnable and exactly one other run is in flight;
1556 /// `parked` names that one task's id. Dispatch is withheld from
1557 /// everyone, including `interrupt_task` itself, until it has left
1558 /// flight - only then is `interrupt_task` let through.
1559 ///
1560 /// `parked` is a `Vec` rather than a bare id for symmetry with
1561 /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
1562 /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
1563 /// when exactly one run is in flight, so it is guaranteed to hold
1564 /// exactly one entry in practice - see that branch's own doc for why
1565 /// more than one is deliberately never attempted.
1566 Parking {
1567 parked: Vec<String>,
1568 interrupt_task: String,
1569 },
1570 /// `interrupt_task` is dispatched and in flight alone. Dispatch is
1571 /// withheld from everyone until it leaves flight - merged, failed, held,
1572 /// it makes no difference - at which point the sequence moves to
1573 /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
1574 /// going straight to `Idle` would hand `parked` back to ordinary
1575 /// priority-order dispatch, where a higher-priority task filed in the
1576 /// meantime could start ahead of it.
1577 Running {
1578 parked: Vec<String>,
1579 interrupt_task: String,
1580 },
1581 /// `interrupt_task` left flight; `parked` still names the one run this
1582 /// sequence owes a resume. Dispatch is withheld from everyone except
1583 /// that task - see [`interrupt_gate`] - so the resume this feature
1584 /// promises is never raced by, or run alongside, an unrelated candidate.
1585 /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
1586 /// own doc on abandonment - the moment it is no longer runnable at all.
1587 Resuming { parked: Vec<String> },
1588}
1589
1590/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
1591/// and `runnable` are read-only snapshots of this tick's reality, and the
1592/// only side effect the caller still owes the world is asking whichever
1593/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
1594/// site.
1595///
1596/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
1597/// accepted rather than a narrower type because that is what [`poll`] already
1598/// has on hand from [`runnable`], and building a second, smaller list on
1599/// every tick just to satisfy this signature would cost more than it proves.
1600///
1601/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
1602/// back to a task they are waiting on no longer being [`runnable`] - held,
1603/// blocked, deleted, or finished by some other means entirely, all of which
1604/// an operator can do to a task sitting in the queue with no claim on it at
1605/// all, at any moment, interrupt sequence or not. Without this check the
1606/// sequence would wait forever for a dispatch that can never come, and
1607/// `interrupt_gate` would withhold every other task in the queue right along
1608/// with it - a single `magi task hold` on the wrong id turning into a
1609/// daemon that never dispatches anything again.
1610fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
1611 match state {
1612 Interrupt::Idle => {
1613 // Not just "something to interrupt": exactly one thing. More
1614 // than one run in flight only happens above the default
1615 // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
1616 // one resume, never run alongside anything else" only because
1617 // it is only ever seeded with exactly one id - see
1618 // `Interrupt::Resuming`'s own doc on why releasing more than one
1619 // parked id back to ordinary dispatch cannot be made safe
1620 // against that same setting's own extra concurrency slots.
1621 // Waiting here for the herd to settle to one is the
1622 // simplification this feature's own constraints ask for rather
1623 // than a second concurrency model to reconcile with the first.
1624 if in_flight.len() != 1 {
1625 return Interrupt::Idle;
1626 }
1627 match runnable.iter().find(|t| t.interrupt) {
1628 Some(t) => Interrupt::Parking {
1629 parked: in_flight.to_vec(),
1630 interrupt_task: t.id.clone(),
1631 },
1632 None => Interrupt::Idle,
1633 }
1634 }
1635 Interrupt::Parking {
1636 parked,
1637 interrupt_task,
1638 } => {
1639 if in_flight.iter().any(|id| parked.contains(id)) {
1640 // Still waiting for what was in flight to actually stop.
1641 Interrupt::Parking {
1642 parked,
1643 interrupt_task,
1644 }
1645 } else if in_flight.contains(&interrupt_task) {
1646 Interrupt::Running {
1647 parked,
1648 interrupt_task,
1649 }
1650 } else if runnable.iter().any(|t| t.id == interrupt_task) {
1651 // The parked run(s) are gone, but the interrupt task has not
1652 // been dispatched yet on this tick - `interrupt_gate` is
1653 // what lets it through next.
1654 Interrupt::Parking {
1655 parked,
1656 interrupt_task,
1657 }
1658 } else {
1659 // The interrupt task itself is no longer runnable - see this
1660 // function's own doc on abandonment. The parked run(s) still
1661 // get their guaranteed resume; there is simply no interrupt
1662 // to run ahead of them any longer.
1663 Interrupt::Resuming { parked }
1664 }
1665 }
1666 Interrupt::Running {
1667 parked,
1668 interrupt_task,
1669 } => {
1670 if in_flight.contains(&interrupt_task) {
1671 Interrupt::Running {
1672 parked,
1673 interrupt_task,
1674 }
1675 } else {
1676 // The interrupt task's own run reached a terminal status,
1677 // whichever one - this is the *only* trigger that moves the
1678 // sequence on, driven straight off the same in-flight
1679 // bookkeeping `poll` already reaps every tick, not a second,
1680 // independent poll of anything.
1681 Interrupt::Resuming { parked }
1682 }
1683 }
1684 Interrupt::Resuming { parked } => {
1685 if in_flight.iter().any(|id| parked.contains(id)) {
1686 // One of the parked runs has been dispatched - the resume
1687 // this sequence owed is fulfilled. Whatever else is left in
1688 // `parked` (ordinarily nothing, at the default concurrency
1689 // of one) rejoins ordinary priority-order dispatch, same as
1690 // any other runnable task.
1691 Interrupt::Idle
1692 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
1693 Interrupt::Resuming { parked }
1694 } else {
1695 // Abandonment (see this function's own doc): nothing left in
1696 // `parked` is even runnable any longer.
1697 Interrupt::Idle
1698 }
1699 }
1700 }
1701}
1702
1703/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
1704/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
1705/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
1706/// indistinguishable from any other runnable task - exactly the "off does
1707/// nothing" this feature promises.
1708fn advance_interrupt_tick(
1709 enabled: bool,
1710 state: Interrupt,
1711 in_flight: &[String],
1712 runnable: &[Task],
1713) -> Interrupt {
1714 if !enabled {
1715 return Interrupt::Idle;
1716 }
1717 advance_interrupt(state, in_flight, runnable)
1718}
1719
1720/// Which of this tick's runnable candidates the interrupt sequence actually
1721/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
1722/// each half is assertable on its own: this is the half that keeps a
1723/// competition and an interrupt from ever running at the same moment.
1724fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
1725 match state {
1726 Interrupt::Idle => candidates,
1727 Interrupt::Parking {
1728 parked,
1729 interrupt_task,
1730 } => {
1731 if in_flight.iter().any(|id| parked.contains(id)) {
1732 Vec::new()
1733 } else {
1734 candidates
1735 .into_iter()
1736 .filter(|t| &t.id == interrupt_task)
1737 .collect()
1738 }
1739 }
1740 Interrupt::Running { .. } => Vec::new(),
1741 // At most one: even if `parked` names more than one id (more than
1742 // one run was in flight when the sequence began, only possible
1743 // above the default `max_concurrent_runs = 1`), only the first match
1744 // is offered. Capping this to a single candidate - not merely to
1745 // `parked`'s own ids - is what makes "exactly one resume, never two
1746 // dispatched together" true regardless of how many ordinary slots
1747 // happen to be free this tick.
1748 Interrupt::Resuming { parked } => candidates
1749 .into_iter()
1750 .find(|t| parked.contains(&t.id))
1751 .into_iter()
1752 .collect(),
1753 }
1754}
1755
1756/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
1757/// bundled into one parameter so `poll`'s own signature stays readable -
1758/// see [`drive`]'s call site for where these are actually read.
1759struct DispatchLimits {
1760 /// How many *ordinary* candidates run at once. See
1761 /// [`crate::config::Daemon::max_concurrent_runs`].
1762 max_concurrent: usize,
1763 /// See [`crate::config::Daemon::pause_for_interrupts`].
1764 pause_for_interrupts: bool,
1765}
1766
1767/// Which semaphore, if any, dispatching a candidate should draw its permit
1768/// from.
1769///
1770/// Pure and separate from [`poll`]'s loop body for the same reason
1771/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
1772/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
1773/// exactly the policy this feature adds, and a policy only exercisable by
1774/// running the whole loop is a policy nobody checks.
1775#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1776enum PermitKind {
1777 /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
1778 /// Checked first - a task can be both a land resume and marked
1779 /// [`Task::urgent`], and the resume's own "must not queue behind
1780 /// anything" guarantee takes precedence.
1781 None,
1782 /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
1783 /// (never in addition to trying) the ordinary pool. This is what lets
1784 /// an urgent task dispatch while every ordinary slot is already checked
1785 /// out, and what stops a second urgent task from opening a third run: it
1786 /// waits on this same one-slot semaphore rather than falling through to
1787 /// the ordinary one.
1788 Urgent,
1789 /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
1790 /// above.
1791 Ordinary,
1792}
1793
1794/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
1795/// own boolean, already computed by the caller from [`land_resume_state`].
1796fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
1797 if priority {
1798 PermitKind::None
1799 } else if urgent {
1800 PermitKind::Urgent
1801 } else {
1802 PermitKind::Ordinary
1803 }
1804}
1805
1806/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1807/// teardown and cannot skip the teardown on an early return.
1808///
1809/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
1810/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
1811/// land approval that has since been answered is dispatched outside that
1812/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
1813/// the whole point of parking there is that it must not queue behind
1814/// whatever else the loop happens to be running, even at the default of one.
1815/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
1816/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
1817/// these exemptions is still subject to the interrupt gate below, urgent
1818/// included: a land-resume or urgent candidate is exactly as much "something
1819/// else running" as an ordinary one from the interrupt sequence's point of
1820/// view, and letting either slip through while a run is being parked, or
1821/// while the interrupt task itself has the floor, is precisely the second
1822/// run 75dd's own "at most one run, ever, at once" guarantee must never
1823/// allow - see [`Interrupt`]'s own doc.
1824async fn poll(
1825 opts: &Opts,
1826 queue: &Queue,
1827 status: &Arc<Mutex<Status>>,
1828 home: &Path,
1829 worktrees_root: &Path,
1830 stop: &Stop,
1831 limits: DispatchLimits,
1832) -> Result<()> {
1833 let DispatchLimits {
1834 max_concurrent,
1835 pause_for_interrupts,
1836 } = limits;
1837 // Only consulted by `once`, where a task that just failed is still
1838 // `runnable` and would otherwise be picked up again inside the same drain.
1839 // In the long-running mode a later poll retrying a failed task is the point,
1840 // and the attempt counter is what bounds it.
1841 let mut attempted: Vec<String> = Vec::new();
1842 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1843 // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
1844 // entirely separate from `sem`: an urgent candidate must dispatch
1845 // alongside whatever `sem` already has checked out, never by waiting for
1846 // one of those ordinary slots to free up and never by growing
1847 // `max_concurrent_runs` itself. Sized at one, not unbounded - see
1848 // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
1849 // first on this same slot rather than opening a third run.
1850 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
1851 // A quota hit is a fact about the machine, not the task that happened to
1852 // surface it, and every other *ordinary* candidate is no less likely to
1853 // hit the same wall - see the warning below. A land-merge resume is
1854 // exempt: it is a human decision finishing, not a fresh competition, and
1855 // must not sit out a quota cooldown it did not cause.
1856 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1857 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1858 let mut conductor = Conductor::new();
1859 // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
1860 // a congested queue would otherwise starve of the fully-idle branch below.
1861 let mut cache_last_checked: Option<Timestamp> = None;
1862 // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
1863 let mut interrupt = Interrupt::Idle;
1864 // The `Pause` handed to each dispatched candidate's own `Runner` - see
1865 // `attempt`'s new parameter - kept here so the tick that decides to park
1866 // a run for an interrupt can reach that specific run's handle and no
1867 // other's. Pruned to whatever is still in flight at the top of every
1868 // tick, so a finished attempt's handle does not linger.
1869 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
1870 std::collections::HashMap::new();
1871
1872 while !stop.stopped() {
1873 lock(status).polls += 1;
1874
1875 // Reap whatever finished since the last tick without blocking on
1876 // anything still running. `InFlightGuard` already released the slot
1877 // even if the spawned attempt panicked; this only surfaces that it
1878 // happened, since a panic swallowed here otherwise leaves no trace.
1879 while let Some(result) = inflight.try_join_next() {
1880 if let Err(e) = result {
1881 tracing::error!("a spawned attempt did not finish cleanly: {e}");
1882 notices::raise(Notice::error(
1883 "loop:attempt",
1884 "A queued attempt ended abnormally; check the task it was running.",
1885 ));
1886 }
1887 }
1888
1889 let swept = sweep_stale_claims(queue, STALE_CLAIM);
1890 if !swept.is_empty() {
1891 tracing::warn!(
1892 "swept {} stale claim(s) left behind by an earlier daemon: {}",
1893 swept.len(),
1894 swept.join(", ")
1895 );
1896 }
1897 // Capture stalled work before reclaiming it. A dead daemon's ordinary
1898 // lock is swept and reclaimed in this same poll, but the conductor
1899 // must still see that it was stranded rather than only its mechanical
1900 // terminal state.
1901 let now = Timestamp::now();
1902
1903 // No run this daemon spawned is mid-compile right now, whether or
1904 // not another candidate is about to start - see
1905 // `maybe_prune_cache_between_runs`'s own doc for why this cannot
1906 // wait for the queue to run dry.
1907 if !stop.busy_now() {
1908 maybe_prune_cache_between_runs(
1909 &opts.repo,
1910 opts,
1911 home,
1912 stop,
1913 &mut cache_last_checked,
1914 now,
1915 )
1916 .await;
1917 }
1918
1919 let stalled = stalled_tasks(queue, home, now);
1920 let stalled_ids: std::collections::BTreeSet<_> =
1921 stalled.iter().map(|task| task.id.clone()).collect();
1922 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1923 if !reclaimed.is_empty() {
1924 tracing::warn!(
1925 "reclaimed {} task(s) left `running` by a daemon that never \
1926 recorded the outcome: {}",
1927 reclaimed.len(),
1928 reclaimed.join(", ")
1929 );
1930 }
1931 let abandoned_runs = reclaim_abandoned_runs(home, now);
1932 if !abandoned_runs.is_empty() {
1933 tracing::warn!(
1934 "failed {} run(s) left behind by a killed process, past every \
1935 active seat's own timeout: {}",
1936 abandoned_runs.len(),
1937 abandoned_runs.join(", ")
1938 );
1939 }
1940
1941 // `home`, not `ask::Questions::open()`'s own process-global default:
1942 // `poll` is handed its home explicitly precisely so a test can point
1943 // it elsewhere, the same reason `Queue::at` and the status file path
1944 // are parameters rather than resolved here - see `drive`'s own doc.
1945 let questions = Questions::at(home.join("questions"));
1946
1947 // Deterministic: no model, run before the conductor sees anything so
1948 // its input reflects the queue's current, already-resolved state.
1949 resolve_blockers(queue, &questions);
1950 reconcile_task_questions(queue, &questions);
1951
1952 // The conductor gets one look per cycle, right before the loop takes
1953 // its next task, and only when there is something new to look at -
1954 // see `Conductor::worth_a_look`'s own doc for why "stalled is
1955 // non-empty" is the wrong test. Checked before `prepare` so an
1956 // unchanged cycle never pays for a synchronous config load.
1957 let finished: Vec<Task> = finished_tasks(queue)
1958 .into_iter()
1959 .filter(|task| !stalled_ids.contains(&task.id))
1960 .collect();
1961 let queued = queued_tasks(queue);
1962 // An empty queue has nothing to arrange. In particular, do not let
1963 // the conductor's initial snapshot cause synchronous config I/O
1964 // between the caller's stop notification and the idle wait below.
1965 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1966 && conductor.worth_a_look(queue, &stalled, &finished)
1967 {
1968 match prepare(&opts.repo, opts) {
1969 Ok(cfg) => {
1970 conductor
1971 .maybe_run(
1972 &cfg,
1973 &opts.repo,
1974 queue,
1975 &questions,
1976 home,
1977 &queued,
1978 &stalled,
1979 &finished,
1980 opts.max_attempts,
1981 )
1982 .await;
1983 }
1984 Err(e) => {
1985 tracing::warn!("conductor: no config: {e:#}");
1986 notices::raise(Notice::warn(
1987 "loop:no-config",
1988 "The loop could not read this repository's config, so held tasks are not being triaged.",
1989 ));
1990 }
1991 }
1992 }
1993
1994 let candidates: Vec<Task> = runnable(queue)
1995 .into_iter()
1996 .filter(|t| !opts.once || !attempted.contains(&t.id))
1997 .collect();
1998
1999 // A task id only stays a key here while its attempt is genuinely in
2000 // flight; `status.current` is the same liveness fact `InFlightGuard`
2001 // maintains for the phone's own status file, so this piggybacks on
2002 // it rather than tracking a second copy of the same thing.
2003 let in_flight: Vec<String> = lock(status)
2004 .current
2005 .iter()
2006 .map(|c| c.task.clone())
2007 .collect();
2008 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2009
2010 interrupt =
2011 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2012 if let Interrupt::Parking {
2013 parked,
2014 interrupt_task,
2015 } = &interrupt
2016 {
2017 let reason = format!(
2018 "task {} asked to run first",
2019 crate::run::short_of(interrupt_task)
2020 );
2021 for id in parked {
2022 if let Some(pause) = interrupt_pauses.get(id) {
2023 pause.park_because(reason.clone());
2024 }
2025 }
2026 }
2027 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2028
2029 let cooling_down =
2030 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2031
2032 let mut started_any = false;
2033 for candidate in candidates {
2034 if stop.stopped() {
2035 break;
2036 }
2037
2038 let resume = land_resume_state(&candidate);
2039 if resume == LandResume::StillWaiting {
2040 continue;
2041 }
2042 let priority = resume == LandResume::Ready;
2043
2044 if !priority && cooling_down {
2045 continue;
2046 }
2047 let permit = match permit_kind(priority, candidate.urgent) {
2048 PermitKind::None => None,
2049 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2050 Ok(p) => Some(p),
2051 // The one urgent slot is already spoken for by another
2052 // `--urgent` task's run. Keep looking rather than falling
2053 // back to the ordinary pool - see `PermitKind::Urgent`'s
2054 // own doc - a later candidate might still be an ordinary
2055 // task with a free slot, or another priority resume.
2056 Err(_) => continue,
2057 },
2058 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2059 Ok(p) => Some(p),
2060 // No ordinary slot free right now. A later candidate in
2061 // this same list might still be a priority resume or an
2062 // urgent task, so keep looking rather than stopping here.
2063 Err(_) => continue,
2064 },
2065 };
2066
2067 // A claim we cannot take means another daemon, or a human running
2068 // `magi run`, got there first. That is not the task's fault and
2069 // must not spend one of its attempts: move to the next candidate
2070 // rather than recording a failure.
2071 let Ok(claim) = queue.claim(&candidate.id) else {
2072 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2073 continue;
2074 };
2075 // Re-read under the claim: the task on disk may have been held or
2076 // edited between the listing and the lock.
2077 let mut task = match queue.get(&candidate.id) {
2078 Ok(t) if t.status.runnable() => t,
2079 Ok(_) => continue,
2080 Err(e) => {
2081 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2082 continue;
2083 }
2084 };
2085 let task_id = task.id.clone();
2086 attempted.push(task_id.clone());
2087 lock(status).idle = false;
2088 // A stop asked for from here on is "finishing", not "stopped": the
2089 // run gets to reach a terminal status before the loop returns.
2090 stop.enter();
2091 started_any = true;
2092
2093 // A fresh, unshared handle - never `stop.pause()` - so parking
2094 // this run for an interrupt cannot leak into any other run this
2095 // loop ever drives. See `Pause`'s own doc.
2096 let run_pause = crate::graph::Pause::new();
2097 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2098
2099 let opts = opts.clone();
2100 let queue = queue.clone();
2101 let status = Arc::clone(status);
2102 let stop = stop.clone();
2103 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2104 inflight.spawn(async move {
2105 // Held for the whole attempt: dropping either at the end of
2106 // this task is what releases the claim and, for an ordinary
2107 // candidate, frees its concurrency slot back to the loop.
2108 let _claim = claim;
2109 let _permit = permit;
2110 // See `InFlightGuard`: this must survive a panic inside `attempt`.
2111 let _inflight = InFlightGuard {
2112 status: &status,
2113 stop: &stop,
2114 task_id: &task_id,
2115 };
2116 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2117 lock(&status).completed += 1;
2118 // A quota loss is a fact about the machine, not this task, and
2119 // the next ordinary candidate the loop offers is no less
2120 // likely to hit the same wall: without a cooldown here a
2121 // whole backlog can be run - and failed - in the seconds it
2122 // takes each attempt to notice the CLI is out of quota.
2123 let now = Timestamp::now();
2124 if let Some(until) = cooldown_until("a, now) {
2125 let wait = until.as_second() - now.as_second();
2126 *lock("a_cooldown_until) = Some(until);
2127 let hint = quota
2128 .iter()
2129 .find(|q| q.reset.is_some())
2130 .and_then(|q| q.reset.as_deref());
2131 match hint {
2132 Some(h) => tracing::warn!(
2133 "quota hit; waiting {wait}s before taking another ordinary task \
2134 (CLI reported reset: {h})"
2135 ),
2136 None => tracing::warn!(
2137 "quota hit; waiting {wait}s before taking another ordinary task \
2138 (no reset hint reported)"
2139 ),
2140 }
2141 }
2142 });
2143 }
2144
2145 if started_any {
2146 continue;
2147 }
2148
2149 if stop.busy_now() {
2150 // Something started on an earlier tick is still running. Recheck
2151 // soon rather than sleeping out the whole poll interval - a freed
2152 // slot, or a land approval answered mid-run, must not sit idle
2153 // for it.
2154 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2155 continue;
2156 }
2157
2158 // Truly idle: nothing new to start and nothing still running.
2159 lock(status).idle = true;
2160 if opts.once {
2161 // A one-shot drain must perform the same post-work cleanup as a
2162 // daemon that reached a normal idle interval. The startup pass
2163 // cannot see runs or cache files produced by this drain.
2164 janitor(&opts.repo, opts, home, worktrees_root).await;
2165 resweep_superseded_attempts(queue, home);
2166 triage_held(queue, home, opts).await;
2167 break;
2168 }
2169 stop.idle(opts.poll).await;
2170 if stop.stopped() {
2171 continue;
2172 }
2173 // Housekeeping only after a full quiet interval. Running it before
2174 // the first idle wait can block the executor while an operator's
2175 // stop request is waiting to be scheduled, defeating Stop's retained
2176 // wake permit. No run can start while this branch is active, so the
2177 // janitor still never races an in-flight compile.
2178 janitor(&opts.repo, opts, home, worktrees_root).await;
2179 resweep_superseded_attempts(queue, home);
2180 triage_held(queue, home, opts).await;
2181 }
2182
2183 // Never return while a run is still in flight, whichever way the loop
2184 // above exited: a stop only sets a flag - see `serve_until` - and
2185 // returning here while `inflight` still holds spawned work would abandon
2186 // it exactly as a mid-node kill would.
2187 while let Some(result) = inflight.join_next().await {
2188 if let Err(e) = result {
2189 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2190 notices::raise(Notice::error(
2191 "loop:attempt",
2192 "A queued attempt ended abnormally; check the task it was running.",
2193 ));
2194 }
2195 }
2196 Ok(())
2197}
2198
2199/// Run one claimed task to a terminal status and record the outcome.
2200///
2201/// Every transition is flushed to the queue as it happens, so the state on disk
2202/// is what actually occurred rather than what this process still intends to
2203/// write.
2204async fn attempt(
2205 opts: &Opts,
2206 queue: &Queue,
2207 status: &Arc<Mutex<Status>>,
2208 stop: &Stop,
2209 interrupt_pause: crate::graph::Pause,
2210 task: &mut Task,
2211) -> Vec<QuotaLoss> {
2212 let repo = repo_for(task, &opts.repo);
2213 tracing::info!(
2214 "task {} — {} (repo {})",
2215 task.short(),
2216 task.title,
2217 repo.display()
2218 );
2219
2220 let mut config = match prepare(&repo, opts) {
2221 Ok(c) => c,
2222 Err(e) => {
2223 // A setup failure spends an attempt even though no run was minted.
2224 // Without that, a task naming a repository that does not exist
2225 // would be retried at every poll for as long as the daemon lives.
2226 task.attempts += 1;
2227 task.fail(format!("config: {e:#}"), opts.max_attempts);
2228 record(queue, task);
2229 return Vec::new();
2230 }
2231 };
2232 apply_solo(&mut config, task);
2233
2234 // The free-space gate, checked *before* anything is minted: a task that
2235 // waits out a full disk costs nothing yet, and must not spend an attempt
2236 // or start a run the machine cannot finish. Held tasks stay in the list
2237 // for the human to see, and `magi task release` re-queues them when space
2238 // comes back - the same recovery as any other hold. A volume whose free
2239 // space cannot be measured closes the gate too: starting a run blind on a
2240 // disk that may be full is how the machine ends up with 6.7 GB free.
2241 if let Some(reason) = disk_gate(&repo, &config) {
2242 task.last_error = Some(reason.clone());
2243 task.hold_machine(Some(reason.clone()));
2244 record(queue, task);
2245 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2246 // Stable wording - the free-space figures live in the task's hold
2247 // reason, and changing numbers would relight the bell every poll.
2248 notices::raise(
2249 Notice::warn(
2250 &format!("disk:{}", repo.display()),
2251 "A task was held for want of free disk space; free some, then release it from the queue.",
2252 )
2253 .link(Link::Task {
2254 id: task.id.clone(),
2255 }),
2256 );
2257 return Vec::new();
2258 }
2259
2260 // A resumable run of this task is carried on, never re-competed. The
2261 // candidates are built and paid for, and a fresh competition races a
2262 // second implementation against them.
2263 //
2264 // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2265 // started 3cbf on the same task a moment later, duplicating two and a
2266 // half hours of agent work. Then b25f stalled on a judge that timed out
2267 // and one that answered with no JSON - `quota: 0`, so nothing the machine
2268 // was to blame for - and 4043 started **one second** later, buying three
2269 // fresh implementations to reach the same panel. `RunStatus::resumable`
2270 // rather than `!done()` is what catches the second case: a stall is
2271 // terminal, and its cheap recovery re-asks only the absent seats.
2272 //
2273 // A load failure is warned about rather than silently read as "not
2274 // resumable": the alternative is exactly what let a schema mismatch on
2275 // run `eba2` fall through to a full re-competition with nobody told why.
2276 // `crate::conduct` is what actually offers a better answer than
2277 // `Runner::start` here (see `Recovery::Review`), once this task's next
2278 // failure shows it up as `held`/`failed` with the run state unreadable.
2279 let unfinished = (!task.fresh_start)
2280 .then(|| unfinished_run(&task.runs, task.short()))
2281 .flatten();
2282 // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2283 // branch survived, and this reopens exactly that branch as a
2284 // review-only pass rather than resuming or competing again. Consumed
2285 // (cleared) here whichever way this goes, so it never outlives this one
2286 // attempt - see `queue::Task::review_branch`.
2287 let review_branch = task.review_branch.take();
2288 let branch_exists = match &review_branch {
2289 Some(branch) => crate::git::branch_exists(&repo, branch)
2290 .await
2291 .unwrap_or(false),
2292 None => false,
2293 };
2294 let starter = choose_starter(
2295 review_branch.as_deref(),
2296 branch_exists,
2297 unfinished.as_deref(),
2298 );
2299 let started = match &starter {
2300 Starter::Review(branch) => {
2301 tracing::info!(
2302 "task {} reopens `{branch}` as a review-only pass",
2303 task.short()
2304 );
2305 Runner::review(&repo, branch, config).await
2306 }
2307 Starter::Resume(id) => {
2308 tracing::info!("resuming run {id} rather than competing again");
2309 Runner::resume(id).map(|mut r| {
2310 if let Some(instruction) =
2311 prepare_instruction(&starter, Some(&r.state.instruction), task)
2312 {
2313 r.state.instruction = instruction;
2314 }
2315 r
2316 })
2317 }
2318 Starter::Start => {
2319 if let Some(branch) = &review_branch {
2320 tracing::warn!(
2321 "conductor chose review for task {} but branch `{branch}` no longer \
2322 exists; requeuing as a fresh competition instead",
2323 task.short()
2324 );
2325 }
2326 let instruction = prepare_instruction(&starter, None, task)
2327 .unwrap_or_else(|| task.instruction.clone());
2328 Runner::start(&repo, instruction, config).await
2329 }
2330 };
2331 let mut runner = match started {
2332 Ok(r) => r,
2333 Err(e) => {
2334 task.attempts += 1;
2335 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2336 record(queue, task);
2337 return Vec::new();
2338 }
2339 };
2340 // A stop that means "park" reaches the graph through this handle.
2341 runner.on_pause(stop.pause());
2342 // `poll`'s interrupt scheduler reaches this one run - and no other -
2343 // through this handle. See `Pause`'s own doc for why these are never
2344 // the same one.
2345 runner.watch_interrupt(interrupt_pause);
2346
2347 // `start` has minted the run, so the task can now point at it. Persisting
2348 // `Running` before `execute` is what makes a crash mid-run legible.
2349 let run = runner.state.id.clone();
2350 task.start(run.clone());
2351 record(queue, task);
2352 lock(status).current.push(Current {
2353 task: task.id.clone(),
2354 run,
2355 });
2356
2357 // `RunState::quota` is the run's whole history across every resume, so
2358 // only what this execution added may arm the cooldown or earn a refund.
2359 let quota_before = runner.state.quota.clone();
2360 let detail = match runner.execute().await {
2361 Ok(()) => describe(&runner.state),
2362 Err(e) => format!("{e:#}"),
2363 };
2364 let fresh = losses_this_attempt("a_before, &runner.state.quota);
2365 let verdict = Verdict {
2366 status: runner.state.status,
2367 // A run that opened a pull request handed its work over, whatever the
2368 // gate then decided about merging it.
2369 left_pr: runner.state.pr.is_some(),
2370 // Only a rate limit earns the task its attempt back - and only one
2371 // suffered now: a refund justified by a previous session's loss is
2372 // the same mistake as re-arming the cooldown from it. A stalled run
2373 // resumed without hitting quota again therefore spends its attempt,
2374 // like any other failure of the task's own.
2375 quota_hit: !fresh.is_empty(),
2376 // A run that parked was asked to stop; that is not a failure and must
2377 // not spend an attempt, or replacing the binary a few times would
2378 // exhaust a task's budget without an agent ever misbehaving.
2379 parked: runner.state.parked,
2380 // A quota loss that left nothing viable is the same machine fact as a
2381 // `Stalled` quota loss; see `settle`'s doc table.
2382 no_viable_candidates: runner.state.viable().is_empty(),
2383 };
2384 settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2385 if task.status == TaskStatus::Done {
2386 supersede_prior_runs(task, &crate::run::home());
2387 }
2388 record(queue, task);
2389 tracing::info!(
2390 "task {} is {} after run {} ({})",
2391 task.short(),
2392 task.status.as_str(),
2393 runner.state.short(),
2394 label(runner.state.status)
2395 );
2396 fresh
2397}
2398
2399/// The quota losses `after` holds that `before` did not: what one execution
2400/// suffered, as opposed to the run's history.
2401///
2402/// Compared by value rather than by length or position because
2403/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2404/// the vector can shrink and shift under a resume. A retried seat that hits
2405/// quota again is a `push` with a new `at`, so it shows up as new here.
2406/// `reclaim` deliberately keeps reading the whole history: after a crash there
2407/// is no attempt boundary to diff against.
2408fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2409 after
2410 .iter()
2411 .filter(|q| !before.contains(q))
2412 .cloned()
2413 .collect()
2414}
2415
2416/// When the loop-wide quota cooldown should end, given this attempt's losses;
2417/// `None` when there were none. Reset-hint parsing and the cap live here.
2418fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2419 if quota.is_empty() {
2420 return None;
2421 }
2422 let with_hint = quota.iter().find(|q| q.reset.is_some());
2423 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2424 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2425 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2426 Some(
2427 now.checked_add(jiff::SignedDuration::from_secs(secs))
2428 .unwrap_or(Timestamp::MAX),
2429 )
2430}
2431
2432/// Cut this attempt's candidate count to one when the task asked to run
2433/// alone.
2434///
2435/// Pure and separate from [`attempt`] so the one thing this feature changes -
2436/// which `candidates` a `solo` task's run is built with - can be asserted
2437/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2438/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2439/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2440/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2441fn apply_solo(config: &mut Config, task: &Task) {
2442 if task.solo {
2443 config.graph.candidates = 1;
2444 }
2445}
2446
2447/// Load the config for a task's repository, with the merge override applied.
2448fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2449 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2450 if let Some(mode) = &opts.merge {
2451 config.merge.mode = merge_mode(mode)?;
2452 }
2453 Ok(config)
2454}
2455
2456/// Prune the shared build cache back under its cap at a safe boundary
2457/// between runs, so a queue that never empties - and so never reaches
2458/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2459/// does not leave the cache to grow unchecked for as long as the backlog
2460/// lasts.
2461///
2462/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2463/// same liveness fact the idle branch's own janitor call rests on - no run
2464/// this daemon spawned is still mid-compile - so pruning here races nothing.
2465/// The caller must not call this while a run is in flight; there is no
2466/// second `busy_now()` check inside this function, on purpose, because there
2467/// is nothing left to check that `busy_now()` has not already answered.
2468///
2469/// A stop that has already been asked for *is* checked here, for a different
2470/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2471/// synchronously before it decides anything, so the poll loop cannot get back
2472/// to its own `stopped()` test until that walk is over — and a loop already
2473/// on its way out must not make the operator wait out housekeeping it is
2474/// about to stop needing. This is the same call the idle branch makes when it
2475/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2476/// it matters more here: `busy_now()` is false throughout, so
2477/// [`Stop::finishing`] would report a stop as already landed while the walk
2478/// still held the loop. Nothing is lost by skipping — the cap is a standing
2479/// policy, and the next daemon's startup pass measures the same cache.
2480///
2481/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2482/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2483/// and the next has not yet claimed a task, which can be every few
2484/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2485/// more than the growth it is guarding against.
2486async fn maybe_prune_cache_between_runs(
2487 repo: &Path,
2488 opts: &Opts,
2489 home: &Path,
2490 stop: &Stop,
2491 last_checked: &mut Option<Timestamp>,
2492 now: Timestamp,
2493) {
2494 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2495 return;
2496 }
2497 *last_checked = Some(now);
2498 let cfg = match prepare(repo, opts) {
2499 Ok(cfg) => cfg,
2500 Err(e) => {
2501 tracing::warn!("cache check: no config: {e:#}");
2502 return;
2503 }
2504 };
2505 match clean::prune_cache_if_over_limit(&cfg, home) {
2506 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2507 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2508 pruned.files,
2509 pruned.freed
2510 ),
2511 Ok(_) => {}
2512 Err(e) => {
2513 tracing::warn!("housekeep: prune cache: {e:#}");
2514 notices::raise_in(
2515 home,
2516 Notice::warn(
2517 "housekeep:cache",
2518 "Pruning the shared build cache failed; disk usage may keep growing.",
2519 ),
2520 );
2521 }
2522 }
2523}
2524
2525/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2526/// now, given when it last did (if ever). Pure, so the cadence is asserted
2527/// directly rather than by waiting out real minutes in a test.
2528fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2529 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2530}
2531
2532/// The disk janitor, with its housekeeping logged rather than fatal.
2533///
2534/// Called only at the loop's idle points, for the reason the caller documents:
2535/// a prune racing a live compile would delete files mid-build. The config is
2536/// re-read on every call because the repository that just ran may not be the
2537/// daemon's own default, and the cache directory is a repository fact.
2538///
2539/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2540/// and [`crate::run::default_worktree_root`] read here, for the same reason
2541/// [`drive`] takes its queue and status file rather than resolving them: a
2542/// test driving the loop must not reach through to the operator's real home
2543/// or worktree bay just because the janitor runs on every idle tick.
2544/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2545/// to get wrong silently - a test's `home` was already isolated, but nothing
2546/// exercised the parameter next to it, so a real worktree bay stayed wired in
2547/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2548/// it for real, every test in this file that drives the loop at all started
2549/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2550async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2551 let cfg = match prepare(repo, opts) {
2552 Ok(cfg) => cfg,
2553 Err(e) => {
2554 tracing::warn!("housekeep: no config: {e:#}");
2555 return;
2556 }
2557 };
2558 // A run's own worktree lives under `config.graph.worktree_root` when the
2559 // repository sets one - the same precedence `RunState::worktree_root`
2560 // uses - and `worktrees_root` only stands in for the *default* an
2561 // unconfigured repository resolves to (see this function's own
2562 // parameter, or the test fixture wiring one to a fake path). Housekeeping
2563 // that always swept the default regardless of this override would never
2564 // see, and so never reclaim, a single worktree for a repository that
2565 // relocated them elsewhere.
2566 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2567 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2568 // Reported whenever there is anything to say, not only when `folded > 0`:
2569 // the incident this exists to prevent was 90 of 93 runs skipped and 0
2570 // folded, on every single pass, for months - a report gated on `folded`
2571 // would have stayed silent through every one of them.
2572 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2573 let mut extra = Vec::new();
2574 if out.unreadable > 0 {
2575 extra.push(format!("{} unreadable", out.unreadable));
2576 }
2577 if out.orphaned_worktrees > 0 {
2578 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2579 }
2580 let detail = if extra.is_empty() {
2581 String::new()
2582 } else {
2583 format!(" ({})", extra.join(", "))
2584 };
2585 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2586 }
2587 if out.external_merges_recorded > 0 {
2588 tracing::info!(
2589 "housekeep: recorded {} run(s) as merged externally",
2590 out.external_merges_recorded
2591 );
2592 }
2593 if out.cache_files > 0 {
2594 tracing::info!(
2595 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2596 out.cache_files,
2597 out.cache_freed
2598 );
2599 }
2600 if out.questions_abandoned > 0 {
2601 tracing::info!(
2602 "housekeep: abandoned {} question(s) left open by a finished run",
2603 out.questions_abandoned
2604 );
2605 }
2606}
2607
2608/// Run [`triage::run_once`] and log whatever it did, the same "only when
2609/// there is something to say" rule [`janitor`] follows for its own report.
2610///
2611/// Called at the same idle points as [`janitor`] - once per full poll
2612/// interval, never mid-attempt - for the same reason: it is not liveness
2613/// critical, and a task's own `hold_reason` string is the one thing this
2614/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2615/// tick for no benefit.
2616async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2617 let questions = Questions::at(home.join("questions"));
2618 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2619 if report.is_empty() {
2620 return;
2621 }
2622 if !report.quarantined.is_empty() {
2623 tracing::info!(
2624 "triage: held {} blocked task(s) whose blocked-on task or \
2625 question no longer exists: {}",
2626 report.quarantined.len(),
2627 report.quarantined.join(", ")
2628 );
2629 }
2630 if !report.resumed.is_empty() {
2631 tracing::info!(
2632 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2633 report.resumed.len(),
2634 report.resumed.join(", ")
2635 );
2636 }
2637 if !report.asked.is_empty() {
2638 tracing::info!(
2639 "triage: asked about {} held task(s): {}",
2640 report.asked.len(),
2641 report.asked.join(", ")
2642 );
2643 }
2644 if !report.answered.is_empty() {
2645 tracing::info!(
2646 "triage: applied {} operator answer(s): {}",
2647 report.answered.len(),
2648 report.answered.join(", ")
2649 );
2650 }
2651}
2652
2653/// The free-space gate: what stands between this task and a new run, if
2654/// anything. `Some(reason)` holds the task; `None` lets it start.
2655///
2656/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2657/// the operator opted out. A measurement failure is a gate, not a pass: both
2658/// sides of "cannot tell" are served by not starting.
2659fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2660 disk_gate_with(repo, config, crate::disk::free_bytes)
2661}
2662
2663/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2664/// test can assert the exact wiring `attempt` runs - config's threshold in,
2665/// task-holding reason out - without asking the real machine's disk anything.
2666fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2667 repo: &Path,
2668 config: &Config,
2669 free_bytes: F,
2670) -> Option<String> {
2671 let min = config.disk.min_free_bytes;
2672 if min == 0 {
2673 return None;
2674 }
2675 match free_bytes(repo) {
2676 Ok(free) => crate::disk::gate(free, min),
2677 Err(e) => Some(format!(
2678 "could not measure free space on {} ({e}); the disk gate refuses \
2679 to let a run start blind",
2680 repo.display()
2681 )),
2682 }
2683}
2684
2685/// How long to wait before offering another task when a run lost a seat to a
2686/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2687/// could read, or carried nothing at all. Long enough that a quota outage
2688/// cannot burn through a whole backlog in the few seconds each doomed attempt
2689/// takes to fail; short enough that a quota which clears early is not left
2690/// idle for the fallback's sake.
2691const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2692
2693/// Longest a parsed reset hint may push the wait out to. The hint comes from
2694/// the CLI's own words, not a contract, so a parsing slip that lands a day
2695/// away must not leave the loop asleep for a day.
2696const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2697
2698/// How long [`poll`] should wait before offering the next task, after a run
2699/// lost at least one seat to a rate limit.
2700///
2701/// Pure and separate from the loop so the policy can be exercised without a
2702/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2703/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2704/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2705/// far a parsed hint is trusted to push the wait out.
2706fn quota_wait(
2707 reset_at: Option<Timestamp>,
2708 now: Timestamp,
2709 fallback: Duration,
2710 cap: Duration,
2711) -> Duration {
2712 match reset_at {
2713 Some(at) if at > now => {
2714 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
2715 Duration::from_secs(secs).min(cap)
2716 }
2717 _ => fallback,
2718 }
2719}
2720
2721/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
2722///
2723/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
2724/// explains why parsing it exactly "would be a bug factory" — so this only
2725/// recognises the shapes actually observed in the wild, and returns `None`
2726/// for anything else rather than guess at a format nobody has seen.
2727///
2728/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
2729/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
2730/// said it, not from whenever this loop happens to read it: anchoring on `now`
2731/// would push the reset later on every read and would read an already-elapsed
2732/// reset as still in the future. (A long hint is still clamped by
2733/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
2734fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
2735 parse_reset_hint_zoned(text, now)
2736 .or_else(|| parse_reset_hint_dated(text))
2737 .or_else(|| parse_reset_hint_relative(text, recorded))
2738}
2739
2740/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
2741/// optional but at least one required, in that order. A bare number or any
2742/// unknown unit is refused.
2743fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
2744 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
2745 let mut rest = rest.trim();
2746 if rest.is_empty() {
2747 return None;
2748 }
2749 let mut total: i64 = 0;
2750 let mut matched = false;
2751 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
2752 if let Some((digits, tail)) = rest.split_once(unit)
2753 && !digits.is_empty()
2754 && digits.bytes().all(|b| b.is_ascii_digit())
2755 {
2756 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
2757 rest = tail;
2758 matched = true;
2759 }
2760 }
2761 if !rest.is_empty() || !matched {
2762 return None;
2763 }
2764 recorded
2765 .checked_add(jiff::SignedDuration::from_secs(total))
2766 .ok()
2767}
2768
2769/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
2770/// case-insensitive) into a 24-hour hour and minute. Shared by every
2771/// reset-hint shape below.
2772fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
2773 let clock = clock.trim().to_lowercase();
2774 let (digits, pm) = clock
2775 .strip_suffix("am")
2776 .map(|d| (d, false))
2777 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
2778 let (h, m) = digits.trim().split_once(':')?;
2779 let mut hour: i8 = h.trim().parse().ok()?;
2780 let minute: i8 = m.trim().parse().ok()?;
2781 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
2782 return None;
2783 }
2784 if pm && hour != 12 {
2785 hour += 12;
2786 } else if !pm && hour == 12 {
2787 hour = 0;
2788 }
2789 Some((hour, minute))
2790}
2791
2792/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
2793/// and a zone, never a date. A clock reading already past today is read as
2794/// tomorrow's: a CLI naming a same-day reset that has already gone by means
2795/// the window rolled over while nothing was watching.
2796fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
2797 let open = text.find('(')?;
2798 let close = text.rfind(')')?;
2799 if close <= open {
2800 return None;
2801 }
2802 let zone = text[open + 1..close].trim();
2803 let (hour, minute) = parse_12h_clock(&text[..open])?;
2804 let tz = jiff::tz::TimeZone::get(zone).ok()?;
2805 let candidate = now
2806 .to_zoned(tz)
2807 .with()
2808 .hour(hour)
2809 .minute(minute)
2810 .second(0)
2811 .millisecond(0)
2812 .microsecond(0)
2813 .nanosecond(0)
2814 .build()
2815 .ok()?;
2816 let mut at = candidate.timestamp();
2817 if at <= now {
2818 at += jiff::SignedDuration::from_hours(24);
2819 }
2820 Some(at)
2821}
2822
2823/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
2824/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
2825/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
2826/// "already past today" correction to make: the year already disambiguates
2827/// it. Scanned as a five-word window so it can be pulled out of the middle
2828/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
2829/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
2830/// any other timestamp with no zone attached.
2831fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
2832 let words: Vec<&str> = text.split_whitespace().collect();
2833 if words.len() < 5 {
2834 return None;
2835 }
2836 (0..=words.len() - 5)
2837 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
2838}
2839
2840/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
2841/// parenthesis right after the window is refused rather than ignored — it
2842/// reads as an explicit zone annotation on a shape that otherwise carries
2843/// none, and guessing UTC anyway would be exactly the silent misread this
2844/// module's parsing otherwise avoids.
2845fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
2846 if trailing.is_some_and(|next| next.starts_with('(')) {
2847 return None;
2848 }
2849 let month = month_number(window[0])?;
2850 let day_token = window[1].strip_suffix(',')?.to_lowercase();
2851 let day_digits = ["st", "nd", "rd", "th"]
2852 .iter()
2853 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
2854 let day: i8 = day_digits.parse().ok()?;
2855 let year_token = window[2];
2856 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
2857 return None;
2858 }
2859 let year: i16 = year_token.parse().ok()?;
2860 // The am/pm word carries the sentence's own trailing punctuation, e.g.
2861 // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
2862 // reusing the same 12-hour clock reader the bracketed shape uses.
2863 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
2864 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
2865 let date = jiff::civil::Date::new(year, month, day).ok()?;
2866 let candidate = date
2867 .at(hour, minute, 0, 0)
2868 .to_zoned(jiff::tz::TimeZone::UTC)
2869 .ok()?;
2870 Some(candidate.timestamp())
2871}
2872
2873/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
2874/// case-insensitively, into a 1-based month number.
2875fn month_number(name: &str) -> Option<i8> {
2876 const NAMES: [&str; 12] = [
2877 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
2878 ];
2879 let lower = name.to_lowercase();
2880 NAMES
2881 .iter()
2882 .position(|n| *n == lower.as_str())
2883 .map(|i| i as i8 + 1)
2884}
2885
2886/// Resuming a `Blocked` run that already spent every review round its own
2887/// config allowed cannot make progress: `graph::Runner`'s review loop walks
2888/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
2889/// reached `max_rounds`, so `execute` would settle straight back to
2890/// `Blocked` without asking anyone anything. Read-only against a state this
2891/// build never mutates — `src/graph.rs` stays untouched — but without this
2892/// check, [`unfinished_run`] would keep reporting such a run as still
2893/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
2894/// promise is a fresh competition when a design needs to change) would
2895/// silently resume the exhausted run instead, spending an attempt on a
2896/// cycle that cannot change anything.
2897fn exhausted_review_budget(state: &RunState) -> bool {
2898 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
2899}
2900
2901/// This task's *most recent* run, if resuming it would actually make
2902/// progress. `short` is only for the warning's own message.
2903///
2904/// Only ever `runs.last()` — never a search back through older history.
2905/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
2906/// mint, oldest first, and every entry before the last one was already
2907/// superseded at the moment it was minted: the daemon only ever starts a new
2908/// run when the previous one was not worth resuming (unresumable, exhausted,
2909/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
2910/// opens a fresh review-only run alongside an older, already-failed
2911/// competition. Searching further back would let an old run that merely
2912/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
2913/// behind, say — get resumed instead of the fresh competition
2914/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
2915/// nothing asked to revisit.
2916///
2917/// Two runs paid for the "prefer resuming over restarting" half of this
2918/// lesson, which is why this still checks `runs.last()` rather than always
2919/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
2920/// task a moment later, duplicating two and a half hours of agent work. Then
2921/// b25f stalled on a judge that timed out and one that answered with no JSON
2922/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
2923/// **one second** later, buying three fresh implementations to reach the
2924/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
2925/// the second case: a stall is terminal, and its cheap recovery re-asks only
2926/// the absent seats. [`exhausted_review_budget`] is the other half: a run
2927/// that is technically `resumable()` but provably cannot progress must not
2928/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
2929/// no-op instead of the fresh competition it promises.
2930///
2931/// A load failure is warned about rather than silently read as "not
2932/// resumable": the alternative is exactly what let a schema mismatch on run
2933/// `eba2` fall through to a full re-competition with nobody told why.
2934/// `crate::conduct` is what actually offers a better answer than
2935/// `Runner::start` here (see `Recovery::Review`), once this task's next
2936/// failure shows it up as `held`/`failed` with the run state unreadable.
2937fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
2938 unfinished_run_with(runs, short, RunState::load)
2939}
2940
2941/// [`unfinished_run`] with an injected state reader. Tests provide their
2942/// fixtures directly rather than touching the process-global run home.
2943fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
2944where
2945 F: FnOnce(&str) -> Result<RunState>,
2946{
2947 let id = runs.last()?;
2948 match load(id) {
2949 Ok(s) if s.status.resumable() && !exhausted_review_budget(&s) => Some(id.clone()),
2950 Ok(_) => None,
2951 Err(e) => {
2952 tracing::warn!("could not read run {id} for task {short}: {e:#}");
2953 None
2954 }
2955 }
2956}
2957
2958/// Which of the three ways [`attempt`] can mint or continue a run this task
2959/// should use.
2960#[derive(Debug, Clone, PartialEq, Eq)]
2961enum Starter {
2962 /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
2963 /// and that still exists.
2964 Review(String),
2965 /// `crate::graph::Runner::resume` on an unfinished run of this task.
2966 Resume(String),
2967 /// `crate::graph::Runner::start`: a fresh competition.
2968 Start,
2969}
2970
2971/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
2972/// this attempt should use. Pure, and separate from [`attempt`], so the
2973/// routing itself is assertable without spawning a real graph or a git
2974/// process: `attempt`'s own `crate::git::branch_exists` call has already
2975/// happened by the time this is called.
2976///
2977/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
2978/// whose branch is gone falls all the way through to [`Starter::Start`], not
2979/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
2980/// old (likely `Blocked`) run in the first place, and a branch that vanished
2981/// out from under that choice is not evidence resuming it would fare better.
2982fn choose_starter(
2983 review_branch: Option<&str>,
2984 branch_exists: bool,
2985 unfinished: Option<&str>,
2986) -> Starter {
2987 match review_branch {
2988 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
2989 Some(_) => Starter::Start,
2990 None => match unfinished {
2991 Some(id) => Starter::Resume(id.to_owned()),
2992 None => Starter::Start,
2993 },
2994 }
2995}
2996
2997/// Which repository a task runs in. A task that names none — the normal case
2998/// for one filed from a phone — runs in the daemon's own default.
2999fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3000 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3001 return fallback.to_path_buf();
3002 }
3003 task.repo.clone()
3004}
3005
3006/// The header [`append_answers`] appends operator answers under. Shared with
3007/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
3008/// rather than grown a new block on every resume.
3009const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3010
3011/// Render the first `count` answers in the block appended to an instruction.
3012fn answers_block(task: &Task, count: usize) -> String {
3013 let mut s = ANSWERS_HEADER.to_owned();
3014 for a in &task.answers[..count] {
3015 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3016 }
3017 s
3018}
3019
3020/// Append every answer `crate::conduct` has collected for `task` onto `base`,
3021/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
3022fn append_answers(base: &str, task: &Task) -> String {
3023 if task.answers.is_empty() {
3024 return base.to_owned();
3025 }
3026 let mut s = base.to_owned();
3027 s.push_str(&answers_block(task, task.answers.len()));
3028 s
3029}
3030
3031/// Drop the prior answer block only when it is exactly the suffix this task
3032/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
3033/// the task author is ordinary instruction text, not a block to remove.
3034fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3035 for count in (1..=task.answers.len()).rev() {
3036 let block = answers_block(task, count);
3037 if let Some(base) = instruction.strip_suffix(&block) {
3038 return base;
3039 }
3040 }
3041 instruction
3042}
3043
3044/// The instruction handed to `Runner::start`: the task's own text, plus any
3045/// operator answers `crate::conduct` collected for it (see
3046/// [`Task::answers`]), so a decision the operator actually made reaches the
3047/// implementers rather than only clearing the block that was waiting on it.
3048///
3049/// Appended rather than merged into [`Task::instruction`] itself, so the
3050/// task's own record stays exactly what its author wrote.
3051fn instruction_for(task: &Task) -> String {
3052 append_answers(&task.instruction, task)
3053}
3054
3055/// The instruction a resumed run should carry on with: whatever it already
3056/// had, refreshed with the task's *current* operator answers.
3057///
3058/// A resumable run's own `RunState::instruction` predates any answer
3059/// `crate::conduct` collects after the run parks, so resuming it unchanged —
3060/// the behaviour before this function existed — silently drops the very
3061/// decision the operator made to unblock it. Re-stripping any block this
3062/// function appended on an earlier resume before re-appending the current
3063/// list (rather than blindly appending again) is what keeps a task resumed
3064/// three times over three answered questions from carrying the same answer
3065/// three times.
3066fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3067 append_answers(strip_answers_block(old_instruction, task), task)
3068}
3069
3070/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
3071/// answers before handing it to `Runner` — the actual boundary between
3072/// [`choose_starter`]'s routing and the graph, factored out so it is
3073/// assertable without a real repository, git branch, or agent CLI.
3074///
3075/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
3076/// instruction from the reviewed branch's own commit log because there is no
3077/// task statement to speak of for hand-written work, and splicing operator
3078/// answers into that text would contradict the very message it sends
3079/// reviewers ("there is no task statement").
3080fn prepare_instruction(
3081 starter: &Starter,
3082 old_instruction: Option<&str>,
3083 task: &Task,
3084) -> Option<String> {
3085 match starter {
3086 Starter::Start => Some(instruction_for(task)),
3087 Starter::Resume(_) => Some(resumed_instruction(
3088 old_instruction.expect("a resumed run always has a prior instruction"),
3089 task,
3090 )),
3091 Starter::Review(_) => None,
3092 }
3093}
3094
3095/// Persist a transition. A queue write failure is logged rather than fatal: the
3096/// run already happened, and taking the daemon down would only add a lost
3097/// backlog to a full disk.
3098fn record(queue: &Queue, task: &mut Task) {
3099 if let Err(e) = queue.put(task) {
3100 tracing::error!("could not record task {}: {e:#}", task.short());
3101 notices::raise(Notice::error(
3102 "loop:record",
3103 "The loop could not save a task's state; check the disk.",
3104 ));
3105 }
3106}
3107
3108/// Every runnable task, in the order the loop should try them.
3109///
3110/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
3111/// tail exists so that a claim somebody else holds costs the loop the next
3112/// candidate rather than a whole poll interval of idleness.
3113fn runnable(queue: &Queue) -> Vec<Task> {
3114 let mut tasks: Vec<Task> = queue
3115 .list()
3116 .into_iter()
3117 .filter(|t| t.status.runnable())
3118 .collect();
3119 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3120 tasks
3121}
3122
3123/// Why a run ended where it did, in one line, for [`Task::last_error`].
3124///
3125/// A stalled run names the seats the quota took out: "out of quota" is not
3126/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
3127/// agent to replace or which plan to top up.
3128///
3129/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
3130/// purpose: unlike `label`'s other callers (an internal log line, an
3131/// already-a-bug fallback message), this string becomes `Task::last_error`
3132/// verbatim, which the phone renders in the same alarm-styled box an
3133/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
3134/// `.err` styling. A bare `verified_noop` there would read exactly like the
3135/// failure this whole feature exists to tell apart from one.
3136fn describe(state: &RunState) -> String {
3137 let mut detail = if state.status == RunStatus::Stalled {
3138 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3139 seats.sort_unstable();
3140 seats.dedup();
3141 if seats.is_empty() {
3142 "the judging panel lost its quorum".to_owned()
3143 } else {
3144 format!(
3145 "the judging panel lost its quorum; quota took out {}",
3146 seats.join(", ")
3147 )
3148 }
3149 } else {
3150 format!("run ended {}", state.status.display_label())
3151 };
3152 if let Some(last) = state.events.last() {
3153 detail.push_str(&format!(" ({}: {})", last.node, last.message));
3154 }
3155 detail.push_str(&format!(" [run {}]", state.id));
3156 detail
3157}
3158
3159/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3160///
3161/// The task file lives in the backlog indefinitely; a diagnostic is an
3162/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3163/// stay small regardless of how much a gate command or a candidate printed.
3164const DIAGNOSTIC_MAX: usize = 4_000;
3165
3166/// Tail kept from a single failing command's output inside a diagnostic.
3167/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3168/// pointer for a human deciding whether to go read the full artifact by hand,
3169/// not a replacement for reading it.
3170const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3171
3172/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3173/// `magi task show` says more than the one-line reason in [`describe`].
3174///
3175/// The one-liner answers "where did the run stop"; this answers "what would a
3176/// human have found opening `artifacts/` by hand" — the point of the whole
3177/// feature is the case that one-liner actively misleads on: a run held as "no
3178/// candidate produced a change" can mean the implementer actually finished
3179/// the task (opened a PR, merged it, tagged a release) and only left a clean
3180/// local worktree behind, which reads as "nothing happened" unless someone
3181/// goes and reads what the agent actually said. `None` when the run carries
3182/// none of the three shapes this recognises — an ordinary run held for
3183/// something not diagnosable from `RunState` alone still explains itself
3184/// through `Task::last_error`.
3185fn diagnostic(state: &RunState) -> Option<String> {
3186 let mut parts: Vec<String> = Vec::new();
3187
3188 // Gate failure: which check(s), and the tail of what each printed.
3189 for o in state.gate.iter().filter(|o| !o.ok()) {
3190 parts.push(format!(
3191 "gate `{}` failed ({:?}):\n{}",
3192 o.command,
3193 o.code,
3194 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3195 ));
3196 }
3197
3198 // The land loop gave up because the fixer declined while checks were
3199 // still red: the message already names them (see `land::run`).
3200 if let Some(last) = state
3201 .events
3202 .iter()
3203 .rev()
3204 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3205 {
3206 parts.push(last.message.clone());
3207 }
3208
3209 // No viable candidate: every implementer's own final word, sanitized the
3210 // same way a judge would have read it, so a run that actually finished
3211 // the job does not read as an unexplained failure. A verified no-op is
3212 // called out ahead of its own summary and apart from an ordinary
3213 // failure's `why` — this is the one candidate shape whose diagnostic a
3214 // human is expected to actually judge, not just skim.
3215 if state.viable().is_empty() {
3216 for c in &state.candidates {
3217 if let Some(evidence) = &c.verified_noop {
3218 parts.push(format!(
3219 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3220 c.label
3221 ));
3222 } else if !c.summary.trim().is_empty() {
3223 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3224 } else if let Some(why) = &c.failed {
3225 parts.push(format!("candidate {}: {why}", c.label));
3226 }
3227 }
3228 }
3229
3230 if parts.is_empty() {
3231 return None;
3232 }
3233 // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3234 // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3235 // back slightly over. Leave it enough room to always land under the
3236 // limit.
3237 Some(crate::run::tail(
3238 &parts.join("\n\n"),
3239 DIAGNOSTIC_MAX.saturating_sub(100),
3240 ))
3241}
3242
3243/// Stable lower-case name for a run status, for an internal log line and the
3244/// "graph stopped without reaching a terminal status" bug message in
3245/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3246/// doc for why that one reads [`RunStatus::display_label`] instead. One
3247/// definition of a status's name, on the type that owns it: this table used
3248/// to live here as a second copy, and a status renamed in one place would
3249/// have gone on reading correctly in the other.
3250fn label(status: RunStatus) -> &'static str {
3251 status.as_str()
3252}
3253
3254/// Parse a merge mode override.
3255fn merge_mode(mode: &str) -> Result<MergeMode> {
3256 match mode {
3257 "none" => Ok(MergeMode::None),
3258 "local" => Ok(MergeMode::Local),
3259 "pr" => Ok(MergeMode::Pr),
3260 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3261 }
3262}
3263
3264/// Take the status lock, recovering from a poisoned one.
3265///
3266/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3267/// data, and the worst a poisoned lock can hold is a stale timestamp.
3268fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3269 mutex
3270 .lock()
3271 .unwrap_or_else(std::sync::PoisonError::into_inner)
3272}
3273
3274#[cfg(test)]
3275mod tests {
3276 use super::*;
3277 use crate::queue::{Source, TaskStatus};
3278 use crate::run::{Candidate, CommandOutcome};
3279 use pretty_assertions::assert_eq;
3280
3281 fn task() -> Task {
3282 Task::new(
3283 "add retries".to_owned(),
3284 "add retries".to_owned(),
3285 PathBuf::from("/repo"),
3286 Source::Human,
3287 )
3288 }
3289
3290 /// A runnable task marked to interrupt, with an id fixed for assertions
3291 /// rather than the random one [`Task::new`] mints.
3292 fn interrupt_task(id: &str) -> Task {
3293 let mut t = task();
3294 t.id = id.to_owned();
3295 t.interrupt = true;
3296 t
3297 }
3298
3299 /// An ordinary runnable task with an id fixed for assertions.
3300 fn task_with_id(id: &str) -> Task {
3301 let mut t = task();
3302 t.id = id.to_owned();
3303 t
3304 }
3305
3306 /// A runnable task marked `--urgent`, with an id fixed for assertions.
3307 fn urgent_task(id: &str) -> Task {
3308 let mut t = task();
3309 t.id = id.to_owned();
3310 t.urgent = true;
3311 t
3312 }
3313
3314 /// The land-resume exemption wins outright, whether or not the candidate
3315 /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3316 /// queue behind anything" guarantee cannot be weaker just because the
3317 /// same task was also filed with `--urgent`.
3318 #[test]
3319 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3320 assert_eq!(permit_kind(true, false), PermitKind::None);
3321 assert_eq!(permit_kind(true, true), PermitKind::None);
3322 }
3323
3324 /// The one property this whole feature exists for: `--urgent` draws from
3325 /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3326 /// ordinary candidate draws from the ordinary pool exactly as before,
3327 /// untouched by the urgent slot's existence.
3328 #[test]
3329 fn permit_kind_separates_urgent_from_ordinary() {
3330 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3331 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3332 }
3333
3334 /// The exact wiring `attempt` runs before minting anything: a config's
3335 /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3336 /// Free space is injected rather than asked of the real disk - the point
3337 /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3338 /// is deterministic on every machine this test runs on, never dependent
3339 /// on how full the CI runner's own disk happens to be.
3340 #[test]
3341 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3342 let cfg = Config::default();
3343 let repo = Path::new("/any/repo/path");
3344
3345 let reason =
3346 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3347 assert!(reason.contains("1024"), "{reason}");
3348 assert!(
3349 reason.contains(&cfg.disk.min_free_bytes.to_string()),
3350 "{reason}"
3351 );
3352
3353 assert_eq!(
3354 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3355 None,
3356 "exactly at the floor is open"
3357 );
3358 assert_eq!(
3359 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3360 None,
3361 "comfortably above the floor is open"
3362 );
3363 }
3364
3365 #[test]
3366 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3367 let mut cfg = Config::default();
3368 cfg.disk.min_free_bytes = 0;
3369 let repo = Path::new("/any/repo/path");
3370 assert_eq!(
3371 disk_gate_with(repo, &cfg, |_| Ok(0)),
3372 None,
3373 "a zero floor never measures at all"
3374 );
3375 }
3376
3377 #[test]
3378 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3379 let cfg = Config::default();
3380 let repo = Path::new("/any/repo/path");
3381 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3382 .expect("a measurement failure must close the gate, not open it");
3383 assert!(reason.contains("could not measure"), "{reason}");
3384 }
3385
3386 #[test]
3387 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3388 let ordinary = task();
3389 let next = advance_interrupt(
3390 Interrupt::Idle,
3391 std::slice::from_ref(&ordinary.id),
3392 std::slice::from_ref(&ordinary),
3393 );
3394 assert_eq!(next, Interrupt::Idle);
3395 }
3396
3397 #[test]
3398 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3399 // Nothing to interrupt - this is just an ordinary candidate, and the
3400 // loop's normal dispatch will pick it up like any other.
3401 let marked = interrupt_task("marked");
3402 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3403 assert_eq!(next, Interrupt::Idle);
3404 }
3405
3406 #[test]
3407 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3408 let marked = interrupt_task("marked");
3409 let next = advance_interrupt(
3410 Interrupt::Idle,
3411 &["running".to_owned()],
3412 std::slice::from_ref(&marked),
3413 );
3414 assert_eq!(
3415 next,
3416 Interrupt::Parking {
3417 parked: vec!["running".to_owned()],
3418 interrupt_task: "marked".to_owned(),
3419 }
3420 );
3421 }
3422
3423 /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3424 /// one run can be in flight when a task becomes runnable and marked.
3425 /// Parking all of them would mean `Resuming` later has more than one id
3426 /// to release back to ordinary dispatch, which cannot be made safe
3427 /// against that same setting's own extra concurrency slots letting two
3428 /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3429 /// The simplification the task's own constraints ask for: do not begin
3430 /// a sequence at all until the herd settles back to exactly one.
3431 #[test]
3432 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3433 let marked = interrupt_task("marked");
3434
3435 let two = advance_interrupt(
3436 Interrupt::Idle,
3437 &["a".to_owned(), "b".to_owned()],
3438 std::slice::from_ref(&marked),
3439 );
3440 assert_eq!(two, Interrupt::Idle);
3441
3442 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3443 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3444 }
3445
3446 #[test]
3447 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3448 let state = Interrupt::Parking {
3449 parked: vec!["running".to_owned()],
3450 interrupt_task: "marked".to_owned(),
3451 };
3452 // Still in flight: no change.
3453 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3454 assert_eq!(still_going, state);
3455
3456 // Left flight, but the interrupt task has not been dispatched yet on
3457 // this tick - stays `Parking` so `interrupt_gate` can let it through,
3458 // as long as it is still runnable.
3459 let stopped_but_not_yet_dispatched =
3460 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3461 assert_eq!(stopped_but_not_yet_dispatched, state);
3462
3463 // Left flight, and the interrupt task is now in flight itself.
3464 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3465 assert_eq!(
3466 dispatched,
3467 Interrupt::Running {
3468 parked: vec!["running".to_owned()],
3469 interrupt_task: "marked".to_owned(),
3470 }
3471 );
3472 }
3473
3474 #[test]
3475 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3476 let state = Interrupt::Running {
3477 parked: vec!["running".to_owned()],
3478 interrupt_task: "marked".to_owned(),
3479 };
3480 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3481 assert_eq!(still_running, state);
3482
3483 // Whatever it ended as - merged, failed, held - is not this
3484 // function's concern: leaving flight is the only trigger, driven
3485 // straight off the same in-flight list `poll` already reaps. It does
3486 // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3487 // why that would let an unrelated task start ahead of, or alongside,
3488 // the guaranteed resume.
3489 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3490 assert_eq!(
3491 ended,
3492 Interrupt::Resuming {
3493 parked: vec!["running".to_owned()]
3494 }
3495 );
3496 }
3497
3498 #[test]
3499 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3500 let state = Interrupt::Resuming {
3501 parked: vec!["running".to_owned()],
3502 };
3503 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3504 assert_eq!(still_waiting, state);
3505
3506 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3507 assert_eq!(dispatched, Interrupt::Idle);
3508 }
3509
3510 /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3511 /// or otherwise moved on by an operator with no claim standing in the
3512 /// way - must not wedge the sequence (and so the whole loop's dispatch,
3513 /// via `interrupt_gate`) waiting forever for a dispatch that can never
3514 /// come. The parked run still gets its resume.
3515 #[test]
3516 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3517 {
3518 let state = Interrupt::Parking {
3519 parked: vec!["running".to_owned()],
3520 interrupt_task: "marked".to_owned(),
3521 };
3522 // `marked` has been held/blocked/deleted since the sequence began:
3523 // it no longer appears in `runnable` at all.
3524 let next = advance_interrupt(state, &[], &[]);
3525 assert_eq!(
3526 next,
3527 Interrupt::Resuming {
3528 parked: vec!["running".to_owned()]
3529 },
3530 "abandoning the interrupt must not abandon the resume it owes"
3531 );
3532 }
3533
3534 /// The same abandonment, one step later: `Resuming` itself must not wait
3535 /// forever for a parked task that has since become unrunnable.
3536 #[test]
3537 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3538 let state = Interrupt::Resuming {
3539 parked: vec!["running".to_owned()],
3540 };
3541 let next = advance_interrupt(state, &[], &[]);
3542 assert_eq!(
3543 next,
3544 Interrupt::Idle,
3545 "nothing is left to wait for; the loop must not stay wedged"
3546 );
3547 }
3548
3549 #[test]
3550 fn disabled_by_config_the_sequence_can_never_leave_idle() {
3551 let marked = interrupt_task("marked");
3552 let next = advance_interrupt_tick(
3553 false,
3554 Interrupt::Idle,
3555 &["running".to_owned()],
3556 std::slice::from_ref(&marked),
3557 );
3558 assert_eq!(
3559 next,
3560 Interrupt::Idle,
3561 "an unmarked, unconfigured daemon must behave exactly as before"
3562 );
3563 }
3564
3565 #[test]
3566 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3567 let state = Interrupt::Parking {
3568 parked: vec!["running".to_owned()],
3569 interrupt_task: "marked".to_owned(),
3570 };
3571 let candidates = vec![interrupt_task("marked"), task()];
3572 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3573 assert!(
3574 allowed.is_empty(),
3575 "nothing may dispatch - not even the interrupt task itself - \
3576 until the parked run has actually stopped"
3577 );
3578 }
3579
3580 /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3581 /// grow a special case for it: an urgent candidate that is not the
3582 /// interrupt task withholds exactly like an ordinary one for as long as
3583 /// the parked run it is racing has not actually left flight. A version
3584 /// of this feature once bypassed the gate for urgent candidates, on the
3585 /// theory that a genuinely separate concurrency lane could not collide
3586 /// with 75dd's own; it could, and did - the bypassed task dispatched
3587 /// alongside a run 75dd's own state machine had only *asked* to park,
3588 /// not yet confirmed gone, which is exactly the second run
3589 /// `Interrupt::Parking`'s own doc says must never happen. There is no
3590 /// tick during Parking/Running/Resuming where letting an extra
3591 /// candidate through is safe, urgent or not - the parked run may still
3592 /// be genuinely mid-call.
3593 #[test]
3594 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3595 for state in [
3596 Interrupt::Parking {
3597 parked: vec!["running".to_owned()],
3598 interrupt_task: "marked".to_owned(),
3599 },
3600 Interrupt::Running {
3601 parked: vec!["running".to_owned()],
3602 interrupt_task: "marked".to_owned(),
3603 },
3604 Interrupt::Resuming {
3605 parked: vec!["running".to_owned()],
3606 },
3607 ] {
3608 let candidates = vec![
3609 interrupt_task("marked"),
3610 urgent_task("hot"),
3611 task_with_id("ordinary"),
3612 ];
3613 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3614 assert!(
3615 !allowed.iter().any(|t| t.id == "hot"),
3616 "an urgent candidate must wait out the same gate as anything \
3617 else while the run it would run alongside has not actually \
3618 left flight, for state {state:?}: {allowed:?}"
3619 );
3620 }
3621 }
3622
3623 /// The one case where marking a task `--urgent` and `interrupt` at once
3624 /// is not redundant: once the interrupt sequence's own guaranteed
3625 /// resume/dispatch actually admits the task, it is unaffected by also
3626 /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3627 /// never on the urgent flag.
3628 #[test]
3629 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3630 let state = Interrupt::Resuming {
3631 parked: vec!["hot".to_owned()],
3632 };
3633 let candidates = vec![urgent_task("hot"), task()];
3634 let allowed = interrupt_gate(&state, &[], candidates);
3635 assert_eq!(
3636 allowed.iter().filter(|t| t.id == "hot").count(),
3637 1,
3638 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3639 );
3640 }
3641
3642 #[test]
3643 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3644 let state = Interrupt::Parking {
3645 parked: vec!["running".to_owned()],
3646 interrupt_task: "marked".to_owned(),
3647 };
3648 let other = task();
3649 let candidates = vec![interrupt_task("marked"), other.clone()];
3650 let allowed = interrupt_gate(&state, &[], candidates);
3651 assert_eq!(allowed.len(), 1);
3652 assert_eq!(allowed[0].id, "marked");
3653 }
3654
3655 #[test]
3656 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
3657 let state = Interrupt::Running {
3658 parked: vec!["running".to_owned()],
3659 interrupt_task: "marked".to_owned(),
3660 };
3661 let candidates = vec![task(), task()];
3662 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
3663 assert!(allowed.is_empty());
3664 }
3665
3666 /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
3667 /// sequence began (only reachable above the default
3668 /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
3669 /// never both in the same tick, which is what "exactly one resume, no
3670 /// simultaneous run" actually requires structurally rather than by
3671 /// coincidence of how many ordinary slots happen to be free.
3672 #[test]
3673 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
3674 let state = Interrupt::Resuming {
3675 parked: vec!["a".to_owned(), "c".to_owned()],
3676 };
3677 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
3678 let allowed = interrupt_gate(&state, &[], candidates);
3679 assert_eq!(
3680 allowed.len(),
3681 1,
3682 "at most one candidate may be offered while resuming: {allowed:?}"
3683 );
3684 assert_eq!(allowed[0].id, "a");
3685 }
3686
3687 #[test]
3688 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
3689 let state = Interrupt::Resuming {
3690 parked: vec!["a".to_owned()],
3691 };
3692 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
3693 assert!(allowed.is_empty());
3694 }
3695
3696 /// The invariant the completion criteria ask for by name: across a whole
3697 /// simulated sequence, there is never a tick where the gate would let
3698 /// through both the parked run's resume and the interrupt task, and
3699 /// exactly one candidate resumes the instant the interrupt task's run
3700 /// ends - never zero, never more than one.
3701 #[test]
3702 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
3703 let running = task(); // id: whatever `Task::new` minted
3704 let marked = interrupt_task("marked");
3705
3706 let mut state = Interrupt::Idle;
3707 // Tick 1: `running` is in flight, `marked` becomes runnable.
3708 let in_flight = vec![running.id.clone()];
3709 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
3710 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
3711 assert!(gated.is_empty(), "still waiting on `running` to park");
3712
3713 // Tick 2: `running` parked and left flight; nothing dispatched yet.
3714 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
3715 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
3716 assert_eq!(
3717 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3718 vec!["marked"],
3719 "only the interrupt task may be offered to the dispatcher now"
3720 );
3721
3722 // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
3723 state = advance_interrupt_tick(
3724 true,
3725 state,
3726 &["marked".to_owned()],
3727 std::slice::from_ref(&running),
3728 );
3729 let gated = interrupt_gate(
3730 &state,
3731 &["marked".to_owned()],
3732 vec![marked.clone(), running.clone()],
3733 );
3734 assert!(
3735 gated.is_empty(),
3736 "the parked run must not be offered back while the interrupt \
3737 task is still running"
3738 );
3739
3740 // Tick 4: `marked`'s run reached a terminal status and left flight.
3741 // A higher-priority ordinary task `other` is also runnable now - it
3742 // must not be let through instead of, or alongside, `running`.
3743 let other = task_with_id("other");
3744 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
3745 assert_eq!(
3746 state,
3747 Interrupt::Resuming {
3748 parked: vec![running.id.clone()]
3749 }
3750 );
3751 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
3752 assert_eq!(
3753 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3754 vec![running.id.as_str()],
3755 "exactly the parked run resumes - not the unrelated task, even \
3756 though it was offered first"
3757 );
3758
3759 // Tick 5: `running` is now in flight (dispatched from tick 4's
3760 // gate). Only now does the sequence end and ordinary dispatch fully
3761 // resume.
3762 state = advance_interrupt_tick(
3763 true,
3764 state,
3765 std::slice::from_ref(&running.id),
3766 std::slice::from_ref(&other),
3767 );
3768 assert_eq!(state, Interrupt::Idle);
3769 let gated = interrupt_gate(
3770 &state,
3771 std::slice::from_ref(&running.id),
3772 vec![other.clone()],
3773 );
3774 assert_eq!(
3775 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3776 vec![other.id.as_str()],
3777 "ordinary dispatch is unrestricted again"
3778 );
3779 }
3780
3781 #[test]
3782 fn every_run_status_settles_the_task_it_came_from() {
3783 // run status, resulting task status, attempts still standing after one
3784 let table = [
3785 (RunStatus::Merged, TaskStatus::Done, 1),
3786 (RunStatus::Ready, TaskStatus::Done, 1),
3787 (RunStatus::Stalled, TaskStatus::Failed, 0),
3788 (RunStatus::Blocked, TaskStatus::Failed, 1),
3789 (RunStatus::Failed, TaskStatus::Failed, 1),
3790 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
3791 (RunStatus::Prep, TaskStatus::Failed, 1),
3792 (RunStatus::Implementing, TaskStatus::Failed, 1),
3793 (RunStatus::Judging, TaskStatus::Failed, 1),
3794 (RunStatus::Deliberating, TaskStatus::Failed, 1),
3795 (RunStatus::Voting, TaskStatus::Failed, 1),
3796 (RunStatus::Reviewing, TaskStatus::Failed, 1),
3797 (RunStatus::Gating, TaskStatus::Failed, 1),
3798 ];
3799 for (run, want, attempts) in table {
3800 let mut t = task();
3801 t.start("20260902-000000-aaaa".to_owned());
3802 settle(
3803 &mut t,
3804 Verdict {
3805 status: run,
3806 left_pr: false,
3807 parked: false,
3808 quota_hit: matches!(run, RunStatus::Stalled),
3809 no_viable_candidates: false,
3810 },
3811 "why",
3812 2,
3813 );
3814 assert_eq!(t.status, want, "task status after {}", label(run));
3815 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
3816 }
3817 }
3818
3819 #[test]
3820 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
3821 let mut stalled = task();
3822 stalled.start("20260902-000000-aaaa".to_owned());
3823 settle(
3824 &mut stalled,
3825 Verdict {
3826 status: RunStatus::Stalled,
3827 left_pr: false,
3828 parked: false,
3829 quota_hit: true,
3830 no_viable_candidates: false,
3831 },
3832 "quota",
3833 1,
3834 );
3835 assert_eq!(stalled.attempts, 0);
3836 assert!(
3837 stalled.status.runnable(),
3838 "a machine problem must leave the task in line"
3839 );
3840
3841 let mut blocked = task();
3842 blocked.start("20260902-000000-aaaa".to_owned());
3843 settle(
3844 &mut blocked,
3845 Verdict {
3846 status: RunStatus::Blocked,
3847 left_pr: false,
3848 parked: false,
3849 quota_hit: false,
3850 no_viable_candidates: false,
3851 },
3852 "findings open",
3853 1,
3854 );
3855 assert_eq!(blocked.attempts, 1);
3856 assert_eq!(
3857 blocked.status,
3858 TaskStatus::Held,
3859 "the last attempt hands the task to a human"
3860 );
3861 }
3862
3863 #[test]
3864 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
3865 // Attempts to spare: without the pull request this task would go
3866 // straight back in line and run the whole competition again.
3867 let mut delivered = task();
3868 delivered.start("20260903-080619-01c2".to_owned());
3869 settle(
3870 &mut delivered,
3871 Verdict {
3872 status: RunStatus::Blocked,
3873 left_pr: true,
3874 parked: false,
3875 quota_hit: false,
3876 no_viable_candidates: false,
3877 },
3878 "no check status",
3879 4,
3880 );
3881 assert_eq!(
3882 delivered.status,
3883 TaskStatus::Held,
3884 "a pull request waiting on CI or a person is not a retryable failure"
3885 );
3886 assert!(
3887 !delivered.status.runnable(),
3888 "the loop must not pick this task up again"
3889 );
3890 assert_eq!(
3891 delivered.last_error.as_deref(),
3892 Some("no check status"),
3893 "the operator needs to be told what the gate was waiting for"
3894 );
3895
3896 // The same status without a pull request is a plain failure, and with
3897 // attempts left it is retried.
3898 let mut empty_handed = task();
3899 empty_handed.start("20260903-080619-01c2".to_owned());
3900 settle(
3901 &mut empty_handed,
3902 Verdict {
3903 status: RunStatus::Blocked,
3904 left_pr: false,
3905 parked: false,
3906 quota_hit: false,
3907 no_viable_candidates: false,
3908 },
3909 "findings open",
3910 4,
3911 );
3912 assert_eq!(empty_handed.status, TaskStatus::Failed);
3913 assert!(empty_handed.status.runnable());
3914 }
3915
3916 #[test]
3917 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
3918 // Every candidate agreed, with evidence, that nothing belonged in the
3919 // worktree. That is not a confirmed success to close automatically -
3920 // a human still has to check the claim - and it is not an ordinary
3921 // failure either, so this settles exactly like a pull request nobody
3922 // merged yet: `Held`, same as `Blocked` with a PR.
3923 let mut noop = task();
3924 noop.start("20260912-131304-391f".to_owned());
3925 settle(
3926 &mut noop,
3927 Verdict {
3928 status: RunStatus::VerifiedNoop,
3929 left_pr: false,
3930 parked: false,
3931 quota_hit: false,
3932 no_viable_candidates: true,
3933 },
3934 "candidate A: already fixed by b32cfc4, on main",
3935 4,
3936 );
3937 assert_eq!(
3938 noop.status,
3939 TaskStatus::Held,
3940 "an unverified claim is a request for a human, not a failure"
3941 );
3942 assert!(
3943 !noop.status.runnable(),
3944 "the loop must not requeue this on the same unverified claim"
3945 );
3946 // `Task::release` resets attempts to zero the moment a human looks at
3947 // the evidence and lets it run again, so it does not matter here
3948 // whether the one attempt already spent stays spent - what matters is
3949 // that nothing retries this task unattended in the meantime.
3950 assert_eq!(noop.attempts, 1);
3951 }
3952
3953 #[test]
3954 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
3955 // Parking is the operator asking for the process back - to replace the
3956 // binary, most of all. The run's work is intact on disk, so this is
3957 // not a failed attempt, and charging for it would mean a few upgrades
3958 // could exhaust a budget meant for agents that misbehaved.
3959 let mut parked = task();
3960 parked.start("20260903-183634-2d98".to_owned());
3961 settle(
3962 &mut parked,
3963 Verdict {
3964 status: RunStatus::Implementing,
3965 left_pr: false,
3966 quota_hit: false,
3967 parked: true,
3968 no_viable_candidates: false,
3969 },
3970 "parked after `implementing`",
3971 2,
3972 );
3973 assert_eq!(parked.attempts, 0, "a park is refunded");
3974 assert!(
3975 parked.status.runnable(),
3976 "and the task stays in line so the next loop resumes its run"
3977 );
3978 assert_eq!(
3979 parked.last_error.as_deref(),
3980 Some("parked after `implementing`"),
3981 "the card says where it stopped"
3982 );
3983
3984 // Without the park flag the same non-terminal status is what it always
3985 // was: `execute` returning mid-flight, which is a bug and spends an
3986 // attempt so a task cannot loop on it forever.
3987 let mut broken = task();
3988 broken.start("20260903-183634-2d98".to_owned());
3989 settle(
3990 &mut broken,
3991 Verdict {
3992 status: RunStatus::Implementing,
3993 left_pr: false,
3994 quota_hit: false,
3995 parked: false,
3996 no_viable_candidates: false,
3997 },
3998 "returned mid-flight",
3999 2,
4000 );
4001 assert_eq!(broken.attempts, 1);
4002 }
4003
4004 #[test]
4005 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4006 // Run e633: quorum lost because two judges answered with the wrong
4007 // JSON shape, `quota: []`. Refunding that takes the bound off the
4008 // retry loop, and each retry pays for a fresh hour-long implement
4009 // wave before it can fail the same way.
4010 let mut flaky = task();
4011 flaky.start("20260903-123023-e633".to_owned());
4012 settle(
4013 &mut flaky,
4014 Verdict {
4015 status: RunStatus::Stalled,
4016 left_pr: false,
4017 parked: false,
4018 quota_hit: false,
4019 no_viable_candidates: false,
4020 },
4021 "verdict rests on 1 of 3 judges",
4022 2,
4023 );
4024 assert_eq!(
4025 flaky.attempts, 1,
4026 "flakiness spends an attempt, so `max_attempts` still bounds it"
4027 );
4028 assert!(flaky.status.runnable(), "and it is still worth retrying");
4029
4030 // The same status, lost to a rate limit, is the machine's fault.
4031 let mut limited = task();
4032 limited.start("20260903-123023-e633".to_owned());
4033 settle(
4034 &mut limited,
4035 Verdict {
4036 status: RunStatus::Stalled,
4037 left_pr: false,
4038 parked: false,
4039 quota_hit: true,
4040 no_viable_candidates: false,
4041 },
4042 "judge-2, judge-3 out of quota",
4043 2,
4044 );
4045 assert_eq!(limited.attempts, 0, "a quota window is refunded");
4046 assert!(limited.status.runnable());
4047
4048 // And the bound really binds: a task that keeps stalling on flakiness
4049 // reaches a human instead of running the roster forever.
4050 let mut worn = task();
4051 for _ in 0..2 {
4052 worn.release();
4053 }
4054 worn.start("20260903-123023-e633".to_owned());
4055 worn.attempts = 2;
4056 settle(
4057 &mut worn,
4058 Verdict {
4059 status: RunStatus::Stalled,
4060 left_pr: false,
4061 parked: false,
4062 quota_hit: false,
4063 no_viable_candidates: false,
4064 },
4065 "no quorum again",
4066 2,
4067 );
4068 assert_eq!(worn.status, TaskStatus::Held);
4069 assert!(!worn.status.runnable());
4070 }
4071
4072 #[test]
4073 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4074 // The implement wave loses every seat to the same rate limit and
4075 // `after_implement` bails with nothing viable, which surfaces as
4076 // `Failed` rather than `Stalled`. That is the same machine fact the
4077 // `Stalled`-quota row already refunds, and must be refunded the same
4078 // way, or a quota outage quietly holds every task it touches instead
4079 // of leaving them in line for the reset.
4080 let mut wiped_out = task();
4081 wiped_out.start("20260907-025000-a1b2".to_owned());
4082 settle(
4083 &mut wiped_out,
4084 Verdict {
4085 status: RunStatus::Failed,
4086 left_pr: false,
4087 parked: false,
4088 quota_hit: true,
4089 no_viable_candidates: true,
4090 },
4091 "no candidate produced a change; nothing to judge",
4092 2,
4093 );
4094 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4095 assert!(
4096 wiped_out.status.runnable(),
4097 "a machine problem must leave the task in line"
4098 );
4099
4100 // This is the exemption that must stay narrow: a candidate that did
4101 // produce a change, and then failed for some other reason, still
4102 // spends the attempt even though a seat elsewhere hit its quota.
4103 // Otherwise every ordinary failure that happens to share a run with
4104 // an unrelated rate limit would be refunded for free.
4105 let mut partial_progress = task();
4106 partial_progress.start("20260907-025500-c3d4".to_owned());
4107 settle(
4108 &mut partial_progress,
4109 Verdict {
4110 status: RunStatus::Failed,
4111 left_pr: false,
4112 parked: false,
4113 quota_hit: true,
4114 no_viable_candidates: false,
4115 },
4116 "gate failed on the winning candidate",
4117 2,
4118 );
4119 assert_eq!(
4120 partial_progress.attempts, 1,
4121 "a candidate that actually produced a change spends the attempt \
4122 even though some other seat hit its quota"
4123 );
4124 assert!(partial_progress.status.runnable());
4125 }
4126
4127 #[test]
4128 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4129 // `reclaim` builds its own `Verdict` from a `RunState` it loads off
4130 // disk, and that construction must reach the same conclusion as the
4131 // one `attempt` builds from a live run, or a crash at exactly the
4132 // wrong moment gives a recovered task a different policy than one a
4133 // daemon finished settling itself.
4134 let mut t = task();
4135 t.start("20260907-025000-a1b2".to_owned());
4136 let mut state = run_state(RunStatus::Failed);
4137 state.quota.push(QuotaLoss {
4138 seat: "cand-a".to_owned(),
4139 node: "implement".to_owned(),
4140 at: Timestamp::now(),
4141 reset: None,
4142 });
4143 assert!(
4144 state.viable().is_empty(),
4145 "no candidate was added, so nothing is viable"
4146 );
4147 reclaim(&mut t, Some(state), 2);
4148 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4149 assert!(t.status.runnable());
4150 }
4151
4152 #[test]
4153 fn a_held_task_is_never_offered_to_the_loop() {
4154 let dir = tempfile::tempdir().unwrap();
4155 let queue = Queue::at(dir.path().to_path_buf());
4156 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4157 let mut t = task();
4158 t.id = format!("2026090{n}-000000-000{n}");
4159 t.priority = priority;
4160 queue.put(&mut t).unwrap();
4161 }
4162 let mut held = task();
4163 held.id = "20260909-000000-9999".to_owned();
4164 held.priority = 99;
4165 held.hold_machine(None);
4166 queue.put(&mut held).unwrap();
4167
4168 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4169 assert_eq!(order.len(), 3);
4170 assert!(!order.contains(&held.id));
4171 assert_eq!(
4172 order.first().cloned(),
4173 queue.next_runnable().map(|t| t.id),
4174 "the loop's first candidate is exactly what the queue offers"
4175 );
4176 assert_eq!(
4177 order,
4178 vec![
4179 "20260902-000000-0002".to_owned(),
4180 "20260903-000000-0003".to_owned(),
4181 "20260901-000000-0001".to_owned(),
4182 ],
4183 "priority first, then oldest, so nothing starves"
4184 );
4185 }
4186
4187 #[test]
4188 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4189 let dir = tempfile::tempdir().unwrap();
4190 let queue = Queue::at(dir.path().to_path_buf());
4191 let mut old = task();
4192 old.id = "20260101-000000-old0".to_owned();
4193 queue.put(&mut old).unwrap();
4194 let mut fresh = task();
4195 fresh.id = "20260101-000000-new0".to_owned();
4196 queue.put(&mut fresh).unwrap();
4197
4198 // No parseable pid at all, so age is the only signal there is to
4199 // check - unlike a real `Queue::claim`, which always names a real,
4200 // and therefore alive, pid this test cannot fake as dead.
4201 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4202 std::thread::sleep(Duration::from_millis(60));
4203 let live = queue.claim(&fresh.id).unwrap();
4204
4205 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4206 assert_eq!(swept, vec![old.id.clone()]);
4207 assert!(
4208 queue.claim(&old.id).is_ok(),
4209 "an unparseable lock older than the threshold is swept"
4210 );
4211 assert!(
4212 queue.claim(&fresh.id).is_err(),
4213 "a live pid protects its lock regardless of age"
4214 );
4215 drop(live);
4216 }
4217
4218 #[test]
4219 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4220 // The regression this guards: `sweep` now runs concurrently with
4221 // every attempt this daemon itself has spawned (see
4222 // `InFlightGuard`), not only between them the way a single
4223 // sequential loop once did. A run that legitimately outlives
4224 // `older_than` still has this very process's own live pid sitting in
4225 // its own lock file on every later sweep, and deciding by age alone
4226 // would delete that still-valid claim out from under the attempt
4227 // that holds it - which `reclaim_orphaned_running` would then read
4228 // as abandoned and hand to a second, competing attempt.
4229 let dir = tempfile::tempdir().unwrap();
4230 let queue = Queue::at(dir.path().to_path_buf());
4231 let mut t = task();
4232 t.id = "20260101-000000-live".to_owned();
4233 queue.put(&mut t).unwrap();
4234
4235 let claim = queue.claim(&t.id).unwrap();
4236 std::thread::sleep(Duration::from_millis(60));
4237
4238 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4239 assert!(
4240 swept.is_empty(),
4241 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4242 );
4243 assert!(
4244 queue.claim(&t.id).is_err(),
4245 "the lock still protects its task"
4246 );
4247 drop(claim);
4248 }
4249
4250 /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4251 /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4252 fn injected_dead_pid() -> u32 {
4253 std::process::id().checked_add(1).unwrap_or(1)
4254 }
4255
4256 #[test]
4257 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4258 let dir = tempfile::tempdir().unwrap();
4259 let queue = Queue::at(dir.path().to_path_buf());
4260 let mut t = task();
4261 t.id = "20260101-000000-dead".to_owned();
4262 queue.put(&mut t).unwrap();
4263 let dead_pid = injected_dead_pid();
4264
4265 // Written directly rather than through `Queue::claim`, which would
4266 // stamp this test process's own very much alive pid and defeat the
4267 // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4268 // like moments after it died, not six hours later.
4269 std::fs::write(
4270 dir.path().join(format!("{}.lock", t.id)),
4271 dead_pid.to_string(),
4272 )
4273 .unwrap();
4274
4275 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4276 pid != dead_pid
4277 });
4278 assert_eq!(
4279 swept,
4280 vec![t.id.clone()],
4281 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4282 );
4283 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4284 }
4285
4286 #[test]
4287 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4288 let dir = tempfile::tempdir().unwrap();
4289 let queue = Queue::at(dir.path().to_path_buf());
4290 let mut t = task();
4291 t.id = "20260101-000000-late".to_owned();
4292 queue.put(&mut t).unwrap();
4293 let dead_pid = injected_dead_pid();
4294
4295 // Tick one, standing in for the sweep `poll` already runs at
4296 // startup: nothing to find yet.
4297 assert!(
4298 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4299 "nothing has claimed the task yet"
4300 );
4301
4302 // A second daemon claims the task and dies before it ever writes
4303 // `running`, well after this loop's own startup sweep already ran.
4304 std::fs::write(
4305 dir.path().join(format!("{}.lock", t.id)),
4306 dead_pid.to_string(),
4307 )
4308 .unwrap();
4309
4310 // Tick two, standing in for a poll long into this daemon's uptime:
4311 // the same function, called again, notices what only just appeared -
4312 // proving the sweep is not a one-shot startup check.
4313 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4314 pid != dead_pid
4315 });
4316 assert_eq!(swept, vec![t.id.clone()]);
4317 }
4318
4319 #[test]
4320 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4321 // `reclaim_orphaned_running` looks up the task's last run, which
4322 // touches `run::home()`; the first call anywhere in this binary wins,
4323 // so this is a no-op if another test already pinned one, and either
4324 // way the run id below is never written under it.
4325 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4326 let dir = tempfile::tempdir().unwrap();
4327 let queue = Queue::at(dir.path().to_path_buf());
4328 let mut t = task();
4329 t.id = "20260101-000000-crsh".to_owned();
4330 t.status = TaskStatus::Running;
4331 t.attempts = 1;
4332 // No `run.json` behind this id: standing in for a run this test does
4333 // not need to make readable, since the point is the lock, not the
4334 // recovery table `reclaim` already has its own tests for.
4335 t.runs.push("20260904-000000-4043".to_owned());
4336 queue.put(&mut t).unwrap();
4337 let dead_pid = injected_dead_pid();
4338
4339 // The crashed daemon's own claim, naming a pid nothing on the
4340 // machine holds anymore.
4341 std::fs::write(
4342 dir.path().join(format!("{}.lock", t.id)),
4343 dead_pid.to_string(),
4344 )
4345 .unwrap();
4346
4347 // Before the lock is swept the task looks claimed, and
4348 // `reclaim_orphaned_running` must leave it alone - this is exactly
4349 // the bug: a `running` task stranded behind a dead daemon's lock,
4350 // invisible to the claim-as-proof check because the lock outlived
4351 // the process that wrote it.
4352 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4353 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4354
4355 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4356 pid != dead_pid
4357 });
4358 assert_eq!(swept, vec![t.id.clone()]);
4359
4360 let reclaimed = reclaim_orphaned_running(&queue, 2);
4361 assert_eq!(reclaimed, vec![t.id.clone()]);
4362 let after = queue.get(&t.id).unwrap();
4363 assert_eq!(
4364 after.status,
4365 TaskStatus::Held,
4366 "no run.json to recover from, so a human is asked"
4367 );
4368 assert_eq!(
4369 after.runs,
4370 vec!["20260904-000000-4043".to_owned()],
4371 "the crashed run's id is kept as evidence, not discarded"
4372 );
4373 }
4374
4375 #[test]
4376 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4377 let dir = tempfile::tempdir().unwrap();
4378 let queue = Queue::at(dir.path().to_path_buf());
4379 let mut t = task();
4380 t.id = "20260101-000000-unknown".to_owned();
4381 queue.put(&mut t).unwrap();
4382 let dead_pid = injected_dead_pid();
4383 std::fs::write(
4384 dir.path().join(format!("{}.lock", t.id)),
4385 dead_pid.to_string(),
4386 )
4387 .unwrap();
4388
4389 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4390 assert!(swept.is_empty(), "an unknown pid must keep its lock");
4391 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4392 }
4393
4394 fn run_state(status: RunStatus) -> RunState {
4395 let mut state = RunState::new(
4396 PathBuf::from("/repo"),
4397 "main".to_owned(),
4398 "abc1234def".to_owned(),
4399 "add retries".to_owned(),
4400 Config::default(),
4401 );
4402 state.status = status;
4403 state
4404 }
4405
4406 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4407 Candidate {
4408 index: 0,
4409 label,
4410 agent: "claude".to_owned(),
4411 branch: format!("magi/x/{label}"),
4412 worktree: PathBuf::from("/repo"),
4413 summary: summary.to_owned(),
4414 stat: String::new(),
4415 files: 0,
4416 commits: usize::from(!empty),
4417 empty,
4418 failed: failed.map(str::to_owned),
4419 verified_noop: None,
4420 duration_ms: 0,
4421 folded: false,
4422 }
4423 }
4424
4425 #[test]
4426 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4427 let mut state = run_state(RunStatus::Blocked);
4428 state.gate = vec![
4429 CommandOutcome {
4430 command: "cargo make check".to_owned(),
4431 code: Some(0),
4432 output_tail: "ok".to_owned(),
4433 duration_ms: 0,
4434 resource_blocked: false,
4435 },
4436 CommandOutcome {
4437 command: "cargo test".to_owned(),
4438 code: Some(101),
4439 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4440 duration_ms: 0,
4441 resource_blocked: false,
4442 },
4443 ];
4444 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4445 assert!(d.contains("cargo test"), "{d}");
4446 assert!(
4447 !d.contains("cargo make check"),
4448 "a passing check is not a diagnostic: {d}"
4449 );
4450 assert!(d.contains("assertion failed"), "{d}");
4451 }
4452
4453 #[test]
4454 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4455 let mut state = run_state(RunStatus::Blocked);
4456 state.event(
4457 "land",
4458 "stopped: the fixer produced no commit while 2 check(s) were failing \
4459 (build, lint); stopping instead of looping on an unchanged tree",
4460 );
4461 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4462 assert!(d.contains("build"), "{d}");
4463 assert!(d.contains("lint"), "{d}");
4464 assert!(d.contains("fixer produced no commit"), "{d}");
4465 }
4466
4467 #[test]
4468 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4469 // `describe`'s output becomes `Task::last_error` verbatim, and the
4470 // phone renders that in the same alarm-styled box an ordinary
4471 // failure gets. A bare `verified_noop` there would read exactly like
4472 // the failure this status exists to be told apart from.
4473 let state = run_state(RunStatus::VerifiedNoop);
4474 let d = describe(&state);
4475 assert!(
4476 d.contains("agent-verified no-op"),
4477 "expected the display label, not the wire spelling: {d}"
4478 );
4479 assert!(!d.contains("verified_noop"), "{d}");
4480 }
4481
4482 #[test]
4483 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4484 // The whole point of the feature: a run held as "no candidate produced
4485 // a change" can mean the implementer actually finished the task and
4486 // only left a clean local tree behind - see AGENTS.md on this exact
4487 // failure mode. The diagnostic has to carry what the agent actually
4488 // said, not just the fact that nothing was there to judge.
4489 let mut state = run_state(RunStatus::Failed);
4490 state.candidates = vec![candidate(
4491 'A',
4492 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4493 true,
4494 None,
4495 )];
4496 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4497 assert!(d.contains("candidate A"), "{d}");
4498 assert!(d.contains("tagged v1.2.3"), "{d}");
4499 }
4500
4501 #[test]
4502 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4503 let mut state = run_state(RunStatus::Failed);
4504 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4505 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4506 assert!(d.contains("candidate A"), "{d}");
4507 assert!(d.contains("agent timed out"), "{d}");
4508 }
4509
4510 #[test]
4511 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4512 // A viable candidate existed, the gate never ran, and nothing land
4513 // said matches - `Task::last_error` is left to explain this one alone.
4514 let mut state = run_state(RunStatus::Failed);
4515 state.candidates = vec![candidate('A', "did the work", false, None)];
4516 assert!(diagnostic(&state).is_none());
4517 }
4518
4519 #[test]
4520 fn diagnostic_is_bounded_however_much_a_run_printed() {
4521 let mut state = run_state(RunStatus::Blocked);
4522 state.gate = vec![
4523 CommandOutcome {
4524 command: "cargo test".to_owned(),
4525 code: Some(101),
4526 output_tail: "x".repeat(50_000),
4527 duration_ms: 0,
4528 resource_blocked: false,
4529 },
4530 CommandOutcome {
4531 command: "cargo clippy".to_owned(),
4532 code: Some(1),
4533 output_tail: "y".repeat(50_000),
4534 duration_ms: 0,
4535 resource_blocked: false,
4536 },
4537 ];
4538 state.candidates = vec![
4539 candidate('A', &"z".repeat(50_000), true, None),
4540 candidate('B', &"w".repeat(50_000), true, None),
4541 ];
4542 let d = diagnostic(&state).expect("plenty here to diagnose");
4543 assert!(
4544 d.len() <= DIAGNOSTIC_MAX,
4545 "diagnostic grew to {} bytes, unbounded",
4546 d.len()
4547 );
4548 }
4549
4550 #[test]
4551 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4552 let mut state = run_state(RunStatus::Blocked);
4553 state.gate = vec![CommandOutcome {
4554 command: "cargo test".to_owned(),
4555 code: Some(101),
4556 output_tail: "assertion failed".to_owned(),
4557 duration_ms: 0,
4558 resource_blocked: false,
4559 }];
4560 let verdict = Verdict {
4561 status: RunStatus::Blocked,
4562 left_pr: false,
4563 quota_hit: false,
4564 parked: false,
4565 no_viable_candidates: false,
4566 };
4567
4568 // Attempt one of two still has a retry coming: no diagnostic yet, the
4569 // task is going to run again and this run's evidence would go stale.
4570 let mut t = task();
4571 t.start("run-1".to_owned());
4572 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4573 assert_eq!(t.status, TaskStatus::Failed);
4574 assert!(t.diagnostic.is_none());
4575
4576 // Attempt two exhausts the budget: now it is held, and the
4577 // diagnostic is what `magi task show` has to say more than one line.
4578 t.start("run-2".to_owned());
4579 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4580 assert_eq!(t.status, TaskStatus::Held);
4581 let d = t.diagnostic.expect("a held task must carry its diagnostic");
4582 assert!(d.contains("cargo test"), "{d}");
4583 }
4584
4585 #[test]
4586 fn a_held_task_names_the_open_question_it_is_waiting_on() {
4587 // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
4588 // `magi ask` question settled Held with `hold_reason: null`, so the
4589 // notification said nothing actionable. `note_open_question` should
4590 // append the question id to whatever `handed_off` already wrote.
4591 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4592 let home = crate::run::home();
4593 let state = run_state(RunStatus::VerifiedNoop);
4594 let mut q = ask::Question::new(
4595 state.id.clone(),
4596 "implement".to_owned(),
4597 "impl-A".to_owned(),
4598 "is this really a no-op?".to_owned(),
4599 String::new(),
4600 Vec::new(),
4601 );
4602 Questions::at(home.join("questions")).put(&mut q).unwrap();
4603
4604 let verdict = Verdict {
4605 status: RunStatus::VerifiedNoop,
4606 left_pr: false,
4607 quota_hit: false,
4608 parked: false,
4609 no_viable_candidates: false,
4610 };
4611 let mut t = task();
4612 t.start(state.id.clone());
4613 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4614
4615 assert_eq!(t.status, TaskStatus::Held);
4616 let reason = t.hold_reason.expect("a held task must record why");
4617 assert!(
4618 reason.starts_with("run ended agent-verified no-op"),
4619 "the original settle reason must survive unchanged: {reason}"
4620 );
4621 assert!(
4622 reason.contains(q.short()),
4623 "the open question's id must be named so the notice is actionable: {reason}"
4624 );
4625 }
4626
4627 #[test]
4628 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
4629 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4630 let state = run_state(RunStatus::VerifiedNoop);
4631
4632 let verdict = Verdict {
4633 status: RunStatus::VerifiedNoop,
4634 left_pr: false,
4635 quota_hit: false,
4636 parked: false,
4637 no_viable_candidates: false,
4638 };
4639 let mut t = task();
4640 t.start(state.id.clone());
4641 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4642
4643 assert_eq!(t.status, TaskStatus::Held);
4644 assert_eq!(
4645 t.hold_reason.as_deref(),
4646 Some("run ended agent-verified no-op"),
4647 "nothing to append when the question was already answered or never asked"
4648 );
4649 }
4650
4651 #[test]
4652 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
4653 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4654 let mut first = run_state(RunStatus::Blocked);
4655 first.id = "20260101-000000-sup1".to_owned();
4656 first.save().unwrap();
4657 let mut second = run_state(RunStatus::Merged);
4658 second.id = "20260101-000000-sup2".to_owned();
4659 second.save().unwrap();
4660
4661 let mut t = task();
4662 t.runs = vec![first.id.clone(), second.id.clone()];
4663 t.status = TaskStatus::Done;
4664
4665 supersede_prior_runs(&t, &crate::run::home());
4666
4667 assert_eq!(
4668 RunState::load(&first.id).unwrap().status,
4669 RunStatus::Superseded,
4670 "the first attempt's Blocked no longer needs anyone's attention"
4671 );
4672 assert_eq!(
4673 RunState::load(&second.id).unwrap().status,
4674 RunStatus::Merged,
4675 "the run that actually succeeded is left exactly as it was"
4676 );
4677 }
4678
4679 #[test]
4680 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
4681 // `is_working_on` alone only proves a *daemon* claim; a `magi run
4682 // --resume` invoked by hand outside the daemon never touches
4683 // `daemon.json` at all, so it would look identical to a genuinely
4684 // idle run without also consulting `RunState::liveness`, which reads
4685 // this run's own recorded `driver_pid` instead.
4686 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4687 let mut first = run_state(RunStatus::Blocked);
4688 first.id = "20260101-000000-sup9".to_owned();
4689 // This test process's own pid: guaranteed alive without needing a
4690 // real second process or daemon.
4691 first.driver_pid = Some(std::process::id());
4692 first.driver_started_at = Some(
4693 crate::proc::process_started_at(std::process::id())
4694 .expect("this test process's own start time must be queryable"),
4695 );
4696 first.save().unwrap();
4697 let mut second = run_state(RunStatus::Merged);
4698 second.id = "20260101-000000-supa".to_owned();
4699 second.save().unwrap();
4700
4701 let mut t = task();
4702 t.runs = vec![first.id.clone(), second.id.clone()];
4703 t.status = TaskStatus::Done;
4704
4705 supersede_prior_runs(&t, &crate::run::home());
4706
4707 assert_eq!(
4708 RunState::load(&first.id).unwrap().status,
4709 RunStatus::Blocked,
4710 "a live driver_pid means something is still actually working this run, \
4711 even though no daemon claims it - rewriting under it would just be \
4712 undone the next time that process saves"
4713 );
4714 }
4715
4716 #[test]
4717 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
4718 // The first resweep must skip a still-live attempt exactly like
4719 // `supersede_prior_runs` itself does; a later resweep, once that
4720 // process is no longer actually driving it, is what closes the gap
4721 // `supersede_prior_runs` alone leaves - a task only ever reaches
4722 // `Done` once, so nothing else would ever look at this run again.
4723 let dir = tempfile::tempdir().unwrap();
4724 let home = dir.path().to_path_buf();
4725 let queue = Queue::at(dir.path().join("queue"));
4726
4727 let mut first = run_state(RunStatus::Blocked);
4728 first.id = "20260101-000000-supd".to_owned();
4729 first.driver_pid = Some(std::process::id());
4730 first.driver_started_at = Some(
4731 crate::proc::process_started_at(std::process::id())
4732 .expect("this test process's own start time must be queryable"),
4733 );
4734 first.save_under(&home).unwrap();
4735 let mut second = run_state(RunStatus::Merged);
4736 second.id = "20260101-000000-supe".to_owned();
4737 second.save_under(&home).unwrap();
4738
4739 let mut t = task();
4740 t.runs = vec![first.id.clone(), second.id.clone()];
4741 t.status = TaskStatus::Done;
4742 queue.put(&mut t).unwrap();
4743
4744 resweep_superseded_attempts(&queue, &home);
4745 assert_eq!(
4746 RunState::load_under(&first.id, &home).unwrap().status,
4747 RunStatus::Blocked,
4748 "still live on the first pass, so still untouched"
4749 );
4750
4751 // Stand in for the manual process no longer being the one driving
4752 // this run: same pid (this test process really is still alive), but
4753 // an identity marker that no longer matches it - see
4754 // `RunState::liveness`'s own doc for why a mismatched
4755 // `driver_started_at` reads as `Dead`, not merely `Unknown`.
4756 let mut stale = RunState::load_under(&first.id, &home).unwrap();
4757 stale.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
4758 stale.save_under(&home).unwrap();
4759
4760 resweep_superseded_attempts(&queue, &home);
4761 assert_eq!(
4762 RunState::load_under(&first.id, &home).unwrap().status,
4763 RunStatus::Superseded,
4764 "the second pass catches up what the first one correctly skipped"
4765 );
4766 }
4767
4768 #[test]
4769 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
4770 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4771 let mut first = run_state(RunStatus::Blocked);
4772 first.id = "20260101-000000-sup3".to_owned();
4773 first.save().unwrap();
4774 let mut second = run_state(RunStatus::Blocked);
4775 second.id = "20260101-000000-sup4".to_owned();
4776 second.save().unwrap();
4777
4778 let mut t = task();
4779 t.runs = vec![first.id.clone(), second.id.clone()];
4780 // Still retrying: nothing about this task's story is settled yet, so
4781 // neither Blocked run may be relabelled, even though a later attempt
4782 // already exists.
4783 t.status = TaskStatus::Failed;
4784
4785 supersede_prior_runs(&t, &crate::run::home());
4786
4787 assert_eq!(
4788 RunState::load(&first.id).unwrap().status,
4789 RunStatus::Blocked
4790 );
4791 assert_eq!(
4792 RunState::load(&second.id).unwrap().status,
4793 RunStatus::Blocked
4794 );
4795 }
4796
4797 #[test]
4798 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
4799 // `magi task done` (or the API's equivalent) can close a task with no
4800 // run of its own ever having succeeded - there is nothing here that
4801 // counts as "the attempt that finished it", so nothing is rewritten.
4802 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4803 let mut first = run_state(RunStatus::Blocked);
4804 first.id = "20260101-000000-sup5".to_owned();
4805 first.save().unwrap();
4806
4807 let mut t = task();
4808 t.runs = vec![first.id.clone()];
4809 t.status = TaskStatus::Done;
4810
4811 supersede_prior_runs(&t, &crate::run::home());
4812
4813 assert_eq!(
4814 RunState::load(&first.id).unwrap().status,
4815 RunStatus::Blocked,
4816 "a single-attempt task has no earlier run to supersede"
4817 );
4818 }
4819
4820 #[test]
4821 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
4822 // `magi task done` (or the web/conductor equivalents) can close a
4823 // task in any status, including one whose *last* recorded attempt is
4824 // itself still `Blocked`/`Failed` - a manual merge magi's own loop
4825 // never watched, say. `runs.last()` being `Done`-adjacent is not
4826 // proof it actually succeeded, so nothing earlier may be relabelled
4827 // on its say-so alone.
4828 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4829 let mut first = run_state(RunStatus::Blocked);
4830 first.id = "20260101-000000-supb".to_owned();
4831 first.save().unwrap();
4832 let mut second = run_state(RunStatus::Failed);
4833 second.id = "20260101-000000-supc".to_owned();
4834 second.save().unwrap();
4835
4836 let mut t = task();
4837 t.runs = vec![first.id.clone(), second.id.clone()];
4838 t.status = TaskStatus::Done;
4839
4840 supersede_prior_runs(&t, &crate::run::home());
4841
4842 assert_eq!(
4843 RunState::load(&first.id).unwrap().status,
4844 RunStatus::Blocked,
4845 "the task's last attempt never landed, so there is nothing here \
4846 actually superseding it"
4847 );
4848 }
4849
4850 #[test]
4851 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
4852 // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
4853 // to look" - `Failed` and `VerifiedNoop` are already their own
4854 // terminal answers and must not be relabelled into a third one.
4855 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4856 let mut failed = run_state(RunStatus::Failed);
4857 failed.id = "20260101-000000-sup6".to_owned();
4858 failed.save().unwrap();
4859 let mut noop = run_state(RunStatus::VerifiedNoop);
4860 noop.id = "20260101-000000-sup7".to_owned();
4861 noop.save().unwrap();
4862 let mut winner = run_state(RunStatus::Ready);
4863 winner.id = "20260101-000000-sup8".to_owned();
4864 winner.save().unwrap();
4865
4866 let mut t = task();
4867 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
4868 t.status = TaskStatus::Done;
4869
4870 supersede_prior_runs(&t, &crate::run::home());
4871
4872 assert_eq!(
4873 RunState::load(&failed.id).unwrap().status,
4874 RunStatus::Failed
4875 );
4876 assert_eq!(
4877 RunState::load(&noop.id).unwrap().status,
4878 RunStatus::VerifiedNoop
4879 );
4880 }
4881
4882 fn approval_question(run: &str) -> ask::Question {
4883 ask::Question::new(
4884 run.to_owned(),
4885 land::APPROVAL_NODE.to_owned(),
4886 "land".to_owned(),
4887 "merge?".to_owned(),
4888 String::new(),
4889 vec!["merge".to_owned(), "hold".to_owned()],
4890 )
4891 }
4892
4893 #[test]
4894 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
4895 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4896 let mut state = run_state(RunStatus::Landing);
4897 state.id = "20260101-000000-fre1".to_owned();
4898 state.parked = true;
4899 state.save().unwrap();
4900 ask::Questions::open()
4901 .put(&mut approval_question(&state.id))
4902 .unwrap();
4903
4904 let mut t = task();
4905 t.runs.push(state.id.clone());
4906 assert_eq!(
4907 land_resume_state(&t),
4908 LandResume::StillWaiting,
4909 "nobody has answered and the timeout has not passed"
4910 );
4911 }
4912
4913 #[test]
4914 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
4915 // `ask::ask_and_wait`'s own deadline used to retire a question
4916 // nobody answered; land's approval bypasses that wait (see
4917 // `land::approval_gate`), so this is now the only place
4918 // `graph.answer_timeout` is enforced for a land approval at all.
4919 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4920 let mut state = run_state(RunStatus::Landing);
4921 state.id = "20260101-000000-exp1".to_owned();
4922 state.parked = true;
4923 state.config.graph.answer_timeout = 60;
4924 state.save().unwrap();
4925
4926 let store = ask::Questions::open();
4927 let mut q = approval_question(&state.id);
4928 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
4929 store.put(&mut q).unwrap();
4930
4931 let mut t = task();
4932 t.runs.push(state.id.clone());
4933 assert_eq!(
4934 land_resume_state(&t),
4935 LandResume::Ready,
4936 "an expired question must not be waited on forever"
4937 );
4938
4939 let after = store.get(&q.id).unwrap();
4940 assert!(
4941 !after.status.open(),
4942 "the question is abandoned, not silently ignored"
4943 );
4944 assert!(
4945 after.resolution().is_none(),
4946 "an abandoned question is not read as a decision"
4947 );
4948 }
4949
4950 #[test]
4951 fn reclaim_settles_a_running_task_against_its_last_run() {
4952 let mut t = task();
4953 t.start("20260904-000000-4043".to_owned());
4954 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
4955 assert_eq!(
4956 t.status,
4957 TaskStatus::Done,
4958 "a run that actually finished must not stay `running` forever"
4959 );
4960 }
4961
4962 #[test]
4963 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
4964 // A blocked run with attempts left goes back to `Failed`, exactly as
4965 // it would from `attempt` itself - `reclaim` must not invent a second
4966 // policy for a task a daemon merely stopped without reporting.
4967 let mut t = task();
4968 t.start("20260904-000000-4043".to_owned());
4969 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
4970 assert_eq!(t.status, TaskStatus::Failed);
4971 assert!(t.status.runnable());
4972 }
4973
4974 #[test]
4975 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
4976 let mut t = task();
4977 t.start("20260904-000000-4043".to_owned());
4978 reclaim(&mut t, None, 2);
4979 assert_eq!(t.status, TaskStatus::Held);
4980 assert!(
4981 t.last_error
4982 .as_deref()
4983 .is_some_and(|e| e.contains("running")),
4984 "the operator needs to know why this task was held"
4985 );
4986 }
4987
4988 #[test]
4989 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
4990 let dir = tempfile::tempdir().unwrap();
4991 let queue = Queue::at(dir.path().to_path_buf());
4992
4993 // No run recorded, so this never has to touch `RunState::load`.
4994 let mut orphaned = task();
4995 orphaned.id = "20260904-000000-orph".to_owned();
4996 orphaned.status = TaskStatus::Running;
4997 orphaned.attempts = 1;
4998 queue.put(&mut orphaned).unwrap();
4999
5000 let mut alive = task();
5001 alive.id = "20260904-000000-live".to_owned();
5002 alive.status = TaskStatus::Running;
5003 alive.attempts = 1;
5004 queue.put(&mut alive).unwrap();
5005 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
5006
5007 let mut queued = task();
5008 queued.id = "20260904-000000-wait".to_owned();
5009 queue.put(&mut queued).unwrap();
5010
5011 let reclaimed = reclaim_orphaned_running(&queue, 2);
5012 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
5013
5014 assert_eq!(
5015 queue.get(&orphaned.id).unwrap().status,
5016 TaskStatus::Held,
5017 "nothing was driving it and there was no run to recover"
5018 );
5019 assert_eq!(
5020 queue.get(&alive.id).unwrap().status,
5021 TaskStatus::Running,
5022 "a live claim must protect the task it belongs to"
5023 );
5024 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
5025 }
5026
5027 /// Read a run.json back from an explicit `home`, the same way
5028 /// `reclaim_abandoned_runs` itself does - never through the
5029 /// process-global `RunState::load`, which this test's own `home` (an
5030 /// isolated tempdir, never pinned into the shared `OnceLock`) does not
5031 /// use at all.
5032 fn read_run_under(home: &Path, id: &str) -> RunState {
5033 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
5034 serde_json::from_str(&body).unwrap()
5035 }
5036
5037 #[test]
5038 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
5039 let dir = tempfile::tempdir().unwrap();
5040 let home = dir.path().to_path_buf();
5041 let now = Timestamp::now();
5042 let overrun_seat = || crate::run::ActiveSeat {
5043 node: "implement".to_owned(),
5044 started_at: now - jiff::SignedDuration::new(21_000, 0),
5045 timeout_secs: 3_600,
5046 attempt: 0,
5047 task: None,
5048 command: None,
5049 index: None,
5050 total: None,
5051 };
5052
5053 let mut dead = run_state(RunStatus::Implementing);
5054 dead.id = "20260101-000000-dead".to_owned();
5055 dead.active.insert("impl-A".to_owned(), overrun_seat());
5056 // A `driver_pid` the injected query below confirms gone outright —
5057 // `liveness` reads this as `Dead`, not merely "no daemon claims it".
5058 dead.driver_pid = Some(4242);
5059 dead.save_under(&home).unwrap();
5060
5061 // Same shape, but a live daemon's heartbeat names it: must be left
5062 // exactly alone, however far past its own timeout the seat sits.
5063 let mut alive = run_state(RunStatus::Implementing);
5064 alive.id = "20260101-000000-aliv".to_owned();
5065 alive.active.insert("impl-A".to_owned(), overrun_seat());
5066 alive.save_under(&home).unwrap();
5067 let mut status = Status::new();
5068 status.current = vec![Current {
5069 task: "20260101-000000-task".to_owned(),
5070 run: alive.id.clone(),
5071 }];
5072 write_status_to(&home.join("daemon.json"), &status).unwrap();
5073
5074 // The abandoned seat left an open question behind: nobody is left to
5075 // read an answer once the run is failed, and this must not wait for
5076 // some later daemon startup's own sweep to notice that.
5077 let questions = Questions::at(home.join("questions"));
5078 let mut q = ask::Question::new(
5079 dead.id.clone(),
5080 "implement".to_owned(),
5081 "impl-A".to_owned(),
5082 "Which storage backend?".to_owned(),
5083 String::new(),
5084 vec!["SQLite".to_owned(), "Redis".to_owned()],
5085 );
5086 questions.put(&mut q).unwrap();
5087
5088 let abandoned = reclaim_abandoned_runs_with(
5089 &home,
5090 now,
5091 |pid| if pid == 4242 { Some(false) } else { None },
5092 |_| panic!("a query answering Dead outright needs no identity corroboration"),
5093 );
5094 assert_eq!(abandoned, vec![dead.id.clone()]);
5095
5096 let reloaded = read_run_under(&home, &dead.id);
5097 assert_eq!(reloaded.status, RunStatus::Failed);
5098 assert!(reloaded.active.is_empty());
5099 assert!(
5100 !questions.get(&q.id).unwrap().status.open(),
5101 "the failed run's own open question must be settled in the same pass"
5102 );
5103
5104 let still_alive = read_run_under(&home, &alive.id);
5105 assert_eq!(
5106 still_alive.status,
5107 RunStatus::Implementing,
5108 "a live daemon's claim protects it"
5109 );
5110 assert!(!still_alive.active.is_empty());
5111 }
5112
5113 /// The exact shape a review round flagged as broken: `magi serve` running
5114 /// in this same `home` scans *every* run on disk, including a manual
5115 /// `magi review` / `magi run` this daemon never started and that
5116 /// therefore claims no heartbeat of its own. Before this scan asked
5117 /// `liveness` rather than just `is_working_on`, a manual run whose active
5118 /// seat merely ran a little past its own timeout — the CLI finishing up,
5119 /// its result still being collected — got wiped and failed by a daemon
5120 /// that had nothing to do with it, out from under a process that was
5121 /// still very much running.
5122 #[test]
5123 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5124 let dir = tempfile::tempdir().unwrap();
5125 let home = dir.path().to_path_buf();
5126 let now = Timestamp::now();
5127
5128 let mut manual = run_state(RunStatus::Reviewing);
5129 manual.id = "20260101-000000-manl".to_owned();
5130 manual.active.insert(
5131 "review-1".to_owned(),
5132 crate::run::ActiveSeat {
5133 node: "review".to_owned(),
5134 started_at: now - jiff::SignedDuration::new(21_000, 0),
5135 timeout_secs: 3_600,
5136 attempt: 0,
5137 task: None,
5138 command: None,
5139 index: None,
5140 total: None,
5141 },
5142 );
5143 // Not claimed by any daemon (no `daemon.json` at all in this `home`),
5144 // but a real, still-running process: `liveness` must corroborate this
5145 // as `Live`, not read the missing daemon claim as death.
5146 manual.driver_pid = Some(4242);
5147 manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
5148 manual.save_under(&home).unwrap();
5149
5150 let abandoned = reclaim_abandoned_runs_with(
5151 &home,
5152 now,
5153 |pid| if pid == 4242 { Some(true) } else { None },
5154 |pid| {
5155 if pid == 4242 {
5156 Some("2026-09-22T10:00:00Z".to_owned())
5157 } else {
5158 None
5159 }
5160 },
5161 );
5162 assert!(
5163 abandoned.is_empty(),
5164 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
5165 );
5166
5167 let reloaded = read_run_under(&home, &manual.id);
5168 assert_eq!(reloaded.status, RunStatus::Reviewing);
5169 assert!(!reloaded.active.is_empty());
5170 }
5171
5172 #[test]
5173 fn an_already_claimed_task_is_skipped_rather_than_failed() {
5174 let dir = tempfile::tempdir().unwrap();
5175 let queue = Queue::at(dir.path().to_path_buf());
5176 let mut only = task();
5177 queue.put(&mut only).unwrap();
5178
5179 let _elsewhere = queue.claim(&only.id).unwrap();
5180 let candidates = runnable(&queue);
5181 assert_eq!(candidates.len(), 1, "the task is still runnable");
5182 assert!(
5183 queue.claim(&candidates[0].id).is_err(),
5184 "the loop cannot take a claim somebody else holds"
5185 );
5186
5187 let after = queue.get(&only.id).unwrap();
5188 assert_eq!(after.status, TaskStatus::Queued);
5189 assert_eq!(
5190 after.attempts, 0,
5191 "losing the race is not an attempt at the task"
5192 );
5193 assert_eq!(after.last_error, None);
5194 }
5195
5196 #[test]
5197 fn the_status_file_round_trips_and_its_heartbeat_advances() {
5198 let dir = tempfile::tempdir().unwrap();
5199 let path = dir.path().join("daemon.json");
5200
5201 let mut status = Status::new();
5202 status.idle = false;
5203 status.completed = 7;
5204 status.current = vec![Current {
5205 task: "20260902-000000-t111".to_owned(),
5206 run: "20260902-000001-r111".to_owned(),
5207 }];
5208 write_status_to(&path, &status).unwrap();
5209 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5210 assert_eq!(first.schema, SCHEMA);
5211 assert_eq!(first.pid, std::process::id());
5212 assert!(!first.idle);
5213 assert_eq!(first.completed, 7);
5214 assert_eq!(first.current, status.current);
5215 assert!(
5216 !path.with_extension("json.tmp").exists(),
5217 "the temp file is renamed, not left behind"
5218 );
5219
5220 std::thread::sleep(Duration::from_millis(5));
5221 status.updated_at = Timestamp::now();
5222 status.polls = 3;
5223 write_status_to(&path, &status).unwrap();
5224 let second: Status =
5225 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5226 assert!(
5227 second.updated_at > first.updated_at,
5228 "a reader can only detect staleness if the heartbeat moves"
5229 );
5230 assert_eq!(
5231 second.started_at, first.started_at,
5232 "the start time is not a heartbeat"
5233 );
5234 assert_eq!(second.polls, 3);
5235 }
5236
5237 #[test]
5238 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
5239 let dir = tempfile::tempdir().unwrap();
5240
5241 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
5242
5243 let mut status = Status::new();
5244 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
5245 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5246 let stale = read_status(dir.path()).unwrap();
5247 assert!(
5248 !stale.running(Timestamp::now()),
5249 "a minute without a heartbeat is a dead daemon, not a busy one"
5250 );
5251 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
5252
5253 status.updated_at = Timestamp::now();
5254 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5255 let fresh = read_status(dir.path()).unwrap();
5256 assert!(fresh.running(Timestamp::now()));
5257 }
5258
5259 #[test]
5260 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
5261 let dir = tempfile::tempdir().unwrap();
5262 let now = Timestamp::now();
5263 let mine = "20260903-080619-01c2";
5264
5265 assert!(
5266 !is_working_on(dir.path(), mine, now),
5267 "no status file means nobody is working on anything"
5268 );
5269
5270 let mut status = Status::new();
5271 status.current = vec![Current {
5272 task: "20260903-080340-0167".to_owned(),
5273 run: mine.to_owned(),
5274 }];
5275 status.updated_at = now;
5276 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5277 assert!(is_working_on(dir.path(), mine, now));
5278 assert!(
5279 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
5280 "a daemon busy with one run is not working on another"
5281 );
5282
5283 // A killed daemon stops writing heartbeats but leaves the file behind
5284 // naming the run it died in. That run must not be undeletable forever.
5285 status.updated_at = now - jiff::SignedDuration::from_secs(600);
5286 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5287 assert!(
5288 !is_working_on(dir.path(), mine, now),
5289 "a stale heartbeat is a dead daemon, so its run is a leftover"
5290 );
5291 }
5292
5293 #[test]
5294 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
5295 let dir = tempfile::tempdir().unwrap();
5296 let now = Timestamp::now();
5297
5298 assert!(
5299 !is_working_on_short(dir.path(), "01c2", now),
5300 "no status file means nobody is working on anything"
5301 );
5302
5303 let mut status = Status::new();
5304 status.current = vec![Current {
5305 task: "20260903-080340-0167".to_owned(),
5306 run: "20260903-080619-01c2".to_owned(),
5307 }];
5308 status.updated_at = now;
5309 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5310 assert!(
5311 is_working_on_short(dir.path(), "01c2", now),
5312 "the run's short id is the last block of its full id"
5313 );
5314 assert!(
5315 !is_working_on_short(dir.path(), "3cbf", now),
5316 "a daemon busy with one worktree bay is not working on another"
5317 );
5318 }
5319
5320 #[test]
5321 fn a_newer_status_file_still_yields_a_reading() {
5322 let dir = tempfile::tempdir().unwrap();
5323 // A field this build has never heard of must not turn the reading into
5324 // nothing at all; that is the whole reason the reader is permissive.
5325 std::fs::write(
5326 dir.path().join("daemon.json"),
5327 serde_json::json!({
5328 "schema": 2,
5329 "updated_at": Timestamp::now().to_string(),
5330 "idle": true,
5331 "surprise": { "nested": [1, 2, 3] },
5332 })
5333 .to_string(),
5334 )
5335 .unwrap();
5336
5337 let reading = read_status(dir.path()).expect("a forward-compatible read");
5338 assert!(reading.running(Timestamp::now()));
5339 assert!(reading.idle);
5340 assert!(reading.current.is_empty());
5341 }
5342
5343 #[test]
5344 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
5345 // A daemon started before `current` became a list keeps writing this
5346 // shape on every heartbeat until it is restarted. A rolling upgrade
5347 // - a newer `magi web` or `magi doctor` reading an older `magi
5348 // serve`'s heartbeat - must still see the run it is on, not "no
5349 // daemon" from a type mismatch failing the whole struct.
5350 let dir = tempfile::tempdir().unwrap();
5351 std::fs::write(
5352 dir.path().join("daemon.json"),
5353 serde_json::json!({
5354 "schema": 1,
5355 "pid": 4242,
5356 "updated_at": Timestamp::now().to_string(),
5357 "idle": false,
5358 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
5359 "completed": 3,
5360 "polls": 9,
5361 })
5362 .to_string(),
5363 )
5364 .unwrap();
5365
5366 let reading = read_status(dir.path()).expect("an older shape must still parse");
5367 assert!(reading.running(Timestamp::now()));
5368 assert_eq!(
5369 reading.current,
5370 vec![Current {
5371 task: "20260902-140501-aaaa".to_owned(),
5372 run: "20260902-140502-bbbb".to_owned(),
5373 }]
5374 );
5375 }
5376
5377 #[test]
5378 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
5379 let dir = tempfile::tempdir().unwrap();
5380 std::fs::write(
5381 dir.path().join("daemon.json"),
5382 serde_json::json!({
5383 "schema": 1,
5384 "updated_at": Timestamp::now().to_string(),
5385 "idle": true,
5386 "current": null,
5387 })
5388 .to_string(),
5389 )
5390 .unwrap();
5391 let with_null = read_status(dir.path()).expect("null must still parse");
5392 assert!(with_null.current.is_empty());
5393
5394 std::fs::write(
5395 dir.path().join("daemon.json"),
5396 serde_json::json!({
5397 "schema": 1,
5398 "updated_at": Timestamp::now().to_string(),
5399 "idle": true,
5400 })
5401 .to_string(),
5402 )
5403 .unwrap();
5404 let absent = read_status(dir.path()).expect("a missing field must still parse");
5405 assert!(absent.current.is_empty());
5406 }
5407
5408 #[test]
5409 fn a_task_without_a_repository_runs_in_the_daemons_default() {
5410 let fallback = Path::new("/default");
5411 let mut blank = task();
5412 blank.repo = PathBuf::new();
5413 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
5414 let mut dot = task();
5415 dot.repo = PathBuf::from(".");
5416 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
5417 assert_eq!(
5418 repo_for(&task(), fallback),
5419 PathBuf::from("/repo"),
5420 "a task that names a repository keeps it"
5421 );
5422 }
5423
5424 #[test]
5425 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
5426 // Three seats said out loud. What `solo` promises is one candidate
5427 // *whatever the config asks for*, so the contrast has to be a number
5428 // this test owns - it used to be `Config::default()`'s, which became
5429 // 1 when one implementation became the default and left the two
5430 // halves of this test asserting the same thing.
5431 let mut solo_cfg = Config::default();
5432 solo_cfg.graph.candidates = 3;
5433 let mut solo_task = task();
5434 solo_task.solo = true;
5435 apply_solo(&mut solo_cfg, &solo_task);
5436 assert_eq!(solo_cfg.graph.candidates, 1);
5437
5438 let mut plain_cfg = Config::default();
5439 plain_cfg.graph.candidates = 3;
5440 let plain_task = task();
5441 assert!(!plain_task.solo);
5442 apply_solo(&mut plain_cfg, &plain_task);
5443 assert_eq!(
5444 plain_cfg.graph.candidates, 3,
5445 "a task that did not ask to run alone keeps the config's candidates"
5446 );
5447 }
5448
5449 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5450 QuotaLoss {
5451 seat: seat.into(),
5452 node: "judge".into(),
5453 at: at.parse().unwrap(),
5454 reset: reset.map(str::to_string),
5455 }
5456 }
5457
5458 #[test]
5459 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5460 let old: Vec<QuotaLoss> = (1..=4)
5461 .map(|i| {
5462 loss(
5463 &format!("judge-{i}"),
5464 "2026-09-23T05:23:00Z",
5465 Some("2:40pm (Asia/Tokyo)"),
5466 )
5467 })
5468 .collect();
5469 let fresh = losses_this_attempt(&old, &old);
5470 assert!(fresh.is_empty());
5471 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5472 // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5473 }
5474
5475 #[test]
5476 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5477 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5478 let now = Timestamp::now();
5479 let mut after = old.clone();
5480 after.push(loss("judge-2", &now.to_string(), None));
5481 let fresh = losses_this_attempt(&old, &after);
5482 assert_eq!(fresh, vec![after[1].clone()]);
5483 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5484 assert_eq!(
5485 until,
5486 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5487 );
5488 }
5489
5490 #[test]
5491 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5492 // `recover_stall` removes judge-1's loss and the retry then hits quota
5493 // again: the vector is the same length, so an index diff sees nothing.
5494 let before = vec![
5495 loss("judge-1", "2026-09-23T05:23:00Z", None),
5496 loss("judge-2", "2026-09-23T05:24:00Z", None),
5497 ];
5498 let after = vec![
5499 loss("judge-2", "2026-09-23T05:24:00Z", None),
5500 loss("judge-1", "2026-09-24T01:00:00Z", None),
5501 ];
5502 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5503 }
5504
5505 #[test]
5506 fn merge_overrides_are_parsed_or_refused() {
5507 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5508 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5509 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5510 assert!(merge_mode("squash").is_err());
5511 }
5512
5513 #[test]
5514 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5515 let now = Timestamp::now();
5516 let fallback = Duration::from_secs(300);
5517 let cap = Duration::from_secs(1800);
5518
5519 // No reset hint at all: the fallback.
5520 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5521
5522 // A reset ten minutes out, well inside the cap: waited for exactly.
5523 let soon = now + jiff::SignedDuration::from_secs(600);
5524 assert_eq!(
5525 quota_wait(Some(soon), now, fallback, cap),
5526 Duration::from_secs(600)
5527 );
5528
5529 // A reset already in the past is not trusted: the fallback, not a
5530 // zero or negative wait that would spin the loop right back around.
5531 let past = now - jiff::SignedDuration::from_secs(60);
5532 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5533
5534 // A reset further out than the cap is trusted for direction but not
5535 // for magnitude: a parsing slip must not sleep the loop for a day.
5536 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5537 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5538 }
5539
5540 #[test]
5541 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5542 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5543
5544 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5545 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5546
5547 // Same clock reading, but it has already gone by today: read as
5548 // tomorrow's, since the CLI would not still be reporting a limit past
5549 // its own stated reset.
5550 let already_past =
5551 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5552 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5553
5554 assert!(
5555 parse_reset_hint("session limit reached", now, now).is_none(),
5556 "free text with no recognised shape is not guessed at"
5557 );
5558 assert!(
5559 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5560 "an unresolvable zone name is not guessed at either"
5561 );
5562 }
5563
5564 #[test]
5565 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5566 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5567
5568 let at = parse_reset_hint(
5569 "You've hit your usage limit. Visit \
5570 https://chatgpt.com/codex/settings/usage to purchase more \
5571 credits or try again at Sep 19th, 2026 5:10 PM.",
5572 now,
5573 now,
5574 )
5575 .expect("the codex reset wording is a recognised shape");
5576 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5577
5578 // The month is explicit, so a date already earlier in the same
5579 // sentence-implied year than `now` is trusted as written rather than
5580 // rolled forward a year the way the bracketed shape rolls a
5581 // same-day clock reading to tomorrow.
5582 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5583 .expect("an explicit year needs no rollover");
5584 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5585
5586 assert!(
5587 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5588 "a two-digit year is not the documented shape and is not guessed at"
5589 );
5590 assert!(
5591 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5592 "a four-letter month name is not the documented three-letter abbreviation"
5593 );
5594 assert!(
5595 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5596 "an explicit zone on the dated shape is a format nobody has \
5597 documented, and is refused rather than guessed at as UTC"
5598 );
5599 }
5600
5601 #[test]
5602 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5603 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5604 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5605
5606 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5607 assert_eq!(at.as_second() - recorded.as_second(), 3769);
5608
5609 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5610 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5611
5612 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5613 assert!(
5614 parse_reset_hint(bad, now, recorded).is_none(),
5615 "{bad:?} must not be guessed at"
5616 );
5617 }
5618 }
5619
5620 /// A loop whose queue lives in a temp tree and whose poll interval is far
5621 /// longer than the test's patience, so anything that waits out a poll
5622 /// instead of noticing the stop fails rather than merely being slow.
5623 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5624 let config = dir.join("magi.toml");
5625 std::fs::write(
5626 &config,
5627 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5628 )
5629 .unwrap();
5630 let opts = Opts {
5631 poll: Duration::from_secs(30),
5632 config: Some(config),
5633 // The explicit fixture config keeps startup cleanup from reading
5634 // machine configuration. This fictional repository likewise
5635 // keeps any best-effort git cleanup away from this checkout.
5636 repo: dir.join("repo"),
5637 ..Opts::default()
5638 };
5639 // The status file goes in a directory that does not exist yet, so its
5640 // creation is itself evidence the loop published one. `worktrees`
5641 // must be just as fictional: the janitor reclaims worktrees under it
5642 // for real, and a test that let it fall through to
5643 // `crate::run::default_worktree_root()` would have it reclaim
5644 // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5645 // which is exactly what happened before this function took the
5646 // parameter at all.
5647 let home = dir.join("home");
5648 let worktrees = dir.join("wt");
5649 (
5650 opts,
5651 Queue::at(dir.join("queue")),
5652 home.join("daemon.json"),
5653 home,
5654 worktrees,
5655 )
5656 }
5657
5658 #[test]
5659 fn a_stop_is_idempotent_and_once_set_stays_set() {
5660 let stop = Stop::new();
5661 assert!(!stop.stopped());
5662
5663 stop.stop();
5664 assert!(stop.stopped());
5665 stop.stop();
5666 assert!(stop.stopped(), "a second stop is not a toggle");
5667
5668 let shared = stop.clone();
5669 assert!(
5670 shared.stopped(),
5671 "a clone is the same stop; that is how the loop and its caller share one"
5672 );
5673 }
5674
5675 #[test]
5676 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
5677 let stop = Stop::new();
5678 stop.enter();
5679 assert!(
5680 !stop.finishing(),
5681 "a busy loop nobody has asked to stop is just running"
5682 );
5683
5684 stop.stop();
5685 assert!(
5686 stop.finishing(),
5687 "a stop asked for mid-run has not landed until the run is settled"
5688 );
5689
5690 stop.exit();
5691 assert!(
5692 !stop.finishing(),
5693 "once the run is settled the stop has landed and there is nothing to finish"
5694 );
5695 }
5696
5697 #[test]
5698 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
5699 let stop = Stop::new();
5700 stop.enter();
5701 stop.enter();
5702 stop.stop();
5703 assert!(stop.finishing(), "two runs still in flight");
5704
5705 stop.exit();
5706 assert!(
5707 stop.finishing(),
5708 "one run finished, but a sibling is still working"
5709 );
5710
5711 stop.exit();
5712 assert!(
5713 !stop.finishing(),
5714 "the last run out is what actually lands the stop"
5715 );
5716 }
5717
5718 #[tokio::test]
5719 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
5720 let dir = tempfile::tempdir().unwrap();
5721 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5722 let stop = Stop::new();
5723 stop.stop();
5724
5725 let began = std::time::Instant::now();
5726 tokio::time::timeout(
5727 Duration::from_secs(2),
5728 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5729 )
5730 .await
5731 .expect("a stopped loop must return, not sit out its poll interval")
5732 .expect("the loop's own setup and teardown must not fail");
5733 assert!(
5734 began.elapsed() < opts.poll,
5735 "returned only after {:?}, which is a poll interval, not a stop",
5736 began.elapsed()
5737 );
5738 }
5739
5740 #[tokio::test]
5741 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
5742 let dir = tempfile::tempdir().unwrap();
5743 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5744 let stop = Stop::new();
5745
5746 // Asked for after the loop is already parked on its empty queue, which
5747 // is the case an operator tapping stop on a phone actually hits.
5748 let asker = {
5749 let stop = stop.clone();
5750 tokio::spawn(async move {
5751 tokio::time::sleep(Duration::from_millis(20)).await;
5752 stop.stop();
5753 })
5754 };
5755
5756 let began = std::time::Instant::now();
5757 tokio::time::timeout(
5758 Duration::from_secs(2),
5759 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5760 )
5761 .await
5762 .expect("a stop asked for while idle must wake the wait")
5763 .expect("the loop's own setup and teardown must not fail");
5764 asker.await.unwrap();
5765 assert!(
5766 began.elapsed() < opts.poll,
5767 "returned only after {:?}, so the stop waited on the sleep",
5768 began.elapsed()
5769 );
5770 }
5771
5772 #[tokio::test]
5773 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
5774 let dir = tempfile::tempdir().unwrap();
5775 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5776 let stop = Stop::new();
5777 stop.stop();
5778
5779 tokio::time::timeout(
5780 Duration::from_secs(2),
5781 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5782 )
5783 .await
5784 .expect("a stopped loop must return")
5785 .expect("the loop's own setup and teardown must not fail");
5786
5787 assert!(
5788 home.is_dir(),
5789 "the loop did publish a status file, so its removal is the teardown and not an absence"
5790 );
5791 assert!(
5792 !status_file.exists(),
5793 "a stopped loop clears its status file"
5794 );
5795 assert!(
5796 read_status(&home).is_none(),
5797 "a reader must see no daemon at all, not a heartbeat that merely stopped"
5798 );
5799 }
5800
5801 #[tokio::test]
5802 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
5803 let dir = tempfile::tempdir().unwrap();
5804 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5805 opts.once = true;
5806
5807 let mut settled = RunState::new(
5808 dir.path().join("repo"),
5809 "main".to_owned(),
5810 "abc1234".to_owned(),
5811 "fixture".to_owned(),
5812 Config::default(),
5813 );
5814 settled.status = RunStatus::Ready;
5815 let run_dir = home.join("runs").join(&settled.id);
5816 std::fs::create_dir_all(&run_dir).unwrap();
5817 std::fs::write(
5818 run_dir.join("run.json"),
5819 serde_json::to_string_pretty(&settled).unwrap(),
5820 )
5821 .unwrap();
5822 let questions = Questions::at(home.join("questions"));
5823 let mut question = ask::Question::new(
5824 settled.id.clone(),
5825 "review".to_owned(),
5826 "reviewer-1".to_owned(),
5827 "Continue?".to_owned(),
5828 String::new(),
5829 Vec::new(),
5830 );
5831 questions.put(&mut question).unwrap();
5832
5833 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
5834 .await
5835 .unwrap();
5836
5837 assert_eq!(
5838 questions.get(&question.id).unwrap().status,
5839 ask::QuestionStatus::Abandoned,
5840 "an empty --once drain still performs startup question cleanup"
5841 );
5842 }
5843
5844 #[test]
5845 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
5846 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5847
5848 assert!(
5849 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
5850 "never checked before: due at once"
5851 );
5852
5853 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
5854 assert!(
5855 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
5856 "well inside the interval: not due yet"
5857 );
5858
5859 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
5860 assert!(
5861 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
5862 "exactly at the edge: not yet due, same convention as `clean::due`"
5863 );
5864
5865 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5866 assert!(
5867 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
5868 "past the interval: due again"
5869 );
5870 }
5871
5872 /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
5873 /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
5874 /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
5875 /// and the congestion test below both need, and must not drift apart.
5876 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
5877 let config = dir.join("magi.toml");
5878 // A literal (single-quoted) TOML string, not a basic one: the cache
5879 // path is a Windows path full of backslashes, and a basic string
5880 // would have TOML try to interpret `\U` (from `\Users\...`) as a
5881 // Unicode escape and fail to parse - the same trap `magi.toml`'s own
5882 // `{{ vars.cache }}` rendering documents.
5883 std::fs::write(
5884 &config,
5885 format!(
5886 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
5887 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
5888 cache_dir.display()
5889 ),
5890 )
5891 .unwrap();
5892 Opts {
5893 config: Some(config),
5894 repo: dir.join("repo"),
5895 ..Opts::default()
5896 }
5897 }
5898
5899 #[tokio::test]
5900 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
5901 let dir = tempfile::tempdir().unwrap();
5902 let home = dir.path().join("home");
5903 let cache_dir = dir.path().join("cache");
5904 std::fs::create_dir_all(&cache_dir).unwrap();
5905 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5906 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5907
5908 // Nobody has asked this daemon to stop, which is the ordinary case;
5909 // the skip that a stop buys is asserted by its own test below.
5910 let running = Stop::new();
5911 let mut last_checked = None;
5912 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5913 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
5914 .await;
5915 assert_eq!(
5916 crate::disk::dir_size(&cache_dir),
5917 0,
5918 "over the cap on the first check ever: pruned at once, no idle queue required"
5919 );
5920 assert_eq!(last_checked, Some(t0));
5921
5922 // A fresh oversized file lands, but the next check is not due yet.
5923 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
5924 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
5925 maybe_prune_cache_between_runs(
5926 &opts.repo,
5927 &opts,
5928 &home,
5929 &running,
5930 &mut last_checked,
5931 too_soon,
5932 )
5933 .await;
5934 assert_eq!(
5935 crate::disk::dir_size(&cache_dir),
5936 10,
5937 "too soon since the last check: left alone rather than rescanned every call"
5938 );
5939 assert_eq!(
5940 last_checked,
5941 Some(t0),
5942 "an idle check does not reset the clock"
5943 );
5944
5945 // Once the interval elapses, the same oversized cache is caught again.
5946 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5947 maybe_prune_cache_between_runs(
5948 &opts.repo,
5949 &opts,
5950 &home,
5951 &running,
5952 &mut last_checked,
5953 due_again,
5954 )
5955 .await;
5956 assert_eq!(
5957 crate::disk::dir_size(&cache_dir),
5958 0,
5959 "due again: pruned back under the cap"
5960 );
5961 }
5962
5963 /// A stop must not queue behind housekeeping. The prune below is a
5964 /// synchronous walk of the whole cache with no await point in it, so a
5965 /// loop that entered it could not get back to its own `stopped()` test
5966 /// until the walk finished - and because no run is in flight at this
5967 /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
5968 /// the stop had already landed. The idle branch has always made this same
5969 /// check before reaching `janitor`; the between-runs path makes it too.
5970 #[tokio::test]
5971 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
5972 let dir = tempfile::tempdir().unwrap();
5973 let home = dir.path().join("home");
5974 let cache_dir = dir.path().join("cache");
5975 std::fs::create_dir_all(&cache_dir).unwrap();
5976 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5977 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5978
5979 let stop = Stop::new();
5980 stop.stop();
5981 assert!(
5982 !stop.finishing(),
5983 "no run is in flight at a between-runs boundary, so nothing else \
5984 would tell the operator this stop had not taken effect yet"
5985 );
5986
5987 let mut last_checked = None;
5988 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5989 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
5990 .await;
5991 assert_eq!(
5992 crate::disk::dir_size(&cache_dir),
5993 10,
5994 "over its cap, and due for the first check ever, but a stop outranks \
5995 it: the cap is a standing policy the next start measures again"
5996 );
5997 assert_eq!(
5998 last_checked, None,
5999 "a check that never happened must not claim the interval"
6000 );
6001 }
6002
6003 /// The regression this whole change exists for: gate timeouts on runs
6004 /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
6005 /// GiB against a 10 GiB cap, because the operator's queue never had a
6006 /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
6007 /// `janitor` pass.
6008 ///
6009 /// Reproduced here with a task whose repository is never created:
6010 /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
6011 /// spawning no agent CLI, so the task keeps failing and re-queuing
6012 /// (`Task::fail` with attempts still under the budget leaves it
6013 /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
6014 /// the loop keeps polling - exactly the "queue with no idle moment"
6015 /// this task describes, produced without a real competition.
6016 #[tokio::test]
6017 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
6018 let dir = tempfile::tempdir().unwrap();
6019 let cache_dir = dir.path().join("cache");
6020 std::fs::create_dir_all(&cache_dir).unwrap();
6021 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
6022
6023 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
6024 opts.poll = Duration::from_millis(20);
6025 opts.max_attempts = 1_000;
6026
6027 let queue = Queue::at(dir.path().join("queue"));
6028 let mut t = Task::new(
6029 "x".to_owned(),
6030 "x".to_owned(),
6031 opts.repo.clone(),
6032 Source::Human,
6033 );
6034 queue.put(&mut t).unwrap();
6035
6036 let home = dir.path().join("home");
6037 let worktrees = dir.path().join("wt");
6038 let status_file = home.join("daemon.json");
6039 let stop = Stop::new();
6040 let stopper = {
6041 let stop = stop.clone();
6042 tokio::spawn(async move {
6043 tokio::time::sleep(Duration::from_millis(400)).await;
6044 stop.stop();
6045 })
6046 };
6047
6048 tokio::time::timeout(
6049 Duration::from_secs(10),
6050 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6051 )
6052 .await
6053 .expect("the loop must not hang on a queue that keeps producing failing work")
6054 .expect("the loop's own setup and teardown must not fail");
6055 stopper.await.unwrap();
6056
6057 let after = queue.get(&t.id).unwrap();
6058 assert!(
6059 after.attempts >= 2,
6060 "the harness must actually have retried more than once, or this is not \
6061 exercising a busy queue at all (got {} attempt(s))",
6062 after.attempts
6063 );
6064 assert!(
6065 after.status.runnable(),
6066 "still under its attempt budget: the queue never reached a natural idle \
6067 on its own, only the external stop ended the test"
6068 );
6069
6070 assert_eq!(
6071 crate::disk::dir_size(&cache_dir),
6072 0,
6073 "an oversized cache must not be left to grow unboundedly just because the \
6074 queue kept the loop busy the whole time"
6075 );
6076 }
6077
6078 #[test]
6079 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
6080 let dir = tempfile::tempdir().unwrap();
6081 let queue = Queue::at(dir.path().join("queue"));
6082 let questions = Questions::at(dir.path().join("questions"));
6083 let mut task = task();
6084 queue.put(&mut task).unwrap();
6085
6086 let mut task_question = ask::Question::new(
6087 task.id.clone(),
6088 crate::conduct::NODE.to_owned(),
6089 "conduct".to_owned(),
6090 "Which backend?".to_owned(),
6091 String::new(),
6092 Vec::new(),
6093 );
6094 questions.put(&mut task_question).unwrap();
6095 task.block(vec![task_question.id.clone()], None);
6096 queue.put(&mut task).unwrap();
6097
6098 let mut run_question = ask::Question::new(
6099 "20260101-000000-run1".to_owned(),
6100 "review".to_owned(),
6101 "reviewer-1".to_owned(),
6102 "Run question".to_owned(),
6103 String::new(),
6104 Vec::new(),
6105 );
6106 questions.put(&mut run_question).unwrap();
6107
6108 // A question from another node whose `run` happens to equal this
6109 // task's id — the same field, filled in for an unrelated reason. Only
6110 // `crate::conduct::NODE` questions use `run` as a task id; this one
6111 // must never be touched by this reconciliation, even after release.
6112 let mut coincidental = ask::Question::new(
6113 task.id.clone(),
6114 "review".to_owned(),
6115 "reviewer-1".to_owned(),
6116 "Unrelated review question".to_owned(),
6117 String::new(),
6118 Vec::new(),
6119 );
6120 questions.put(&mut coincidental).unwrap();
6121
6122 reconcile_task_questions(&queue, &questions);
6123 assert!(questions.get(&task_question.id).unwrap().status.open());
6124 assert!(questions.get(&run_question.id).unwrap().status.open());
6125 assert!(questions.get(&coincidental.id).unwrap().status.open());
6126
6127 task.release();
6128 queue.put(&mut task).unwrap();
6129 reconcile_task_questions(&queue, &questions);
6130 assert_eq!(
6131 questions.get(&task_question.id).unwrap().status,
6132 ask::QuestionStatus::Abandoned
6133 );
6134 assert!(
6135 questions.get(&run_question.id).unwrap().status.open(),
6136 "run questions remain the run janitor's responsibility"
6137 );
6138 assert!(
6139 questions.get(&coincidental.id).unwrap().status.open(),
6140 "a non-conductor question must not be abandoned just because its \
6141 run id coincides with a task id"
6142 );
6143 }
6144
6145 #[test]
6146 fn a_freshly_started_running_task_is_never_stalled() {
6147 let dir = tempfile::tempdir().unwrap();
6148 let mut t = task();
6149 t.start("run-1".to_owned());
6150 // `updated_at` is `Timestamp::now()`, left alone: no live daemon
6151 // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
6152 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
6153 }
6154
6155 #[test]
6156 fn a_long_running_task_with_no_live_daemon_is_stalled() {
6157 let dir = tempfile::tempdir().unwrap();
6158 let mut t = task();
6159 t.start("run-1".to_owned());
6160 t.updated_at = Timestamp::now()
6161 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6162 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
6163 assert_eq!(
6164 stalled_tasks(
6165 &Queue::at(dir.path().join("q")),
6166 dir.path(),
6167 Timestamp::now()
6168 )
6169 .len(),
6170 0,
6171 "the task was never written to this queue"
6172 );
6173 }
6174
6175 #[test]
6176 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
6177 let dir = tempfile::tempdir().unwrap();
6178 let mut t = task();
6179 t.id = "20260903-080340-0167".to_owned();
6180 t.start("20260903-080619-01c2".to_owned());
6181 t.updated_at = Timestamp::now()
6182 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6183
6184 let mut status = Status::new();
6185 status.current = vec![Current {
6186 task: t.id.clone(),
6187 run: "20260903-080619-01c2".to_owned(),
6188 }];
6189 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6190
6191 assert!(
6192 !is_stalled(&t, dir.path(), Timestamp::now()),
6193 "a live daemon's own heartbeat rules out stalled, however long the task has run"
6194 );
6195 }
6196
6197 /// Rewrite a task's `updated_at` on disk directly, bypassing
6198 /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
6199 /// a fixture look like it has genuinely been `running` for a while.
6200 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
6201 let path = queue.path_of(id);
6202 let body = std::fs::read_to_string(&path).unwrap();
6203 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
6204 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
6205 v["updated_at"] = serde_json::Value::String(old.to_string());
6206 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
6207 }
6208
6209 #[test]
6210 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
6211 // The realistic `poll()` ordering, not `is_stalled` in isolation:
6212 // `reclaim_orphaned_running` runs first, on every poll, and settles
6213 // any `running` task whose claim it can actually take. For most
6214 // crashes that is immediate - a dead pid is proof enough for
6215 // `sweep_stale_claims` to drop the lock the same tick, and the very
6216 // next claim attempt succeeds. But a lock whose pid cannot be parsed
6217 // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
6218 // `sweep_stale_claims`'s own doc), so the lock - and the claim
6219 // failure behind it - can legitimately outlive many polls. This is
6220 // exactly the gap `stalled_tasks` exists to surface well before that
6221 // six-hour sweep would: reclaim leaves the task `running`, and it
6222 // must still reach the conductor as stalled.
6223 let dir = tempfile::tempdir().unwrap();
6224 let queue = Queue::at(dir.path().join("queue"));
6225 let home = dir.path().join("home");
6226
6227 let mut t = task();
6228 t.id = "20260101-000001-lock".to_owned();
6229 t.start("run-1".to_owned());
6230 queue.put(&mut t).unwrap();
6231 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6232 std::fs::write(
6233 dir.path().join("queue").join(format!("{}.lock", t.id)),
6234 "not a pid",
6235 )
6236 .unwrap();
6237
6238 let now = Timestamp::now();
6239 assert!(
6240 reclaim_orphaned_running(&queue, 2).is_empty(),
6241 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
6242 and reclaim must leave the task alone"
6243 );
6244 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6245
6246 let stalled = stalled_tasks(&queue, &home, now);
6247 assert_eq!(
6248 stalled.len(),
6249 1,
6250 "reclaim's inability to claim it yet must not hide it from the conductor"
6251 );
6252 assert_eq!(stalled[0].id, t.id);
6253 }
6254
6255 #[test]
6256 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
6257 let dir = tempfile::tempdir().unwrap();
6258 crate::run::set_home(dir.path().join("run-home"));
6259 let queue = Queue::at(dir.path().join("queue"));
6260 let home = dir.path().join("home");
6261 let questions = Questions::at(dir.path().join("questions"));
6262
6263 let mut t = task();
6264 t.id = "20260101-000003-dead".to_owned();
6265 t.start("missing-run".to_owned());
6266 queue.put(&mut t).unwrap();
6267 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6268
6269 // This is the real poll ordering: retain the deterministic stalled
6270 // input before a claim proves the owner is gone and reclaims it.
6271 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6272 assert_eq!(
6273 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
6274 [&t.id]
6275 );
6276 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
6277 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
6278
6279 // Reclaim drops its guard before conductor decisions are applied, so
6280 // the decision for the captured stalled input has a real write path.
6281 crate::conduct::apply(
6282 &queue,
6283 &questions,
6284 &crate::conduct::Verdict {
6285 decisions: vec![crate::conduct::Decision {
6286 id: t.id.clone(),
6287 recovery: Some(crate::conduct::Recovery::Requeue),
6288 ..crate::conduct::Decision::default()
6289 }],
6290 },
6291 )
6292 .unwrap();
6293 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
6294 }
6295
6296 #[test]
6297 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
6298 let dir = tempfile::tempdir().unwrap();
6299 let queue = Queue::at(dir.path().join("queue"));
6300 let home = dir.path().join("home");
6301
6302 let mut fresh = task();
6303 fresh.id = "20260101-000001-aaaa".to_owned();
6304 fresh.start("run-1".to_owned());
6305 queue.put(&mut fresh).unwrap();
6306
6307 let mut old = task();
6308 old.id = "20260101-000002-bbbb".to_owned();
6309 old.start("run-2".to_owned());
6310 queue.put(&mut old).unwrap();
6311 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
6312
6313 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6314 assert_eq!(stalled.len(), 1);
6315 assert_eq!(stalled[0].id, old.id);
6316 }
6317
6318 #[test]
6319 fn queued_and_finished_task_views_partition_by_status() {
6320 let dir = tempfile::tempdir().unwrap();
6321 let queue = Queue::at(dir.path().join("queue"));
6322
6323 let mut queued = task();
6324 queued.id = "20260101-000001-aaaa".to_owned();
6325 queue.put(&mut queued).unwrap();
6326
6327 let mut failed = task();
6328 failed.id = "20260101-000002-bbbb".to_owned();
6329 failed.start("run-1".to_owned());
6330 failed.fail("gate red", 5);
6331 queue.put(&mut failed).unwrap();
6332
6333 let mut held = task();
6334 held.id = "20260101-000003-cccc".to_owned();
6335 held.hold_machine(None);
6336 queue.put(&mut held).unwrap();
6337
6338 let mut running = task();
6339 running.id = "20260101-000004-dddd".to_owned();
6340 running.start("run-2".to_owned());
6341 queue.put(&mut running).unwrap();
6342
6343 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
6344 assert_eq!(queued_ids, [queued.id.clone()]);
6345
6346 let mut finished_ids: Vec<String> =
6347 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
6348 finished_ids.sort_unstable();
6349 let mut want = vec![failed.id.clone(), held.id.clone()];
6350 want.sort_unstable();
6351 assert_eq!(finished_ids, want);
6352 }
6353
6354 #[test]
6355 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
6356 let dir = tempfile::tempdir().unwrap();
6357 let queue = Queue::at(dir.path().join("queue"));
6358 let questions = ask::Questions::at(dir.path().join("questions"));
6359
6360 let mut dep = task();
6361 dep.id = "20260101-000001-dep0".to_owned();
6362 dep.succeed();
6363 queue.put(&mut dep).unwrap();
6364
6365 let mut still_going = task();
6366 still_going.id = "20260101-000002-dep1".to_owned();
6367 queue.put(&mut still_going).unwrap();
6368
6369 let mut blocked = task();
6370 blocked.id = "20260101-000003-main".to_owned();
6371 blocked.block(
6372 vec![dep.id.clone(), still_going.id.clone()],
6373 Some("waits on both".to_owned()),
6374 );
6375 queue.put(&mut blocked).unwrap();
6376
6377 resolve_blockers(&queue, &questions);
6378
6379 let after = queue.get(&blocked.id).unwrap();
6380 assert_eq!(
6381 after.status,
6382 TaskStatus::Blocked,
6383 "one dependency is still outstanding"
6384 );
6385 assert_eq!(after.blocked_by, [still_going.id.clone()]);
6386 }
6387
6388 #[test]
6389 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
6390 let dir = tempfile::tempdir().unwrap();
6391 let queue = Queue::at(dir.path().join("queue"));
6392 let questions = ask::Questions::at(dir.path().join("questions"));
6393
6394 let mut q = crate::ask::Question::new(
6395 "20260101-000001-main".to_owned(),
6396 crate::conduct::NODE.to_owned(),
6397 "conduct".to_owned(),
6398 "Which backend?".to_owned(),
6399 String::new(),
6400 Vec::new(),
6401 );
6402 questions.put(&mut q).unwrap();
6403 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
6404 .unwrap();
6405 questions.put(&mut q).unwrap();
6406
6407 let mut blocked = task();
6408 blocked.id = "20260101-000001-main".to_owned();
6409 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
6410 queue.put(&mut blocked).unwrap();
6411
6412 resolve_blockers(&queue, &questions);
6413
6414 let after = queue.get(&blocked.id).unwrap();
6415 assert_eq!(
6416 after.status,
6417 TaskStatus::Queued,
6418 "the only blocker resolved"
6419 );
6420 assert_eq!(after.answers.len(), 1);
6421 assert_eq!(after.answers[0].question, "Which backend?");
6422 assert_eq!(after.answers[0].answer, "SQLite");
6423
6424 // And the run this task starts next is told about it.
6425 let instruction = instruction_for(&after);
6426 assert!(instruction.contains("Which backend?"));
6427 assert!(instruction.contains("SQLite"));
6428 }
6429
6430 #[test]
6431 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
6432 // Reproduces the reported bug (task 3958): a task held out of
6433 // attempts, blocked on a `crate::conduct` follow-up question, must
6434 // come back `held` once that question is answered - never `queued`,
6435 // whatever the answer said - or it silently re-enters the
6436 // competition queue with its attempts already exhausted.
6437 let dir = tempfile::tempdir().unwrap();
6438 let queue = Queue::at(dir.path().join("queue"));
6439 let questions = ask::Questions::at(dir.path().join("questions"));
6440
6441 let mut q = crate::ask::Question::new(
6442 "20260101-000001-main".to_owned(),
6443 crate::conduct::NODE.to_owned(),
6444 "conduct".to_owned(),
6445 "How should this be handled?".to_owned(),
6446 String::new(),
6447 Vec::new(),
6448 );
6449 questions.put(&mut q).unwrap();
6450 q.answer(crate::ask::Answer::Text(
6451 "leave it held, a human will look at it later".to_owned(),
6452 ))
6453 .unwrap();
6454 questions.put(&mut q).unwrap();
6455
6456 let mut held = task();
6457 held.id = "20260101-000001-main".to_owned();
6458 held.hold_machine(Some("out of attempts".to_owned()));
6459 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6460 queue.put(&mut held).unwrap();
6461
6462 resolve_blockers(&queue, &questions);
6463
6464 let after = queue.get(&held.id).unwrap();
6465 assert_eq!(after.status, TaskStatus::Held);
6466 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6467 assert_eq!(
6468 after.answers[0].answer,
6469 "leave it held, a human will look at it later"
6470 );
6471 }
6472
6473 #[test]
6474 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6475 // Reproduces the reported bug: a task blocked on a task id that was
6476 // removed (`magi task rm`, or deleted by hand) can never see that id
6477 // reach `Done`, so the ordinary per-id loop has nothing to notice and
6478 // would otherwise leave the task `blocked` forever with no way for an
6479 // operator to find out why.
6480 let dir = tempfile::tempdir().unwrap();
6481 let queue = Queue::at(dir.path().join("queue"));
6482 let questions = ask::Questions::at(dir.path().join("questions"));
6483
6484 let mut still_going = task();
6485 still_going.id = "20260101-000002-dep1".to_owned();
6486 queue.put(&mut still_going).unwrap();
6487
6488 let mut blocked = task();
6489 blocked.id = "20260101-000003-main".to_owned();
6490 blocked.block(
6491 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6492 Some("waits on both".to_owned()),
6493 );
6494 queue.put(&mut blocked).unwrap();
6495
6496 resolve_blockers(&queue, &questions);
6497
6498 let after = queue.get(&blocked.id).unwrap();
6499 assert_eq!(
6500 after.status,
6501 TaskStatus::Held,
6502 "a missing dependency must not leave the task blocked forever"
6503 );
6504 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6505 assert!(after.blocked_by.is_empty());
6506 let reason = after.hold_reason.as_deref().unwrap_or_default();
6507 assert!(
6508 reason.contains("20260101-000001-gone"),
6509 "the missing id must be named so an operator can tell what happened: {reason}"
6510 );
6511 assert!(
6512 reason.contains(&still_going.id),
6513 "the still-valid dependency must not silently vanish from the record: {reason}"
6514 );
6515 }
6516
6517 #[test]
6518 fn instruction_for_is_unchanged_without_any_answers() {
6519 let t = task();
6520 assert_eq!(instruction_for(&t), t.instruction);
6521 }
6522
6523 #[test]
6524 fn resumed_instruction_is_unchanged_without_any_answers() {
6525 let t = task();
6526 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6527 }
6528
6529 #[test]
6530 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6531 let mut t = task();
6532 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6533 // The run's own instruction on disk predates the answer: it is the
6534 // plain original text `Runner::start` saved before the operator was
6535 // ever asked anything.
6536 let old = t.instruction.clone();
6537
6538 let refreshed = resumed_instruction(&old, &t);
6539 assert!(refreshed.starts_with(&old), "the original text is kept");
6540 assert!(refreshed.contains("Which backend?"));
6541 assert!(refreshed.contains("SQLite"));
6542 }
6543
6544 #[test]
6545 fn resumed_instruction_keeps_an_original_answers_heading() {
6546 let mut t = task();
6547 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6548 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6549
6550 let refreshed = resumed_instruction(&t.instruction, &t);
6551
6552 assert!(
6553 refreshed.starts_with(&t.instruction),
6554 "an answers heading in the original instruction is not the appended block"
6555 );
6556 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6557 assert!(refreshed.contains("Which backend?"));
6558 assert!(refreshed.contains("SQLite"));
6559
6560 let repeated = resumed_instruction(&refreshed, &t);
6561 assert_eq!(
6562 repeated, refreshed,
6563 "only the final appended block is refreshed"
6564 );
6565 }
6566
6567 #[test]
6568 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6569 let mut t = task();
6570 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6571
6572 // A first resume appends the block; a second resume of the same run,
6573 // with no new answer in between, must reproduce exactly the same
6574 // text rather than appending the block a second time.
6575 let once = resumed_instruction(&t.instruction, &t);
6576 let twice = resumed_instruction(&once, &t);
6577 assert_eq!(once, twice);
6578 assert_eq!(once.matches("Which backend?").count(), 1);
6579
6580 // A later answer replaces the block wholesale rather than growing it.
6581 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6582 let refreshed = resumed_instruction(&once, &t);
6583 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6584 assert!(refreshed.contains("Which backend?"));
6585 assert!(refreshed.contains("Which cache?"));
6586 }
6587
6588 #[test]
6589 fn prepare_instruction_covers_all_three_starters() {
6590 let mut t = task();
6591 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6592
6593 // Start: a fresh run gets the task text plus every answer so far —
6594 // exactly `instruction_for`.
6595 assert_eq!(
6596 prepare_instruction(&Starter::Start, None, &t),
6597 Some(instruction_for(&t))
6598 );
6599
6600 // Resume: the run's prior instruction is refreshed with the answer,
6601 // not discarded and not left stale.
6602 let old = t.instruction.clone();
6603 assert_eq!(
6604 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6605 Some(resumed_instruction(&old, &t))
6606 );
6607
6608 // Review: a review-only pass builds its own instruction from the
6609 // branch's history in `crate::graph`, with no task statement at all -
6610 // this boundary must leave it alone.
6611 assert_eq!(
6612 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6613 None
6614 );
6615 }
6616
6617 #[test]
6618 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6619 assert_eq!(
6620 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6621 Starter::Review("magi/eba2/A".to_owned())
6622 );
6623 }
6624
6625 #[test]
6626 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6627 assert_eq!(
6628 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6629 Starter::Start,
6630 "a vanished review branch must not fall back to resuming the old run either"
6631 );
6632 }
6633
6634 #[test]
6635 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6636 assert_eq!(
6637 choose_starter(None, false, Some("some-run")),
6638 Starter::Resume("some-run".to_owned())
6639 );
6640 assert_eq!(choose_starter(None, false, None), Starter::Start);
6641 }
6642
6643 #[test]
6644 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
6645 let mut released = task();
6646 released.start("stalled-run".to_owned());
6647 released.requeue();
6648 let unfinished = (!released.fresh_start)
6649 .then(|| Some("stalled-run".to_owned()))
6650 .flatten();
6651 assert_eq!(
6652 choose_starter(None, false, unfinished.as_deref()),
6653 Starter::Start,
6654 "release keeps run history but must not resume it"
6655 );
6656 assert_eq!(released.runs, ["stalled-run"]);
6657 }
6658
6659 #[test]
6660 fn an_ordinary_release_keeps_a_resumable_run_available() {
6661 let mut released = task();
6662 released.start("stalled-run".to_owned());
6663 released.release();
6664 let unfinished = (!released.fresh_start)
6665 .then(|| Some("stalled-run".to_owned()))
6666 .flatten();
6667 assert_eq!(
6668 choose_starter(None, false, unfinished.as_deref()),
6669 Starter::Resume("stalled-run".to_owned()),
6670 "manual release must preserve the normal resume path"
6671 );
6672 }
6673
6674 #[test]
6675 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
6676 let mut state = run_state(RunStatus::Blocked);
6677 state.config.graph.review_rounds = 3;
6678 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
6679 assert!(exhausted_review_budget(&state));
6680
6681 // One round still unused: resuming can still ask a reviewer something.
6682 state.reviews.pop();
6683 assert!(!exhausted_review_budget(&state));
6684
6685 // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
6686 // count: only a `Blocked` run re-enters the review loop on resume.
6687 let mut stalled = run_state(RunStatus::Stalled);
6688 stalled.config.graph.review_rounds = 1;
6689 stalled.reviews = vec![review_round(1)];
6690 assert!(!exhausted_review_budget(&stalled));
6691 }
6692
6693 fn review_round(round: usize) -> crate::run::ReviewRound {
6694 crate::run::ReviewRound {
6695 round,
6696 head: "deadbeef".to_owned(),
6697 verified_head: None,
6698 verified_at: None,
6699 reviews: Vec::new(),
6700 e2e: Vec::new(),
6701 verify_retried: false,
6702 e2e_deferred: false,
6703 e2e_defer_reason: None,
6704 fix: None,
6705 blocking: 0,
6706 answered: 1,
6707 expected: 1,
6708 clean: false,
6709 progressed: true,
6710 vote_split: false,
6711 reconsideration: Vec::new(),
6712 verdict: None,
6713 }
6714 }
6715
6716 #[test]
6717 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
6718 // Mirrors the failure this exists to close: a task's last run ended
6719 // `Blocked` with the review budget spent, `crate::conduct` chose
6720 // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
6721 // evidence), and without this check `attempt` would go on treating
6722 // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
6723 // review loop iterates zero times over an already-spent budget, so
6724 // the resumed run settles right back to `Blocked` having asked nobody
6725 // anything, and `Requeue`'s promised fresh competition never happens.
6726 let mut exhausted = RunState::new(
6727 PathBuf::from("/repo"),
6728 "main".to_owned(),
6729 "abc1234def".to_owned(),
6730 "add retries".to_owned(),
6731 Config::default(),
6732 );
6733 exhausted.status = RunStatus::Blocked;
6734 exhausted.config.graph.review_rounds = 1;
6735 exhausted.reviews = vec![review_round(1)];
6736
6737 assert_eq!(
6738 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
6739 None,
6740 "an exhausted `Blocked` run must not be offered as resumable"
6741 );
6742
6743 // A `Blocked` run with rounds still unused is genuinely worth
6744 // resuming, and must still be found.
6745 let mut has_budget_left = RunState::new(
6746 PathBuf::from("/repo"),
6747 "main".to_owned(),
6748 "abc1234def".to_owned(),
6749 "add retries".to_owned(),
6750 Config::default(),
6751 );
6752 has_budget_left.status = RunStatus::Blocked;
6753 has_budget_left.config.graph.review_rounds = 3;
6754 has_budget_left.reviews = vec![review_round(1)];
6755
6756 assert_eq!(
6757 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
6758 Ok(has_budget_left.clone())
6759 }),
6760 Some(has_budget_left.id.clone())
6761 );
6762 }
6763
6764 #[test]
6765 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
6766 // A task whose history holds an *older* run that still looks
6767 // resumable (say, a competition `Runner::review` was started
6768 // alongside after that older run went `Stalled`) and a *newest* run
6769 // that is `Blocked` with its review budget spent. `Recovery::Requeue`
6770 // on this task must mean a fresh competition — falling back to the
6771 // stale, superseded `Stalled` run instead would resurrect history
6772 // nothing asked to revisit and silently defeat the requeue.
6773 let mut older_stalled = RunState::new(
6774 PathBuf::from("/repo"),
6775 "main".to_owned(),
6776 "abc1234def".to_owned(),
6777 "add retries".to_owned(),
6778 Config::default(),
6779 );
6780 older_stalled.status = RunStatus::Stalled;
6781
6782 let mut newest_exhausted = RunState::new(
6783 PathBuf::from("/repo"),
6784 "main".to_owned(),
6785 "abc1234def".to_owned(),
6786 "add retries".to_owned(),
6787 Config::default(),
6788 );
6789 newest_exhausted.status = RunStatus::Blocked;
6790 newest_exhausted.config.graph.review_rounds = 1;
6791 newest_exhausted.reviews = vec![review_round(1)];
6792
6793 assert_eq!(
6794 unfinished_run_with(
6795 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
6796 "t",
6797 |_| Ok(newest_exhausted.clone())
6798 ),
6799 None,
6800 "the newest run is exhausted, so nothing here is worth resuming - \
6801 least of all the older, already-superseded run"
6802 );
6803 }
6804
6805 #[test]
6806 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
6807 assert_eq!(
6808 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
6809 Err(anyhow::anyhow!("fixture is absent"))
6810 }),
6811 None
6812 );
6813 }
6814}