Skip to main content

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
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, which is the state a
26//! human needs to see: the run's own report explains how far it got, and the
27//! task can be released deliberately. The alternative — reverting the task to
28//! `Queued` on the way out — would hide the abandoned run and re-spend its
29//! quota on the next poll.
30//!
31//! # Retries are bounded
32//!
33//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
34//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
35//! exception is a run that ended `Stalled`: the panel collapsed because the
36//! agent CLIs hit their quota, which is a fact about the machine and not about
37//! the task, so it must not spend an attempt. Without that exception a quota
38//! outage would quietly hold the entire backlog, and the operator would come
39//! back to a reset quota and nothing left that the loop is willing to run.
40
41use std::path::{Path, PathBuf};
42use std::sync::Arc;
43use std::sync::atomic::{AtomicBool, Ordering};
44use std::sync::{Mutex, MutexGuard};
45use std::time::Duration;
46
47use anyhow::{Context, Result, bail};
48use jiff::Timestamp;
49use serde::{Deserialize, Serialize};
50use tokio::sync::Notify;
51
52use crate::config::{Config, MergeMode};
53use crate::graph::Runner;
54use crate::queue::{Queue, Task};
55use crate::run::{RunState, RunStatus};
56
57/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
58pub const SCHEMA: u32 = 1;
59
60/// How often the status file is refreshed. A reader treats a status file older
61/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
62/// that a busy daemon is never mistaken for a dead one.
63pub const HEARTBEAT: Duration = Duration::from_secs(5);
64
65/// How old a heartbeat may be before a reader calls the daemon dead. Six
66/// missed beats: long enough to survive a slow filesystem, short enough that
67/// a crashed daemon is not still reported as running a task.
68///
69/// The single threshold every reader shares — the web UI's `/api/health` and
70/// `magi doctor` both call [`Reading::running`] rather than each comparing
71/// against their own copy of this number, so a crashed daemon cannot look
72/// alive on one screen and dead on another.
73pub const STALE_SECS: i64 = 30;
74
75/// Default queue poll interval.
76pub const POLL: Duration = Duration::from_secs(5);
77
78/// How old a claim has to be before startup sweeps it. Longer than any run
79/// this graph plausibly takes, so a sweep cannot pull a task out from under a
80/// daemon that is merely slow.
81pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
82
83/// What the loop is working on, for the status file.
84#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
85#[serde(default)]
86pub struct Current {
87    /// Task id being run.
88    pub task: String,
89    /// Run id the task produced.
90    pub run: String,
91}
92
93/// The daemon's liveness, published to `<home>/daemon.json`.
94///
95/// This is the only interface between the loop and the web UI, which is why it
96/// carries `updated_at` as well as `started_at`: a reader cannot tell a
97/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
98/// can compare the heartbeat against the clock.
99#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct Status {
101    /// On-disk format version.
102    pub schema: u32,
103    /// Process id, so a human can find or kill the daemon.
104    pub pid: u32,
105    /// When this process started.
106    pub started_at: Timestamp,
107    /// Last heartbeat.
108    pub updated_at: Timestamp,
109    /// True when the queue has nothing runnable.
110    pub idle: bool,
111    /// The task and run in flight, if any.
112    pub current: Option<Current>,
113    /// Tasks that reached a terminal status in this process.
114    pub completed: usize,
115    /// Queue polls since start, so a wedged loop shows up as a frozen count.
116    pub polls: u64,
117}
118
119impl Status {
120    /// A fresh, idle status for this process.
121    #[must_use]
122    pub fn new() -> Self {
123        let now = Timestamp::now();
124        Self {
125            schema: SCHEMA,
126            pid: std::process::id(),
127            started_at: now,
128            updated_at: now,
129            idle: true,
130            current: None,
131            completed: 0,
132            polls: 0,
133        }
134    }
135}
136
137impl Default for Status {
138    fn default() -> Self {
139        Self::new()
140    }
141}
142
143/// How the loop should behave.
144#[derive(Debug, Clone)]
145pub struct Opts {
146    /// Repository used by tasks that name none.
147    pub repo: PathBuf,
148    /// Explicit `magi.toml`, instead of the discovered layer stack.
149    pub config: Option<PathBuf>,
150    /// Queue poll interval.
151    pub poll: Duration,
152    /// Attempts a task gets before it is held for a human.
153    pub max_attempts: usize,
154    /// Drain what is runnable now, then return, instead of waiting for more.
155    pub once: bool,
156    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
157    pub merge: Option<String>,
158}
159
160impl Default for Opts {
161    fn default() -> Self {
162        Self {
163            repo: PathBuf::from("."),
164            config: None,
165            poll: POLL,
166            max_attempts: 2,
167            once: false,
168            merge: None,
169        }
170    }
171}
172
173/// Where the status file lives.
174#[must_use]
175pub fn status_path() -> PathBuf {
176    crate::run::home().join("daemon.json")
177}
178
179/// Publish the status file for this process.
180pub fn write_status(status: &Status) -> Result<()> {
181    write_status_to(&status_path(), status)
182}
183
184/// Publish a status to an explicit path.
185///
186/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
187/// on every health poll and must never see a half-written one.
188pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
189    if let Some(parent) = path.parent() {
190        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
191    }
192    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
193    let tmp = path.with_extension("json.tmp");
194    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
195    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
196    Ok(())
197}
198
199/// Delete the status file. Called on the way out so a clean exit reads as
200/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
201pub fn clear_status() {
202    clear_status_at(&status_path());
203}
204
205/// Delete a status file at an explicit path, so the loop's teardown and
206/// [`clear_status`] cannot drift apart: the loop is handed the path it
207/// published to, and a test can watch a temp file disappear.
208fn clear_status_at(path: &Path) {
209    let _ = std::fs::remove_file(path);
210}
211
212/// A cooperative stop, shared with whoever asked the loop to run.
213///
214/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
215/// Ctrl-C listener and the web UI keep others, and every clone points at the
216/// same flag. There is no channel because there is nothing to send — the only
217/// message is "stop", it is idempotent, and a flag cannot be missed by a
218/// receiver that was not listening yet.
219///
220/// The handle also answers the question the operator's screen asks next: a
221/// stop does not take effect until the run in flight has finished, so
222/// [`Stop::finishing`] reports "asked to stop, still working" rather than
223/// leaving a caller to infer it from a heartbeat and hope.
224#[derive(Debug, Clone, Default)]
225pub struct Stop {
226    /// Set once, never cleared: a stop is not something an operator takes back
227    /// half way through, and a clearable flag would let a start racing a stop
228    /// resurrect a loop that is already unwinding.
229    stopped: Arc<AtomicBool>,
230    /// Whether a run is in flight, so `finishing` can distinguish a stop that
231    /// has landed from one that is waiting on `execute`.
232    busy: Arc<AtomicBool>,
233    /// Wakes the idle wait. Without this a stop would not be seen until the
234    /// poll interval elapsed, and an operator tapping stop on a phone would
235    /// watch a button do nothing for five seconds.
236    wake: Arc<Notify>,
237    /// Handed to the run in flight, so a stop can also mean "park at the next
238    /// node boundary" instead of "finish the whole competition first".
239    pause: crate::graph::Pause,
240}
241
242impl Stop {
243    /// A stop nobody has asked for yet.
244    #[must_use]
245    pub fn new() -> Self {
246        Self::default()
247    }
248
249    /// Ask the loop to stop. Idempotent, and safe to call before the loop
250    /// starts: the flag is checked before the first poll.
251    pub fn stop(&self) {
252        self.stopped.store(true, Ordering::SeqCst);
253        // `notify_one` rather than `notify_waiters` because the loop may not be
254        // parked yet: this stores a permit, so a wait that registers a moment
255        // later returns at once instead of sleeping out the whole interval.
256        self.wake.notify_one();
257    }
258
259    /// Has a stop been asked for?
260    #[must_use]
261    pub fn stopped(&self) -> bool {
262        self.stopped.load(Ordering::SeqCst)
263    }
264
265    /// Has a stop been asked for that has not taken effect yet, because a run
266    /// is still in flight?
267    ///
268    /// This is the state a screen has to be able to show. A stop never abandons
269    /// a run — see [`serve_until`] — so between the tap and the loop's return
270    /// there is a window of tens of minutes in which "running" and "stopped"
271    /// are both misleading answers.
272    #[must_use]
273    pub fn finishing(&self) -> bool {
274        self.stopped() && self.busy.load(Ordering::SeqCst)
275    }
276
277    /// Ask the loop to stop *and* the run in flight to park at its next node
278    /// boundary.
279    ///
280    /// The plain [`Stop::stop`] never abandons a run, which is right when the
281    /// operator only wants the queue to drain: a competition is tens of
282    /// minutes and its worktrees are paid for. But an operator who wants to
283    /// replace the binary cannot wait out a run that has an hour left, and
284    /// killing the process loses whatever the seats in flight had not written.
285    /// Parking costs at most the node in progress and leaves the run
286    /// resumable.
287    pub fn park(&self) {
288        self.pause.park();
289        self.stop();
290    }
291
292    /// Has a park been asked for?
293    #[must_use]
294    pub fn parking(&self) -> bool {
295        self.pause.parked()
296    }
297
298    /// The pause handle to give a runner.
299    #[must_use]
300    pub fn pause(&self) -> crate::graph::Pause {
301        self.pause.clone()
302    }
303
304    /// Is a run in flight right now?
305    ///
306    /// `finishing` answers "a stop is waiting on a run", which is false until
307    /// someone asks to stop. An upgrade needs the plain question, because it
308    /// is about to be the one asking.
309    #[must_use]
310    pub fn busy_now(&self) -> bool {
311        self.busy.load(Ordering::SeqCst)
312    }
313
314    /// Mark a run as in flight, or finished, for [`Stop::finishing`].
315    fn busy(&self, running: bool) {
316        self.busy.store(running, Ordering::SeqCst);
317    }
318
319    /// Wait out one poll interval, returning early once a stop is asked for.
320    async fn idle(&self, poll: Duration) {
321        tokio::select! {
322            () = tokio::time::sleep(poll) => {}
323            () = self.wake.notified() => {}
324        }
325    }
326}
327
328/// The daemon's published state, read permissively.
329///
330/// This mirrors [`Status`], but is a separate declaration on purpose: every
331/// field defaults, so a status file from an older or newer magi still yields
332/// a usable reading — one this build has never heard of — instead of a parse
333/// error that hides the daemon entirely.
334#[derive(Debug, Clone, Default, Deserialize)]
335#[serde(default)]
336pub struct Reading {
337    /// Format version the daemon claims.
338    pub schema: u32,
339    /// Daemon process id, for an operator who wants to stop it.
340    pub pid: Option<u32>,
341    /// When that process started.
342    pub started_at: Option<Timestamp>,
343    /// Last heartbeat. Absent means the file is unusable, hence not running.
344    pub updated_at: Option<Timestamp>,
345    /// True when the queue had nothing runnable at the last poll.
346    pub idle: bool,
347    /// What the daemon is working on.
348    pub current: Option<Current>,
349    /// Tasks this daemon process has finished.
350    pub completed: u64,
351    /// Queue polls this daemon process has made.
352    pub polls: u64,
353}
354
355impl Reading {
356    /// Seconds since the last heartbeat, or `None` when there has never been
357    /// one.
358    #[must_use]
359    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
360        self.updated_at
361            .map(|at| (now.as_second() - at.as_second()).max(0))
362    }
363
364    /// Whether the loop counts as running: a heartbeat no older than
365    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
366    /// progress hours after the daemon that owned it was killed.
367    #[must_use]
368    pub fn running(&self, now: Timestamp) -> bool {
369        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
370    }
371}
372
373/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
374/// usable there.
375///
376/// Missing, half-written and unparseable all collapse to `None`, because the
377/// only question a reader asks is whether a daemon is alive, and a file it
378/// cannot read is not evidence that one is.
379#[must_use]
380pub fn read_status(home: &Path) -> Option<Reading> {
381    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
382    serde_json::from_str(&body).ok()
383}
384
385/// What a live daemon is working on right now, or `None`.
386///
387/// One definition of liveness, because deleting a task and deleting a run are
388/// both gated on it from both the CLI and the web UI - four callers that must
389/// never disagree about whether the same thing is in flight. A stale heartbeat
390/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
391/// left at `running` or a run left at `implementing` by a killed daemon is a
392/// leftover record rather than work in progress.
393#[must_use]
394pub fn current_work(home: &Path, now: Timestamp) -> Option<Current> {
395    read_status(home)
396        .filter(|reading| reading.running(now))
397        .and_then(|reading| reading.current)
398}
399
400/// Whether a live daemon is working on this run at this moment.
401#[must_use]
402pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
403    current_work(home, now).is_some_and(|c| c.run == run)
404}
405
406/// Whether a live daemon is working on this task at this moment.
407#[must_use]
408pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
409    current_work(home, now).is_some_and(|c| c.task == task)
410}
411
412/// Remove claim files older than `older_than` and return the task ids swept.
413///
414/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
415/// destructor, and the orphaned `.lock` file would make its task permanently
416/// unclaimable — the backlog would stop for good at exactly the task that was
417/// in flight when the machine went down.
418///
419/// The test is age alone. There is no portable way to ask whether the pid
420/// recorded in the lock is still alive and still magi (pids are reused, and
421/// `/proc` does not exist on two of the three platforms magi targets), so this
422/// trades a check it cannot make for a bound it can. The risk is real and
423/// one-sided: a run that outlives `older_than` can have its claim swept while
424/// it is still working, letting a second daemon start a second run on the same
425/// task. [`STALE_CLAIM`] is therefore set an order of magnitude above any
426/// plausible run, and the sweep is only ever called at startup, when this
427/// process knows it holds no claims of its own.
428pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
429    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
430        .into_iter()
431        .flatten()
432        .flatten()
433        .map(|e| e.path())
434        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
435        .filter(|p| {
436            p.metadata()
437                .and_then(|m| m.modified())
438                .and_then(|t| t.elapsed().map_err(std::io::Error::other))
439                .is_ok_and(|age| age >= older_than)
440        })
441        .filter(|p| std::fs::remove_file(p).is_ok())
442        .filter_map(|p| {
443            p.file_stem()
444                .and_then(|s| s.to_str())
445                .map(std::borrow::ToOwned::to_owned)
446        })
447        .collect();
448    swept.sort_unstable();
449    swept
450}
451
452/// What a finished run tells the queue about the task it came from.
453///
454/// A struct rather than a fourth and fifth boolean argument: the two flags
455/// answer different questions about the same run, and a call site passing
456/// `(…, true, false)` is one transposition away from refunding attempts
457/// forever.
458#[derive(Debug, Clone, Copy)]
459pub struct Verdict {
460    /// Where the graph stopped.
461    pub status: RunStatus,
462    /// The run opened a pull request.
463    pub left_pr: bool,
464    /// At least one seat was lost to a rate limit.
465    pub quota_hit: bool,
466    /// The run parked at a node boundary because it was asked to.
467    pub parked: bool,
468}
469
470/// Record a finished run against the task it came from.
471///
472/// Kept pure and separate from the loop because this mapping *is* the retry
473/// policy, and a policy that can only be exercised by spawning a graph is a
474/// policy nobody checks. The table:
475///
476/// | run status              | task becomes        | attempt spent |
477/// |-------------------------|---------------------|---------------|
478/// | parked at a boundary    | `Failed` (requeued) | **no**        |
479/// | `Merged`, `Ready`       | `Done`              | yes           |
480/// | `Stalled`, quota hit    | `Failed` (requeued) | **no**        |
481/// | `Stalled`, no quota     | `Failed`, or `Held` | yes           |
482/// | `Blocked` with a PR     | `Held`              | yes           |
483/// | `Blocked`, `Failed`     | `Failed`, or `Held` | yes           |
484/// | anything non-terminal   | `Failed`, or `Held` | yes           |
485///
486/// The two `Stalled` rows are the ones worth reading twice. A quorum lost to
487/// rate limits is a property of the machine and not of the task, so the
488/// attempt is refunded and a reset quota picks the work up where it stopped.
489/// A quorum lost to judges that answered with the wrong shape is ordinary
490/// flakiness, and refunding *that* takes the bound off the retry loop
491/// entirely: run e633 stalled with `quota: []` after two judges wrote
492/// unusable JSON, was refunded, and the next attempt paid for a fresh
493/// hour-long implement wave before it could fail the same way. `max_attempts`
494/// exists precisely so that cannot repeat forever.
495///
496/// A non-terminal status means `execute` returned while the graph was still
497/// mid-flight, which is a bug rather than a verdict; it is treated as a
498/// failure so that a task cannot loop on it either.
499///
500/// `left_pr` splits the `Blocked` row, and it is the difference between a run
501/// that failed and a run that finished into a gate. See [`Task::handed_off`].
502pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
503    // A parked run is the operator's own doing, and its work is intact on
504    // disk. The task goes back in line with its attempt refunded so the next
505    // loop resumes the same run - which `one_task` prefers over competing
506    // again - and so that swapping the binary a few times cannot exhaust a
507    // budget meant for agents that actually misbehaved.
508    if verdict.parked {
509        task.stall(detail);
510        return;
511    }
512    match verdict.status {
513        RunStatus::Merged | RunStatus::Ready => task.succeed(),
514        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
515        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
516        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
517        RunStatus::Blocked => task.fail(detail, max_attempts),
518        other => task.fail(
519            format!(
520                "the graph stopped at `{}` without reaching a terminal status: {detail}",
521                label(other)
522            ),
523            max_attempts,
524        ),
525    }
526}
527
528/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
529///
530/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
531/// sets, so there is one loop body rather than two that drift apart the first
532/// time the retry policy changes on only one of them.
533pub async fn serve(opts: Opts) -> Result<()> {
534    serve_until(opts, Stop::new()).await
535}
536
537/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
538///
539/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
540/// mid-node leaves worktrees, branches and agent sessions behind, and every
541/// agent call already paid for is lost; finishing the run costs the operator a
542/// wait and saves them a cleanup. A stop therefore only sets a flag: the
543/// current `execute` runs to its terminal status, the task's outcome is
544/// recorded, and only then does the loop return. That window is what
545/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
546/// still has a second Ctrl-C, which the runtime turns into a process kill —
547/// and the task left `Running` then tells the next daemon, and the next human,
548/// where to look.
549///
550/// While the queue is empty the stop is honoured within one wakeup rather than
551/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
552/// caller that taps stop does not sit through the remainder of a sleep.
553pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
554    let signal = {
555        let stop = stop.clone();
556        tokio::spawn(async move {
557            if tokio::signal::ctrl_c().await.is_ok() {
558                stop.stop();
559                tracing::info!("shutdown requested; a run in flight will be finished first");
560            }
561        })
562    };
563
564    let outcome = drive(&opts, &Queue::open(), &status_path(), &stop).await;
565
566    signal.abort();
567    outcome
568}
569
570/// The loop proper: setup, poll, teardown, with the queue and the status file
571/// supplied rather than discovered.
572///
573/// Both are parameters because [`crate::run::home`] is process-global and its
574/// override is a `OnceLock`, so a unit test that pinned it would fight every
575/// other test in the binary — and a loop that resolved the home itself could
576/// only be exercised against the operator's real one, publishing over a live
577/// daemon's status file and claiming tasks out of a live backlog.
578async fn drive(opts: &Opts, queue: &Queue, status_file: &Path, stop: &Stop) -> Result<()> {
579    let swept = sweep_stale_claims(queue, STALE_CLAIM);
580    if !swept.is_empty() {
581        tracing::warn!(
582            "swept {} stale claim(s) left behind by an earlier daemon: {}",
583            swept.len(),
584            swept.join(", ")
585        );
586    }
587
588    // The status file is a *snapshot*, not a stream of events: a reader only
589    // ever wants the latest values, and every tick rewrites the whole file
590    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
591    // while an mpsc channel would force the loop to re-send unchanged fields on
592    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
593    // for no gain. The lock is only ever held across a field assignment, never
594    // across an await.
595    let status = Arc::new(Mutex::new(Status::new()));
596    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
597    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
598
599    tracing::info!(
600        "magi serve: queue {} (poll {}s, {} attempts per task, one run at a time)",
601        queue.root().display(),
602        opts.poll.as_secs(),
603        opts.max_attempts
604    );
605
606    let outcome = poll(opts, queue, &status, stop).await;
607
608    beat.abort();
609    clear_status_at(status_file);
610    outcome
611}
612
613/// Refresh the status file on a fixed tick.
614///
615/// Separate from the loop because a run takes tens of minutes: a status file
616/// written only between tasks would look stale for the whole of every run, and
617/// a reader would report the daemon dead exactly while it was busiest.
618async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
619    loop {
620        tokio::time::sleep(HEARTBEAT).await;
621        let snapshot = {
622            let mut guard = lock(&status);
623            guard.updated_at = Timestamp::now();
624            guard.clone()
625        };
626        if let Err(e) = write_status_to(&path, &snapshot) {
627            // A failed heartbeat must not take the daemon down: the loop is the
628            // product, the status file is only the window onto it.
629            tracing::warn!("could not refresh the daemon status file: {e:#}");
630        }
631    }
632}
633
634/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
635/// teardown and cannot skip the teardown on an early return.
636async fn poll(opts: &Opts, queue: &Queue, status: &Arc<Mutex<Status>>, stop: &Stop) -> Result<()> {
637    // Only consulted by `once`, where a task that just failed is still
638    // `runnable` and would otherwise be picked up again inside the same drain.
639    // In the long-running mode a later poll retrying a failed task is the point,
640    // and the attempt counter is what bounds it.
641    let mut attempted: Vec<String> = Vec::new();
642
643    while !stop.stopped() {
644        lock(status).polls += 1;
645
646        let candidates: Vec<Task> = runnable(queue)
647            .into_iter()
648            .filter(|t| !opts.once || !attempted.contains(&t.id))
649            .collect();
650
651        let mut ran = false;
652        for candidate in candidates {
653            if stop.stopped() {
654                break;
655            }
656            // A claim we cannot take means another daemon, or a human running
657            // `magi run`, got there first. That is not the task's fault and
658            // must not spend one of its attempts: move to the next candidate
659            // rather than recording a failure.
660            let Ok(_claim) = queue.claim(&candidate.id) else {
661                tracing::debug!("task {} is claimed elsewhere; skipping", candidate.short());
662                continue;
663            };
664            // Re-read under the claim: the task on disk may have been held or
665            // edited between the listing and the lock.
666            let mut task = match queue.get(&candidate.id) {
667                Ok(t) if t.status.runnable() => t,
668                Ok(_) => continue,
669                Err(e) => {
670                    tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
671                    continue;
672                }
673            };
674            attempted.push(task.id.clone());
675            lock(status).idle = false;
676            // A stop asked for from here on is "finishing", not "stopped": the
677            // run gets to reach a terminal status before the loop returns.
678            stop.busy(true);
679            attempt(opts, queue, status, stop, &mut task).await;
680            stop.busy(false);
681            {
682                let mut guard = lock(status);
683                guard.current = None;
684                guard.completed += 1;
685            }
686            ran = true;
687            break;
688        }
689
690        if ran {
691            continue;
692        }
693
694        lock(status).idle = true;
695        if opts.once {
696            return Ok(());
697        }
698        stop.idle(opts.poll).await;
699    }
700    Ok(())
701}
702
703/// Run one claimed task to a terminal status and record the outcome.
704///
705/// Every transition is flushed to the queue as it happens, so the state on disk
706/// is what actually occurred rather than what this process still intends to
707/// write.
708async fn attempt(
709    opts: &Opts,
710    queue: &Queue,
711    status: &Arc<Mutex<Status>>,
712    stop: &Stop,
713    task: &mut Task,
714) {
715    let repo = repo_for(task, &opts.repo);
716    tracing::info!(
717        "task {} — {} (repo {})",
718        task.short(),
719        task.title,
720        repo.display()
721    );
722
723    let config = match prepare(&repo, opts) {
724        Ok(c) => c,
725        Err(e) => {
726            // A setup failure spends an attempt even though no run was minted.
727            // Without that, a task naming a repository that does not exist
728            // would be retried at every poll for as long as the daemon lives.
729            task.attempts += 1;
730            task.fail(format!("config: {e:#}"), opts.max_attempts);
731            record(queue, task);
732            return;
733        }
734    };
735
736    // A resumable run of this task is carried on, never re-competed. The
737    // candidates are built and paid for, and a fresh competition races a
738    // second implementation against them.
739    //
740    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
741    // started 3cbf on the same task a moment later, duplicating two and a
742    // half hours of agent work. Then b25f stalled on a judge that timed out
743    // and one that answered with no JSON - `quota: 0`, so nothing the machine
744    // was to blame for - and 4043 started **one second** later, buying three
745    // fresh implementations to reach the same panel. `RunStatus::resumable`
746    // rather than `!done()` is what catches the second case: a stall is
747    // terminal, and its cheap recovery re-asks only the absent seats.
748    let unfinished = task
749        .runs
750        .iter()
751        .rev()
752        .find(|id| {
753            RunState::load(id)
754                .map(|s| s.status.resumable())
755                .unwrap_or(false)
756        })
757        .cloned();
758    let started = match &unfinished {
759        Some(id) => {
760            tracing::info!("resuming run {id} rather than competing again");
761            Runner::resume(id)
762        }
763        None => Runner::start(&repo, task.instruction.clone(), config).await,
764    };
765    let mut runner = match started {
766        Ok(r) => r,
767        Err(e) => {
768            task.attempts += 1;
769            task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
770            record(queue, task);
771            return;
772        }
773    };
774    // A stop that means "park" reaches the graph through this handle.
775    runner.on_pause(stop.pause());
776
777    // `start` has minted the run, so the task can now point at it. Persisting
778    // `Running` before `execute` is what makes a crash mid-run legible.
779    let run = runner.state.id.clone();
780    task.start(run.clone());
781    record(queue, task);
782    lock(status).current = Some(Current {
783        task: task.id.clone(),
784        run,
785    });
786
787    let detail = match runner.execute().await {
788        Ok(()) => describe(&runner.state),
789        Err(e) => format!("{e:#}"),
790    };
791    let verdict = Verdict {
792        status: runner.state.status,
793        // A run that opened a pull request handed its work over, whatever the
794        // gate then decided about merging it.
795        left_pr: runner.state.pr.is_some(),
796        // Only a rate limit earns the task its attempt back.
797        quota_hit: !runner.state.quota.is_empty(),
798        // A run that parked was asked to stop; that is not a failure and must
799        // not spend an attempt, or replacing the binary a few times would
800        // exhaust a task's budget without an agent ever misbehaving.
801        parked: runner.state.parked,
802    };
803    settle(task, verdict, &detail, opts.max_attempts);
804    record(queue, task);
805    tracing::info!(
806        "task {} is {} after run {} ({})",
807        task.short(),
808        task.status.as_str(),
809        runner.state.short(),
810        label(runner.state.status)
811    );
812}
813
814/// Load the config for a task's repository, with the merge override applied.
815fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
816    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
817    if let Some(mode) = &opts.merge {
818        config.merge.mode = merge_mode(mode)?;
819    }
820    Ok(config)
821}
822
823/// Which repository a task runs in. A task that names none — the normal case
824/// for one filed from a phone — runs in the daemon's own default.
825fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
826    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
827        return fallback.to_path_buf();
828    }
829    task.repo.clone()
830}
831
832/// Persist a transition. A queue write failure is logged rather than fatal: the
833/// run already happened, and taking the daemon down would only add a lost
834/// backlog to a full disk.
835fn record(queue: &Queue, task: &mut Task) {
836    if let Err(e) = queue.put(task) {
837        tracing::error!("could not record task {}: {e:#}", task.short());
838    }
839}
840
841/// Every runnable task, in the order the loop should try them.
842///
843/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
844/// tail exists so that a claim somebody else holds costs the loop the next
845/// candidate rather than a whole poll interval of idleness.
846fn runnable(queue: &Queue) -> Vec<Task> {
847    let mut tasks: Vec<Task> = queue
848        .list()
849        .into_iter()
850        .filter(|t| t.status.runnable())
851        .collect();
852    tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
853    tasks
854}
855
856/// Why a run ended where it did, in one line, for [`Task::last_error`].
857///
858/// A stalled run names the seats the quota took out: "out of quota" is not
859/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
860/// agent to replace or which plan to top up.
861fn describe(state: &RunState) -> String {
862    let mut detail = if state.status == RunStatus::Stalled {
863        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
864        seats.sort_unstable();
865        seats.dedup();
866        if seats.is_empty() {
867            "the judging panel lost its quorum".to_owned()
868        } else {
869            format!(
870                "the judging panel lost its quorum; quota took out {}",
871                seats.join(", ")
872            )
873        }
874    } else {
875        format!("run ended {}", label(state.status))
876    };
877    if let Some(last) = state.events.last() {
878        detail.push_str(&format!(" ({}: {})", last.node, last.message));
879    }
880    detail.push_str(&format!(" [run {}]", state.id));
881    detail
882}
883
884/// Stable lower-case name for a run status, for logs and task errors.
885/// One definition of a status's name, on the type that owns it: this table
886/// used to live here as a second copy, and a status renamed in one place would
887/// have gone on reading correctly in the other.
888fn label(status: RunStatus) -> &'static str {
889    status.as_str()
890}
891
892/// Parse a merge mode override.
893fn merge_mode(mode: &str) -> Result<MergeMode> {
894    match mode {
895        "none" => Ok(MergeMode::None),
896        "local" => Ok(MergeMode::Local),
897        "pr" => Ok(MergeMode::Pr),
898        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
899    }
900}
901
902/// Take the status lock, recovering from a poisoned one.
903///
904/// A panic elsewhere must not silently stop the heartbeat: the status is plain
905/// data, and the worst a poisoned lock can hold is a stale timestamp.
906fn lock(status: &Mutex<Status>) -> MutexGuard<'_, Status> {
907    status
908        .lock()
909        .unwrap_or_else(std::sync::PoisonError::into_inner)
910}
911
912#[cfg(test)]
913mod tests {
914    use super::*;
915    use crate::queue::{Source, TaskStatus};
916    use pretty_assertions::assert_eq;
917
918    fn task() -> Task {
919        Task::new(
920            "add retries".to_owned(),
921            "add retries".to_owned(),
922            PathBuf::from("/repo"),
923            Source::Human,
924        )
925    }
926
927    #[test]
928    fn every_run_status_settles_the_task_it_came_from() {
929        // run status, resulting task status, attempts still standing after one
930        let table = [
931            (RunStatus::Merged, TaskStatus::Done, 1),
932            (RunStatus::Ready, TaskStatus::Done, 1),
933            (RunStatus::Stalled, TaskStatus::Failed, 0),
934            (RunStatus::Blocked, TaskStatus::Failed, 1),
935            (RunStatus::Failed, TaskStatus::Failed, 1),
936            (RunStatus::Prep, TaskStatus::Failed, 1),
937            (RunStatus::Implementing, TaskStatus::Failed, 1),
938            (RunStatus::Judging, TaskStatus::Failed, 1),
939            (RunStatus::Deliberating, TaskStatus::Failed, 1),
940            (RunStatus::Voting, TaskStatus::Failed, 1),
941            (RunStatus::Reviewing, TaskStatus::Failed, 1),
942            (RunStatus::Gating, TaskStatus::Failed, 1),
943        ];
944        for (run, want, attempts) in table {
945            let mut t = task();
946            t.start("20260902-000000-aaaa".to_owned());
947            settle(
948                &mut t,
949                Verdict {
950                    status: run,
951                    left_pr: false,
952                    parked: false,
953                    quota_hit: matches!(run, RunStatus::Stalled),
954                },
955                "why",
956                2,
957            );
958            assert_eq!(t.status, want, "task status after {}", label(run));
959            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
960        }
961    }
962
963    #[test]
964    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
965        let mut stalled = task();
966        stalled.start("20260902-000000-aaaa".to_owned());
967        settle(
968            &mut stalled,
969            Verdict {
970                status: RunStatus::Stalled,
971                left_pr: false,
972                parked: false,
973                quota_hit: true,
974            },
975            "quota",
976            1,
977        );
978        assert_eq!(stalled.attempts, 0);
979        assert!(
980            stalled.status.runnable(),
981            "a machine problem must leave the task in line"
982        );
983
984        let mut blocked = task();
985        blocked.start("20260902-000000-aaaa".to_owned());
986        settle(
987            &mut blocked,
988            Verdict {
989                status: RunStatus::Blocked,
990                left_pr: false,
991                parked: false,
992                quota_hit: false,
993            },
994            "findings open",
995            1,
996        );
997        assert_eq!(blocked.attempts, 1);
998        assert_eq!(
999            blocked.status,
1000            TaskStatus::Held,
1001            "the last attempt hands the task to a human"
1002        );
1003    }
1004
1005    #[test]
1006    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
1007        // Attempts to spare: without the pull request this task would go
1008        // straight back in line and run the whole competition again.
1009        let mut delivered = task();
1010        delivered.start("20260903-080619-01c2".to_owned());
1011        settle(
1012            &mut delivered,
1013            Verdict {
1014                status: RunStatus::Blocked,
1015                left_pr: true,
1016                parked: false,
1017                quota_hit: false,
1018            },
1019            "no check status",
1020            4,
1021        );
1022        assert_eq!(
1023            delivered.status,
1024            TaskStatus::Held,
1025            "a pull request waiting on CI or a person is not a retryable failure"
1026        );
1027        assert!(
1028            !delivered.status.runnable(),
1029            "the loop must not pick this task up again"
1030        );
1031        assert_eq!(
1032            delivered.last_error.as_deref(),
1033            Some("no check status"),
1034            "the operator needs to be told what the gate was waiting for"
1035        );
1036
1037        // The same status without a pull request is a plain failure, and with
1038        // attempts left it is retried.
1039        let mut empty_handed = task();
1040        empty_handed.start("20260903-080619-01c2".to_owned());
1041        settle(
1042            &mut empty_handed,
1043            Verdict {
1044                status: RunStatus::Blocked,
1045                left_pr: false,
1046                parked: false,
1047                quota_hit: false,
1048            },
1049            "findings open",
1050            4,
1051        );
1052        assert_eq!(empty_handed.status, TaskStatus::Failed);
1053        assert!(empty_handed.status.runnable());
1054    }
1055
1056    #[test]
1057    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
1058        // Parking is the operator asking for the process back - to replace the
1059        // binary, most of all. The run's work is intact on disk, so this is
1060        // not a failed attempt, and charging for it would mean a few upgrades
1061        // could exhaust a budget meant for agents that misbehaved.
1062        let mut parked = task();
1063        parked.start("20260903-183634-2d98".to_owned());
1064        settle(
1065            &mut parked,
1066            Verdict {
1067                status: RunStatus::Implementing,
1068                left_pr: false,
1069                quota_hit: false,
1070                parked: true,
1071            },
1072            "parked after `implementing`",
1073            2,
1074        );
1075        assert_eq!(parked.attempts, 0, "a park is refunded");
1076        assert!(
1077            parked.status.runnable(),
1078            "and the task stays in line so the next loop resumes its run"
1079        );
1080        assert_eq!(
1081            parked.last_error.as_deref(),
1082            Some("parked after `implementing`"),
1083            "the card says where it stopped"
1084        );
1085
1086        // Without the park flag the same non-terminal status is what it always
1087        // was: `execute` returning mid-flight, which is a bug and spends an
1088        // attempt so a task cannot loop on it forever.
1089        let mut broken = task();
1090        broken.start("20260903-183634-2d98".to_owned());
1091        settle(
1092            &mut broken,
1093            Verdict {
1094                status: RunStatus::Implementing,
1095                left_pr: false,
1096                quota_hit: false,
1097                parked: false,
1098            },
1099            "returned mid-flight",
1100            2,
1101        );
1102        assert_eq!(broken.attempts, 1);
1103    }
1104
1105    #[test]
1106    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
1107        // Run e633: quorum lost because two judges answered with the wrong
1108        // JSON shape, `quota: []`. Refunding that takes the bound off the
1109        // retry loop, and each retry pays for a fresh hour-long implement
1110        // wave before it can fail the same way.
1111        let mut flaky = task();
1112        flaky.start("20260903-123023-e633".to_owned());
1113        settle(
1114            &mut flaky,
1115            Verdict {
1116                status: RunStatus::Stalled,
1117                left_pr: false,
1118                parked: false,
1119                quota_hit: false,
1120            },
1121            "verdict rests on 1 of 3 judges",
1122            2,
1123        );
1124        assert_eq!(
1125            flaky.attempts, 1,
1126            "flakiness spends an attempt, so `max_attempts` still bounds it"
1127        );
1128        assert!(flaky.status.runnable(), "and it is still worth retrying");
1129
1130        // The same status, lost to a rate limit, is the machine's fault.
1131        let mut limited = task();
1132        limited.start("20260903-123023-e633".to_owned());
1133        settle(
1134            &mut limited,
1135            Verdict {
1136                status: RunStatus::Stalled,
1137                left_pr: false,
1138                parked: false,
1139                quota_hit: true,
1140            },
1141            "judge-2, judge-3 out of quota",
1142            2,
1143        );
1144        assert_eq!(limited.attempts, 0, "a quota window is refunded");
1145        assert!(limited.status.runnable());
1146
1147        // And the bound really binds: a task that keeps stalling on flakiness
1148        // reaches a human instead of running the roster forever.
1149        let mut worn = task();
1150        for _ in 0..2 {
1151            worn.release();
1152        }
1153        worn.start("20260903-123023-e633".to_owned());
1154        worn.attempts = 2;
1155        settle(
1156            &mut worn,
1157            Verdict {
1158                status: RunStatus::Stalled,
1159                left_pr: false,
1160                parked: false,
1161                quota_hit: false,
1162            },
1163            "no quorum again",
1164            2,
1165        );
1166        assert_eq!(worn.status, TaskStatus::Held);
1167        assert!(!worn.status.runnable());
1168    }
1169
1170    #[test]
1171    fn a_held_task_is_never_offered_to_the_loop() {
1172        let dir = tempfile::tempdir().unwrap();
1173        let queue = Queue::at(dir.path().to_path_buf());
1174        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
1175            let mut t = task();
1176            t.id = format!("2026090{n}-000000-000{n}");
1177            t.priority = priority;
1178            queue.put(&mut t).unwrap();
1179        }
1180        let mut held = task();
1181        held.id = "20260909-000000-9999".to_owned();
1182        held.priority = 99;
1183        held.hold();
1184        queue.put(&mut held).unwrap();
1185
1186        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
1187        assert_eq!(order.len(), 3);
1188        assert!(!order.contains(&held.id));
1189        assert_eq!(
1190            order.first().cloned(),
1191            queue.next_runnable().map(|t| t.id),
1192            "the loop's first candidate is exactly what the queue offers"
1193        );
1194        assert_eq!(
1195            order,
1196            vec![
1197                "20260902-000000-0002".to_owned(),
1198                "20260903-000000-0003".to_owned(),
1199                "20260901-000000-0001".to_owned(),
1200            ],
1201            "priority first, then oldest, so nothing starves"
1202        );
1203    }
1204
1205    #[test]
1206    fn sweep_removes_an_abandoned_lock_and_keeps_a_live_one() {
1207        let dir = tempfile::tempdir().unwrap();
1208        let queue = Queue::at(dir.path().to_path_buf());
1209        let mut old = task();
1210        old.id = "20260101-000000-old0".to_owned();
1211        queue.put(&mut old).unwrap();
1212        let mut fresh = task();
1213        fresh.id = "20260101-000000-new0".to_owned();
1214        queue.put(&mut fresh).unwrap();
1215
1216        let abandoned = queue.claim(&old.id).unwrap();
1217        std::thread::sleep(Duration::from_millis(60));
1218        let live = queue.claim(&fresh.id).unwrap();
1219
1220        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
1221        assert_eq!(swept, vec![old.id.clone()]);
1222        assert!(
1223            queue.claim(&old.id).is_ok(),
1224            "a swept task is claimable again"
1225        );
1226        assert!(
1227            queue.claim(&fresh.id).is_err(),
1228            "a lock younger than the threshold still protects its task"
1229        );
1230        drop((abandoned, live));
1231    }
1232
1233    #[test]
1234    fn an_already_claimed_task_is_skipped_rather_than_failed() {
1235        let dir = tempfile::tempdir().unwrap();
1236        let queue = Queue::at(dir.path().to_path_buf());
1237        let mut only = task();
1238        queue.put(&mut only).unwrap();
1239
1240        let _elsewhere = queue.claim(&only.id).unwrap();
1241        let candidates = runnable(&queue);
1242        assert_eq!(candidates.len(), 1, "the task is still runnable");
1243        assert!(
1244            queue.claim(&candidates[0].id).is_err(),
1245            "the loop cannot take a claim somebody else holds"
1246        );
1247
1248        let after = queue.get(&only.id).unwrap();
1249        assert_eq!(after.status, TaskStatus::Queued);
1250        assert_eq!(
1251            after.attempts, 0,
1252            "losing the race is not an attempt at the task"
1253        );
1254        assert_eq!(after.last_error, None);
1255    }
1256
1257    #[test]
1258    fn the_status_file_round_trips_and_its_heartbeat_advances() {
1259        let dir = tempfile::tempdir().unwrap();
1260        let path = dir.path().join("daemon.json");
1261
1262        let mut status = Status::new();
1263        status.idle = false;
1264        status.completed = 7;
1265        status.current = Some(Current {
1266            task: "20260902-000000-t111".to_owned(),
1267            run: "20260902-000001-r111".to_owned(),
1268        });
1269        write_status_to(&path, &status).unwrap();
1270        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1271        assert_eq!(first.schema, SCHEMA);
1272        assert_eq!(first.pid, std::process::id());
1273        assert!(!first.idle);
1274        assert_eq!(first.completed, 7);
1275        assert_eq!(first.current, status.current);
1276        assert!(
1277            !path.with_extension("json.tmp").exists(),
1278            "the temp file is renamed, not left behind"
1279        );
1280
1281        std::thread::sleep(Duration::from_millis(5));
1282        status.updated_at = Timestamp::now();
1283        status.polls = 3;
1284        write_status_to(&path, &status).unwrap();
1285        let second: Status =
1286            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
1287        assert!(
1288            second.updated_at > first.updated_at,
1289            "a reader can only detect staleness if the heartbeat moves"
1290        );
1291        assert_eq!(
1292            second.started_at, first.started_at,
1293            "the start time is not a heartbeat"
1294        );
1295        assert_eq!(second.polls, 3);
1296    }
1297
1298    #[test]
1299    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
1300        let dir = tempfile::tempdir().unwrap();
1301
1302        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
1303
1304        let mut status = Status::new();
1305        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
1306        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1307        let stale = read_status(dir.path()).unwrap();
1308        assert!(
1309            !stale.running(Timestamp::now()),
1310            "a minute without a heartbeat is a dead daemon, not a busy one"
1311        );
1312        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
1313
1314        status.updated_at = Timestamp::now();
1315        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1316        let fresh = read_status(dir.path()).unwrap();
1317        assert!(fresh.running(Timestamp::now()));
1318    }
1319
1320    #[test]
1321    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
1322        let dir = tempfile::tempdir().unwrap();
1323        let now = Timestamp::now();
1324        let mine = "20260903-080619-01c2";
1325
1326        assert!(
1327            !is_working_on(dir.path(), mine, now),
1328            "no status file means nobody is working on anything"
1329        );
1330
1331        let mut status = Status::new();
1332        status.current = Some(Current {
1333            task: "20260903-080340-0167".to_owned(),
1334            run: mine.to_owned(),
1335        });
1336        status.updated_at = now;
1337        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1338        assert!(is_working_on(dir.path(), mine, now));
1339        assert!(
1340            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
1341            "a daemon busy with one run is not working on another"
1342        );
1343
1344        // A killed daemon stops writing heartbeats but leaves the file behind
1345        // naming the run it died in. That run must not be undeletable forever.
1346        status.updated_at = now - jiff::SignedDuration::from_secs(600);
1347        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
1348        assert!(
1349            !is_working_on(dir.path(), mine, now),
1350            "a stale heartbeat is a dead daemon, so its run is a leftover"
1351        );
1352    }
1353
1354    #[test]
1355    fn a_newer_status_file_still_yields_a_reading() {
1356        let dir = tempfile::tempdir().unwrap();
1357        // A field this build has never heard of must not turn the reading into
1358        // nothing at all; that is the whole reason the reader is permissive.
1359        std::fs::write(
1360            dir.path().join("daemon.json"),
1361            serde_json::json!({
1362                "schema": 2,
1363                "updated_at": Timestamp::now().to_string(),
1364                "idle": true,
1365                "surprise": { "nested": [1, 2, 3] },
1366            })
1367            .to_string(),
1368        )
1369        .unwrap();
1370
1371        let reading = read_status(dir.path()).expect("a forward-compatible read");
1372        assert!(reading.running(Timestamp::now()));
1373        assert!(reading.idle);
1374        assert_eq!(reading.current, None);
1375    }
1376
1377    #[test]
1378    fn a_task_without_a_repository_runs_in_the_daemons_default() {
1379        let fallback = Path::new("/default");
1380        let mut blank = task();
1381        blank.repo = PathBuf::new();
1382        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
1383        let mut dot = task();
1384        dot.repo = PathBuf::from(".");
1385        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
1386        assert_eq!(
1387            repo_for(&task(), fallback),
1388            PathBuf::from("/repo"),
1389            "a task that names a repository keeps it"
1390        );
1391    }
1392
1393    #[test]
1394    fn merge_overrides_are_parsed_or_refused() {
1395        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
1396        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
1397        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
1398        assert!(merge_mode("squash").is_err());
1399    }
1400
1401    /// A loop whose queue lives in a temp tree and whose poll interval is far
1402    /// longer than the test's patience, so anything that waits out a poll
1403    /// instead of noticing the stop fails rather than merely being slow.
1404    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf) {
1405        let opts = Opts {
1406            poll: Duration::from_secs(30),
1407            ..Opts::default()
1408        };
1409        // The status file goes in a directory that does not exist yet, so its
1410        // creation is itself evidence the loop published one.
1411        (
1412            opts,
1413            Queue::at(dir.join("queue")),
1414            dir.join("home").join("daemon.json"),
1415        )
1416    }
1417
1418    #[test]
1419    fn a_stop_is_idempotent_and_once_set_stays_set() {
1420        let stop = Stop::new();
1421        assert!(!stop.stopped());
1422
1423        stop.stop();
1424        assert!(stop.stopped());
1425        stop.stop();
1426        assert!(stop.stopped(), "a second stop is not a toggle");
1427
1428        let shared = stop.clone();
1429        assert!(
1430            shared.stopped(),
1431            "a clone is the same stop; that is how the loop and its caller share one"
1432        );
1433    }
1434
1435    #[test]
1436    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
1437        let stop = Stop::new();
1438        stop.busy(true);
1439        assert!(
1440            !stop.finishing(),
1441            "a busy loop nobody has asked to stop is just running"
1442        );
1443
1444        stop.stop();
1445        assert!(
1446            stop.finishing(),
1447            "a stop asked for mid-run has not landed until the run is settled"
1448        );
1449
1450        stop.busy(false);
1451        assert!(
1452            !stop.finishing(),
1453            "once the run is settled the stop has landed and there is nothing to finish"
1454        );
1455    }
1456
1457    #[tokio::test]
1458    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
1459        let dir = tempfile::tempdir().unwrap();
1460        let (opts, queue, status_file) = idle_loop(dir.path());
1461        let stop = Stop::new();
1462        stop.stop();
1463
1464        let began = std::time::Instant::now();
1465        tokio::time::timeout(
1466            Duration::from_secs(2),
1467            drive(&opts, &queue, &status_file, &stop),
1468        )
1469        .await
1470        .expect("a stopped loop must return, not sit out its poll interval")
1471        .expect("the loop's own setup and teardown must not fail");
1472        assert!(
1473            began.elapsed() < opts.poll,
1474            "returned only after {:?}, which is a poll interval, not a stop",
1475            began.elapsed()
1476        );
1477    }
1478
1479    #[tokio::test]
1480    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
1481        let dir = tempfile::tempdir().unwrap();
1482        let (opts, queue, status_file) = idle_loop(dir.path());
1483        let stop = Stop::new();
1484
1485        // Asked for after the loop is already parked on its empty queue, which
1486        // is the case an operator tapping stop on a phone actually hits.
1487        let asker = {
1488            let stop = stop.clone();
1489            tokio::spawn(async move {
1490                tokio::time::sleep(Duration::from_millis(20)).await;
1491                stop.stop();
1492            })
1493        };
1494
1495        let began = std::time::Instant::now();
1496        tokio::time::timeout(
1497            Duration::from_secs(2),
1498            drive(&opts, &queue, &status_file, &stop),
1499        )
1500        .await
1501        .expect("a stop asked for while idle must wake the wait")
1502        .expect("the loop's own setup and teardown must not fail");
1503        asker.await.unwrap();
1504        assert!(
1505            began.elapsed() < opts.poll,
1506            "returned only after {:?}, so the stop waited on the sleep",
1507            began.elapsed()
1508        );
1509    }
1510
1511    #[tokio::test]
1512    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
1513        let dir = tempfile::tempdir().unwrap();
1514        let (opts, queue, status_file) = idle_loop(dir.path());
1515        let home = status_file.parent().unwrap().to_path_buf();
1516        let stop = Stop::new();
1517        stop.stop();
1518
1519        tokio::time::timeout(
1520            Duration::from_secs(2),
1521            drive(&opts, &queue, &status_file, &stop),
1522        )
1523        .await
1524        .expect("a stopped loop must return")
1525        .expect("the loop's own setup and teardown must not fail");
1526
1527        assert!(
1528            home.is_dir(),
1529            "the loop did publish a status file, so its removal is the teardown and not an absence"
1530        );
1531        assert!(
1532            !status_file.exists(),
1533            "a stopped loop clears its status file"
1534        );
1535        assert!(
1536            read_status(&home).is_none(),
1537            "a reader must see no daemon at all, not a heartbeat that merely stopped"
1538        );
1539    }
1540}