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