Skip to main content

magi/
queue.rs

1//! The task queue: what magi should do next, and who asked for it.
2//!
3//! The queue is what lets magi run unattended. `magi serve` takes the next
4//! task, runs the graph on it, records the outcome, and takes the next one.
5//!
6//! It is also the reason an agent can ask for work. `magi task add` is the
7//! whole interface, and it is the same command whether a human types it at a
8//! prompt, a phone posts it through the web UI, or an implementer inside a run
9//! shells out to it because it noticed something worth doing but out of scope.
10//! magi's CLI is the operating surface for both kinds of user; the queue is
11//! where their intentions meet.
12//!
13//! One task is one JSON file under [`Queue`]'s root. Files rather than a
14//! database because the operator has to be able to read, edit, and delete the
15//! backlog with the tools already on the machine, and because a crashed daemon
16//! must leave a queue the next one can pick up without recovery ceremony.
17//!
18//! # Shape
19//!
20//! [`Task`] is data plus *pure* state transitions - [`Task::fail`] decides
21//! whether an attempt was the last one, and touches no disk. [`Queue`] owns all
22//! I/O and is constructed with its root, so a test drives a real queue in a
23//! temp directory without setting a process-global home. Splitting them this
24//! way is why the retry policy below can be asserted directly.
25//!
26//! # Bounded by construction
27//!
28//! An autonomous loop that retries forever is a way to spend money on a task
29//! that cannot succeed. Every claim increments [`Task::attempts`]; a task that
30//! has burned its attempts becomes [`TaskStatus::Held`] and waits for a human
31//! rather than for another agent.
32
33use std::collections::HashMap;
34use std::path::{Path, PathBuf};
35
36use anyhow::{Context, Result, bail};
37use jiff::Timestamp;
38use serde::{Deserialize, Serialize};
39
40use crate::ask::Questions;
41
42/// On-disk format for a queued task. Bumped when a field's meaning changes.
43///
44/// 6: added [`Task::resume_override`] (a field only; `#[serde(default)]`, so
45/// an older record reads as `None` and [`read_path`] still accepts it).
46///
47/// 5: added [`Task::triage_applied`], the ids of triage questions whose
48/// answer has already been applied to this task. A "resume" answer used to
49/// leave no trace ([`Task::release`] clears [`Task::hold_reason`], which was
50/// the only place the applied marker lived), so when the released task failed
51/// its attempts and went back to `held`, the next idle pass found the same
52/// answered question "not applied" and released it again with `attempts` reset
53/// to 0 - the `max_attempts` bound never held. `#[serde(default)]` so an older
54/// record reads as empty. A task already looping when this build arrives has
55/// no record, so it is released once more, recorded, and then stays held.
56///
57/// 4: added [`Task::blocked_from`], the status a task had the moment it
58/// became [`TaskStatus::Blocked`], so [`Task::unblock`] restores it instead
59/// of always landing on [`TaskStatus::Queued`]. Without it, a task a human
60/// or `crate::triage` had deliberately left [`TaskStatus::Held`] — machine
61/// or manual — would lose that the instant `crate::conduct` blocked it on a
62/// follow-up question, and come back `Queued` the moment the question was
63/// answered, regardless of what the answer said: exactly the loop where a
64/// task the operator told to stay held instead re-enters the competition
65/// queue every time someone answers a question about it. `#[serde(default)]`
66/// so an older record reads as `None`; [`Task::unblock`] then falls back to
67/// inferring `Held` from surviving hold evidence ([`Task::hold_reason`] /
68/// [`Task::hold_source`], never cleared by [`Task::block`]) rather than
69/// guessing `Queued` outright — see [`Task::unblock`]'s own doc.
70///
71/// 3: added [`HoldSource`] so conductor recovery cannot release a hold an
72/// operator deliberately placed. Old records default to `None` and are
73/// protected as operator-held until an explicit release; the safe direction
74/// when their author was never recorded.
75///
76/// 2: added [`TaskStatus::Blocked`], [`Task::blocked_by`] and
77/// [`Task::block_reason`] (`crate::conduct`'s decisions) and
78/// [`Task::answers`] (operator answers carried forward to the next
79/// conductor prompt and the next run's instruction). All three are
80/// `#[serde(default)]`, so [`read_path`] accepts anything up to and
81/// including this schema rather than only an exact match — a task written
82/// by a build that only knew about schema 1 has nothing to say about
83/// blocking or answers, and defaulting those fields is exactly as good a
84/// reading as a value that build never had a chance to write.
85pub const SCHEMA: u32 = 6;
86
87/// Who placed the current hold.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum HoldSource {
91    /// An operator used the CLI or web UI.
92    Manual,
93    /// The daemon or conductor placed the hold as part of its own recovery.
94    Machine,
95}
96
97impl HoldSource {
98    /// Short human-facing label for reports and the CLI.
99    pub fn label(self) -> &'static str {
100        match self {
101            Self::Manual => "manual",
102            Self::Machine => "machine",
103        }
104    }
105}
106
107/// Where a task came from. Recorded because "who asked for this" is the first
108/// question about an autonomous run, and the answer is not recoverable later.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(tag = "kind", rename_all = "lowercase")]
111pub enum Source {
112    /// A person, at a terminal or through the web UI.
113    Human,
114    /// An agent inside a run, via `magi task add`. Both ids are recorded so a
115    /// task can be traced back to the exact seat that asked for it.
116    Agent {
117        /// Run the asking agent belonged to.
118        run: String,
119        /// Node it was working in, e.g. `implement` or `review`.
120        node: String,
121    },
122    /// A GitHub issue, imported by number.
123    Issue {
124        /// Issue number.
125        number: u64,
126        /// `owner/repo`, as `gh` reports it.
127        repo: String,
128    },
129}
130
131impl Source {
132    /// Short human-facing label, for lists and the web UI.
133    pub fn label(&self) -> String {
134        match self {
135            Self::Human => "human".to_owned(),
136            Self::Agent { run, node } => format!("{node}@{}", short(run)),
137            Self::Issue { number, .. } => format!("issue #{number}"),
138        }
139    }
140}
141
142/// Where a task is in its life.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
144#[serde(rename_all = "lowercase")]
145pub enum TaskStatus {
146    /// Waiting to be claimed.
147    Queued,
148    /// Claimed by a daemon; a run is in flight.
149    Running,
150    /// A run finished and its gate passed.
151    Done,
152    /// A run finished without passing, and attempts remain.
153    Failed,
154    /// Out of attempts, or held by hand. The loop will not pick it up.
155    Held,
156    /// Waiting on another task or an unanswered question. See
157    /// [`Task::blocked_by`]. Set and cleared by `crate::conduct` and
158    /// `crate::daemon`'s deterministic resolver, never by hand.
159    Blocked,
160}
161
162impl TaskStatus {
163    /// Is this task eligible for a daemon to claim?
164    pub fn runnable(self) -> bool {
165        matches!(self, Self::Queued | Self::Failed)
166    }
167
168    /// Lowercase name, as it appears on disk and in the API.
169    pub fn as_str(self) -> &'static str {
170        match self {
171            Self::Queued => "queued",
172            Self::Running => "running",
173            Self::Done => "done",
174            Self::Failed => "failed",
175            Self::Held => "held",
176            Self::Blocked => "blocked",
177        }
178    }
179}
180
181/// One unit of work.
182#[derive(Debug, Clone, Serialize, Deserialize)]
183#[serde(deny_unknown_fields)]
184pub struct Task {
185    /// On-disk format version.
186    pub schema: u32,
187    /// Task id, e.g. `20260902-140501-a1b2`.
188    pub id: String,
189    /// One line, for lists and notifications.
190    pub title: String,
191    /// The task itself, handed to the graph verbatim.
192    pub instruction: String,
193    /// Repository to work in.
194    pub repo: PathBuf,
195    /// Who asked.
196    pub source: Source,
197    /// Higher runs first; ties break oldest-first so nothing starves.
198    #[serde(default)]
199    pub priority: i32,
200    /// Run this task alone: one implementer, no panel of judges to convince.
201    ///
202    /// `#[serde(default)]` so a queue file written before this field existed
203    /// still reads, as `false` - the ordinary multi-candidate competition,
204    /// unchanged. A task set to `solo` still runs the whole graph; only the
205    /// candidate count the daemon builds it with changes, and
206    /// [`crate::graph::Runner`] already collapses a single-candidate run to
207    /// implement → review → gate → merge on its own (see
208    /// [`crate::graph::Runner::review`]'s doc), so nothing about judging,
209    /// deliberation or voting had to change to support this.
210    #[serde(default)]
211    pub solo: bool,
212    /// Current state.
213    pub status: TaskStatus,
214    /// How many times this task has been claimed.
215    #[serde(default)]
216    pub attempts: usize,
217    /// Runs this task has produced, oldest first.
218    #[serde(default)]
219    pub runs: Vec<String>,
220    /// Why the last attempt did not land.
221    #[serde(default)]
222    pub last_error: Option<String>,
223    /// What a human hold is waiting on.
224    ///
225    /// `None` covers both the ordinary cases: a hold the loop makes itself
226    /// (out of attempts, or the disk gate closed) explains itself through
227    /// [`Task::last_error`] instead, and a human hold nobody bothered to
228    /// explain is still a valid hold. The queue has no way to express a
229    /// dependency between two tasks, so on the occasions a hold really is
230    /// "wait for that other task first", this is the only place that reason
231    /// survives - see [`Task::hold_manual`] and [`Task::release`].
232    ///
233    /// `#[serde(default)]` so a queue file written before this field existed
234    /// still reads, with no reason recorded rather than a parse error.
235    #[serde(default)]
236    pub hold_reason: Option<String>,
237    /// Who placed [`Task::hold_reason`].  `None` is a compatible old record;
238    /// see [`Task::operator_held`] for its deliberately conservative meaning.
239    #[serde(default)]
240    pub hold_source: Option<HoldSource>,
241    /// Diagnostic detail excerpted from the run that led to a hold - what a
242    /// human would have found opening `artifacts/` by hand, not the one-line
243    /// reason in [`Task::last_error`]. Set only when a run's own attempts are
244    /// exhausted and the task becomes [`TaskStatus::Held`]; `daemon` computes
245    /// it from the run's own record, since this module has no notion of a
246    /// run's internals. Bounded in length by the writer - see
247    /// `daemon::diagnostic` - so a verbose run cannot make this file grow
248    /// without limit.
249    ///
250    /// `#[serde(default)]` so a queue file written before this field existed
251    /// still reads, with no diagnostic recorded rather than a parse error.
252    #[serde(default)]
253    pub diagnostic: Option<String>,
254    /// What this task is waiting on: other task ids, unanswered
255    /// `crate::ask::Question` ids, or both. Non-empty exactly when
256    /// [`TaskStatus::Blocked`]; emptying it — see [`Task::unblock`] — is what
257    /// puts the task back at [`TaskStatus::Queued`].
258    ///
259    /// Set by `crate::conduct`'s decisions and cleared deterministically by
260    /// `crate::daemon` as each dependency resolves, never by a person. Never
261    /// `#[serde(default)]` is skipped: a queue file from before this field
262    /// existed has nothing to report here, and an empty list is exactly that.
263    #[serde(default)]
264    pub blocked_by: Vec<String>,
265    /// One line explaining the current [`Task::blocked_by`], written by
266    /// `crate::conduct`. Cleared whenever `blocked_by` empties.
267    #[serde(default)]
268    pub block_reason: Option<String>,
269    /// The status this task had the moment [`Task::block`] most recently
270    /// moved it to [`TaskStatus::Blocked`] — what [`Task::unblock`] restores
271    /// once nothing is left in `blocked_by`, instead of always landing on
272    /// [`TaskStatus::Queued`]. See [`SCHEMA`]'s doc for schema 4 on why this
273    /// exists: an answer to a question `crate::conduct` filed about a
274    /// [`TaskStatus::Held`] task must not itself be what puts the task back
275    /// in the competition queue.
276    ///
277    /// `#[serde(default)]` so a queue file written before this field existed
278    /// reads as `None`; [`Task::unblock`] treats that the same as a task
279    /// blocked straight from `Queued`, unless surviving hold evidence says
280    /// otherwise.
281    #[serde(default)]
282    pub blocked_from: Option<TaskStatus>,
283    /// Questions `crate::conduct` asked about this task that the operator has
284    /// since answered, oldest first — what was asked, and what they said.
285    ///
286    /// A blocking question's id leaves [`Task::blocked_by`] the moment
287    /// [`crate::ask::QuestionStatus::Answered`] is observed, but the id alone
288    /// tells nobody what was decided. This is what carries the answer's
289    /// *content* forward: into the next conductor prompt for this task, and
290    /// into the instruction handed to the next run — see `crate::daemon`'s
291    /// deterministic blocker resolution. Kept for the task's whole life, the
292    /// same as [`Task::runs`]: a release resets attempts, not evidence.
293    #[serde(default)]
294    pub answers: Vec<AnsweredQuestion>,
295    /// Ids of the `crate::triage` questions whose answer has been applied to
296    /// this task. Unlike [`Task::hold_reason`], [`Task::release`] and every
297    /// hold transition leave it alone, so an answer is applied at most once
298    /// however many times the task is held again. See [`SCHEMA`]'s doc for
299    /// schema 5. `#[serde(default)]` so an older record reads as empty.
300    #[serde(default)]
301    pub triage_applied: Vec<String>,
302    /// The operator's "resume" answer to a triage question, kept until the
303    /// task actually runs (or is done) so `crate::conduct` cannot silently
304    /// undo it and `crate::triage` can tell that a hold it sees now came
305    /// *after* the answer. See [`OperatorResume`]. `#[serde(default)]`.
306    #[serde(default)]
307    pub resume_override: Option<OperatorResume>,
308    /// Set by `crate::conduct` when it chooses `Review` recovery for a task
309    /// whose branch survived a blocked run: the branch to reopen with
310    /// `crate::graph::Runner::review` instead of competing from scratch.
311    ///
312    /// Requeues the task the same way [`Task::release`] does, so it is
313    /// picked up by the ordinary loop; `crate::daemon` reads this field once,
314    /// when it actually starts the run, and clears it either way — consumed
315    /// on success, dropped if the branch no longer exists by then. Never set
316    /// from the conductor's own words: `crate::daemon` derives the branch
317    /// name itself from the task's last run, so a hallucinated branch can
318    /// never reach here.
319    #[serde(default)]
320    pub review_branch: Option<String>,
321    /// A release deliberately starts a new competition instead of resuming
322    /// the prior run. History remains as evidence in `runs`.
323    #[serde(default)]
324    pub fresh_start: bool,
325    /// Marked by an operator (`magi task interrupt`) to ask `magi serve` to
326    /// run this one ahead of whatever it already has in flight, once
327    /// `[daemon] pause_for_interrupts` is on - see
328    /// `crate::daemon::advance_interrupt`. Never set by the loop itself, and
329    /// deliberately a different operation from [`Task::set_priority`]: a
330    /// priority only reorders the queue a claim has not reached yet, while
331    /// this asks a run already in flight to park at its next safe boundary
332    /// and step aside. `#[serde(default)]` so a queue file written before
333    /// this field existed still reads, as `false` - no task interrupts
334    /// anything unless asked to, exactly as before.
335    #[serde(default)]
336    pub interrupt: bool,
337    /// Marked by `magi task add --urgent`: `crate::daemon::poll` dispatches
338    /// this task through its own one-slot `urgent_sem` the moment it is
339    /// runnable, in addition to whatever is already running under the
340    /// ordinary `[daemon] max_concurrent_runs` pool - never instead of it,
341    /// and never by pausing or otherwise touching that run. This is the
342    /// opposite direction from [`Task::interrupt`]: that one asks a run
343    /// already in flight to step aside; this one never asks anything to
344    /// step aside, it only spends one additional, temporary concurrency
345    /// slot. The two are independent and may both be set on the same task,
346    /// but this exemption stops at `[daemon] pause_for_interrupts`'s own
347    /// park/resume handoff (75dd): while an interrupt sequence is actively
348    /// parking, running, or resuming - its own, or an unrelated task's -
349    /// `crate::daemon::interrupt_gate` withholds an urgent candidate exactly
350    /// like an ordinary one, never exempted. 75dd's "at most one run, ever,
351    /// at once" guarantee takes precedence, because the alternative is a run
352    /// still genuinely in flight (only *asked* to park, not yet gone) ending
353    /// up alongside a second one this feature let through - the very thing
354    /// that guarantee exists to rule out.
355    ///
356    /// `#[serde(default)]` so a queue file written before this field existed
357    /// still reads, as `false` - no task claims the urgent slot unless asked
358    /// to, exactly as before.
359    #[serde(default)]
360    pub urgent: bool,
361    /// When the task was filed.
362    pub created_at: Timestamp,
363    /// Last change to this file.
364    pub updated_at: Timestamp,
365}
366
367/// A triage "resume" answer and what became of it. See
368/// [`Task::resume_override`].
369#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
370pub struct OperatorResume {
371    /// The triage question the operator answered.
372    pub question_id: String,
373    /// When the answer was applied.
374    pub at: Timestamp,
375    /// The reason `crate::conduct` gave for holding the task again after the
376    /// answer, if it did. The conductor may do this once.
377    #[serde(default)]
378    pub conductor_rehold: Option<String>,
379    /// The operator answered "resume" a second time, to the question about
380    /// that contradiction: the conductor may no longer hold this task.
381    #[serde(default)]
382    pub forced: bool,
383}
384
385/// One question `crate::conduct` asked about a task, and what the operator
386/// said back. See [`Task::answers`].
387#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
388pub struct AnsweredQuestion {
389    /// The question as asked, e.g. [`crate::ask::Question::summary`].
390    pub question: String,
391    /// What the operator answered.
392    pub answer: String,
393}
394
395impl Task {
396    /// File a new task. Persist it with [`Queue::put`].
397    pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
398        let now = Timestamp::now();
399        Self {
400            schema: SCHEMA,
401            id: new_id(),
402            title,
403            instruction,
404            repo,
405            source,
406            priority: 0,
407            solo: false,
408            status: TaskStatus::Queued,
409            attempts: 0,
410            runs: Vec::new(),
411            last_error: None,
412            hold_reason: None,
413            hold_source: None,
414            diagnostic: None,
415            blocked_by: Vec::new(),
416            block_reason: None,
417            blocked_from: None,
418            answers: Vec::new(),
419            triage_applied: Vec::new(),
420            resume_override: None,
421            review_branch: None,
422            fresh_start: false,
423            interrupt: false,
424            urgent: false,
425            created_at: now,
426            updated_at: now,
427        }
428    }
429
430    /// Short form used in reports, matching a run's short id.
431    pub fn short(&self) -> &str {
432        short(&self.id)
433    }
434
435    /// Record that triage question `question_id`'s answer has been applied.
436    pub fn mark_triage_applied(&mut self, question_id: &str) {
437        if !self.triage_applied(question_id) {
438            self.triage_applied.push(question_id.to_owned());
439        }
440    }
441
442    /// Has triage question `question_id`'s answer already been applied?
443    pub fn triage_applied(&self, question_id: &str) -> bool {
444        self.triage_applied.iter().any(|id| id == question_id)
445    }
446
447    /// Record that a run has started for this task.
448    ///
449    /// Clears [`Task::interrupt`]: a mark to run ahead of whatever else is
450    /// in flight is fulfilled the moment this task actually gets its turn,
451    /// dispatched same as any other. Without this, a task whose run fails
452    /// and requeues - still `runnable`, still carrying the mark from its
453    /// first attempt - would keep re-triggering `crate::daemon`'s interrupt
454    /// scheduler and re-parking whatever it interrupted on every later
455    /// boundary, for as long as its attempts hold out, instead of the
456    /// one-shot "let this go next" the mark is meant to be.
457    pub fn start(&mut self, run: String) {
458        self.status = TaskStatus::Running;
459        self.attempts += 1;
460        self.runs.push(run);
461        self.last_error = None;
462        self.fresh_start = false;
463        self.interrupt = false;
464        // The answer has been honoured: the task got its turn.
465        self.resume_override = None;
466    }
467
468    /// Record a successful run.
469    ///
470    /// Both `magi task done` and `POST /api/queue/{id}/done` can close a held
471    /// *or blocked* task directly, with no release in between, so this clears
472    /// `hold_reason` and `blocked_by`/`block_reason` the same way
473    /// [`Task::release`] does. Otherwise a task held for "waiting on 3ed9", or
474    /// blocked on a dependency that never actually finished, and then closed
475    /// as done without ever being released would still read as waiting on
476    /// something in `magi task show` and on its card, after it no longer is.
477    pub fn succeed(&mut self) {
478        self.status = TaskStatus::Done;
479        self.resume_override = None;
480        self.last_error = None;
481        self.hold_reason = None;
482        self.hold_source = None;
483        self.diagnostic = None;
484        self.blocked_by.clear();
485        self.block_reason = None;
486        self.blocked_from = None;
487    }
488
489    /// Earlier attempts at this task that a later one has since made moot —
490    /// empty unless the task is [`TaskStatus::Done`] *and* `last_run_succeeded`
491    /// says `runs.last()` is actually why.
492    ///
493    /// `runs` is oldest first, and [`Task::start`] is the only thing that
494    /// pushes to it, always right before the attempt it names either succeeds
495    /// or fails; `succeed` itself never touches `runs`. So whenever `status`
496    /// is `Done` *because* the loop itself saw that last attempt land
497    /// (`Merged`/`Ready`), everything before it in the same list is a retry
498    /// this task no longer needs. But `succeed` is also reachable directly —
499    /// `magi task done`, the web UI's equivalent, and the conductor's
500    /// `Recovery::Done` all call it on a task in *any* status, including one
501    /// whose last recorded attempt never landed at all (closed by hand after
502    /// a merge magi's own loop never saw). `runs.last()` alone cannot tell
503    /// those two cases apart — that requires the caller to have actually
504    /// looked at that run's own `status`, which this module has no way to
505    /// do — so `last_run_succeeded` is the caller's answer to exactly that
506    /// question, not something this function can derive from `Task` alone.
507    ///
508    /// Deliberately narrower than [`Queue::superseded`]'s "every earlier
509    /// attempt has a later one" walk, which fires the moment a retry starts
510    /// even though the retry itself might still fail: that reading is right
511    /// for the web UI's "a newer attempt exists, go look at that one
512    /// instead" note, but wrong for deciding a run no longer needs a human's
513    /// attention, which is only true once the task's story has actually
514    /// ended well. Two Blocked runs sitting side by side while a third
515    /// attempt is still in flight must not be touched by this — see
516    /// `daemon::supersede_prior_runs`, the caller that turns this list into
517    /// rewritten `run.json` files.
518    pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
519        if self.status != TaskStatus::Done || !last_run_succeeded || self.runs.len() < 2 {
520            return &[];
521        }
522        &self.runs[..self.runs.len() - 1]
523    }
524
525    /// Record a failed attempt. Out of attempts means held for a human, rather
526    /// than retried until the money runs out.
527    ///
528    /// Clears [`Task::diagnostic`] unconditionally: it belongs to whatever run
529    /// produced it, and a caller that has one for *this* attempt sets it
530    /// itself right after calling this, once it knows the task actually ended
531    /// up [`TaskStatus::Held`] - see `daemon::diagnostic`. Without the clear, a
532    /// task released after a diagnosed hold and then failed again for an
533    /// unrelated, undiagnosed reason (a config error, say) would go on
534    /// showing the previous run's diagnostic as if it explained the new one.
535    pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
536        self.last_error = Some(why.into());
537        self.diagnostic = None;
538        self.status = if self.attempts >= max_attempts {
539            self.hold_source = Some(HoldSource::Machine);
540            TaskStatus::Held
541        } else {
542            TaskStatus::Failed
543        };
544    }
545
546    /// Record an attempt that failed for a reason the task is not responsible
547    /// for - the agent CLIs ran out of quota and the judging panel collapsed.
548    ///
549    /// This refunds the attempt on purpose. A quota window closing at 4am must
550    /// not spend the backlog's retry budget: the operator would come back to a
551    /// queue of held tasks that were never actually judged, and would have to
552    /// release every one by hand to find out which had a real problem. The task
553    /// goes back to `Failed`, which the loop retries, so a reset quota picks the
554    /// work up where it stopped.
555    pub fn stall(&mut self, why: impl Into<String>) {
556        self.last_error = Some(why.into());
557        self.diagnostic = None;
558        self.attempts = self.attempts.saturating_sub(1);
559        self.status = TaskStatus::Failed;
560    }
561
562    /// Whether this held task may only be released by an operator.
563    ///
564    /// Old files did not record a source. Preserve every such hold rather
565    /// than guessing that it was automatic and risking duplicate work. New
566    /// automatic holds record [`HoldSource::Machine`] and remain recoverable.
567    pub fn operator_held(&self) -> bool {
568        self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
569    }
570
571    /// Take this task out of the loop's reach by an operator action.
572    ///
573    /// Clears `blocked_by`/`block_reason` unconditionally, the same as
574    /// [`Task::release`] and for the same reason its own comment already
575    /// gives: a human choosing to hold a *blocked* task overrides its wait
576    /// outright, the same as it overrides an ordinary hold. Without this, a
577    /// task held straight out of [`TaskStatus::Blocked`] - the web UI's "Hold"
578    /// button is reachable on a blocked task, same as "Mark done" - kept
579    /// reading as still waiting on a dependency it no longer had any claim on.
580    pub fn hold_manual(&mut self, reason: Option<String>) {
581        self.status = TaskStatus::Held;
582        if reason.is_some() {
583            self.hold_reason = reason;
584        }
585        self.hold_source = Some(HoldSource::Manual);
586        self.blocked_by.clear();
587        self.block_reason = None;
588        self.blocked_from = None;
589    }
590
591    /// Take this task out of the loop's reach during automatic recovery.
592    ///
593    /// Clears `blocked_by`/`block_reason` for the same reason
594    /// [`Task::hold_manual`] does.
595    pub fn hold_machine(&mut self, reason: Option<String>) {
596        self.status = TaskStatus::Held;
597        if reason.is_some() {
598            self.hold_reason = reason;
599        }
600        self.hold_source = Some(HoldSource::Machine);
601        self.blocked_by.clear();
602        self.block_reason = None;
603        self.blocked_from = None;
604    }
605
606    /// Block this task on other task ids and/or open question ids, chosen by
607    /// `crate::conduct`. Pure: the caller still owns writing it back with
608    /// [`Queue::put`].
609    ///
610    /// Records [`Task::blocked_from`] the first time this moves the task into
611    /// [`TaskStatus::Blocked`], and leaves it alone on a later call that adds
612    /// or replaces `blocked_by` while the task is already `Blocked` - a
613    /// second question about an already-blocked task must not overwrite the
614    /// status it should eventually return to with `Blocked` itself.
615    pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
616        if self.status != TaskStatus::Blocked {
617            self.blocked_from = Some(self.status);
618        }
619        self.status = TaskStatus::Blocked;
620        self.blocked_by = blocked_by;
621        self.block_reason = reason;
622    }
623
624    /// Remove one resolved dependency (a task id that became [`TaskStatus::Done`],
625    /// or a question id that became [`crate::ask::QuestionStatus::Answered`]).
626    /// Once nothing is left in [`Task::blocked_by`], the task returns to
627    /// whatever [`Task::blocked_from`] recorded - deciding *why* a task was
628    /// blocked was `crate::conduct`'s job, but noticing a dependency resolved
629    /// needs no model at all, and restoring the status it interrupted needs
630    /// nothing more than what `block` already wrote down.
631    ///
632    /// A task blocked while `Running` restores to [`TaskStatus::Queued`]
633    /// instead: whatever process was running it is gone by the time this
634    /// runs, so there is nothing left to resume. A task with no recorded
635    /// `blocked_from` - a pre-schema-4 record, or one blocked before this
636    /// field existed - falls back to [`TaskStatus::Held`] when it still
637    /// carries hold evidence ([`Task::hold_reason`] or [`Task::hold_source`],
638    /// neither ever cleared by `block`), and to `Queued` otherwise: the same
639    /// choice `block` itself would have recorded, reconstructed from what
640    /// survived.
641    ///
642    /// A no-op, on purpose, for a task that is not [`TaskStatus::Blocked`]:
643    /// `crate::daemon`'s deterministic resolver runs over every task on every
644    /// poll, and a task that moved on for some other reason must not be
645    /// dragged back by a stale id it still happens to carry.
646    pub fn unblock(&mut self, resolved_id: &str) {
647        if self.status != TaskStatus::Blocked {
648            return;
649        }
650        self.blocked_by.retain(|id| id != resolved_id);
651        if self.blocked_by.is_empty() {
652            self.status = match self.blocked_from {
653                Some(TaskStatus::Running) => TaskStatus::Queued,
654                Some(other) => other,
655                None if self.hold_reason.is_some() || self.hold_source.is_some() => {
656                    TaskStatus::Held
657                }
658                None => TaskStatus::Queued,
659            };
660            self.block_reason = None;
661            self.blocked_from = None;
662        }
663    }
664
665    /// Record that a question `crate::conduct` asked about this task has been
666    /// answered, so the answer's content — not just the fact that the
667    /// question is gone — reaches the next conductor prompt and the next
668    /// run's instruction. See [`Task::answers`].
669    pub fn record_answer(&mut self, question: String, answer: String) {
670        self.answers.push(AnsweredQuestion { question, answer });
671    }
672
673    /// Requeue this task to reopen its last run as a review-only pass against
674    /// `branch` (`crate::graph::Runner::review`) rather than competing from
675    /// scratch. See [`Task::review_branch`].
676    pub fn request_review(&mut self, branch: String) {
677        self.release();
678        self.review_branch = Some(branch);
679    }
680
681    /// Requeue after a conductor chose a new competition. Unlike an ordinary
682    /// operator release, this deliberately does not resume the old run.
683    pub fn requeue(&mut self) {
684        self.release();
685        self.fresh_start = true;
686    }
687
688    /// Change how urgently this task should run next.
689    ///
690    /// Refused once the task is `running`: priority only feeds the sort
691    /// [`Queue::next_runnable`] does over tasks waiting to be claimed, and a
692    /// running task has already left that pool. Accepting the write anyway
693    /// would look like it worked while changing nothing until - and unless -
694    /// this attempt fails and the task becomes runnable again, which is a
695    /// surprise the phone should not hand back as a success.
696    pub fn set_priority(&mut self, priority: i32) -> Result<()> {
697        if self.status == TaskStatus::Running {
698            bail!(
699                "task {} is running; its priority cannot be changed until \
700                 this attempt finishes",
701                self.short()
702            );
703        }
704        self.priority = priority;
705        Ok(())
706    }
707
708    /// Mark (or unmark) this task to interrupt whatever `magi serve` already
709    /// has in flight, once `[daemon] pause_for_interrupts` is on. See
710    /// [`Task::interrupt`].
711    ///
712    /// Setting it is restricted to a task the loop could pick up on its own
713    /// right now - [`TaskStatus::runnable`] - for the same reason as
714    /// [`Task::set_priority`]: a task already `running` has been claimed, and
715    /// a task that is `done`, `held`, or `blocked` is not going to compete
716    /// for the daemon's attention regardless of this flag. Unlike priority,
717    /// this is never silently inert while `running` - it is refused outright,
718    /// because the entire feature this flag drives (`crate::daemon`'s
719    /// interrupt scheduler) is scoped to tasks still waiting to be claimed.
720    /// Clearing it back to `false` carries no such risk and is always
721    /// allowed, including on a task that moved on since it was set.
722    pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
723        if interrupt && !self.status.runnable() {
724            bail!(
725                "task {} is {}; only a queued or failed task can be marked \
726                 to interrupt",
727                self.short(),
728                self.status.as_str()
729            );
730        }
731        self.interrupt = interrupt;
732        Ok(())
733    }
734
735    /// Replace this task's title and instruction wholesale.
736    ///
737    /// Restricted to `queued` and `held`. A `running` task's instruction has
738    /// already been handed to the graph, so a run in flight and the file on
739    /// disk must not be allowed to disagree about what was asked; a `done` or
740    /// `failed` task is a record of what actually happened and editing it
741    /// after the fact would falsify that record. `id`, `created_at`,
742    /// `source`, and `runs` are left untouched on purpose - an edit stands in
743    /// for "delete and refile", and keeping the id, the timestamp, the
744    /// attribution, and the run history is the entire reason it exists
745    /// instead.
746    pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
747        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
748            bail!(
749                "task {} is {}; only a queued or held task's instruction can \
750                 be edited",
751                self.short(),
752                self.status.as_str()
753            );
754        }
755        self.title = title;
756        self.instruction = instruction;
757        Ok(())
758    }
759
760    /// Record a run that produced a pull request without merging it.
761    ///
762    /// The task is held rather than retried, and it costs no further attempt
763    /// either way. The work the task asked for exists: it is sitting on a
764    /// branch, in a pull request, waiting for CI or for a person. Retrying
765    /// would spend the whole competition budget a second time and then race a
766    /// second branch against the pull request the first one opened - which is
767    /// exactly what happened to run 01c2, whose finished and green pull request
768    /// was re-competed from scratch four seconds after it opened.
769    ///
770    /// A pull request nobody merged is a request for a person, not a failure.
771    pub fn handed_off(&mut self, why: impl Into<String>) {
772        self.last_error = Some(why.into());
773        self.diagnostic = None;
774        self.status = TaskStatus::Held;
775        self.hold_source = Some(HoldSource::Machine);
776    }
777
778    /// Put a held or finished task back in line, with its attempt count reset
779    /// so a release is a real second chance rather than an instant re-hold.
780    /// The run history is kept: attempts reset, evidence does not.
781    pub fn release(&mut self) {
782        self.status = TaskStatus::Queued;
783        self.attempts = 0;
784        self.last_error = None;
785        // Otherwise the next person who holds this task reads a reason that
786        // belonged to whatever it was waiting on last time.
787        self.hold_reason = None;
788        self.hold_source = None;
789        self.diagnostic = None;
790        // A release also un-blocks: the dependency or question `blocked_by`
791        // named may still be unresolved, but a human (or `crate::conduct`)
792        // choosing to release the task overrides that wait outright, the same
793        // as it overrides an ordinary hold.
794        self.blocked_by.clear();
795        self.block_reason = None;
796        self.blocked_from = None;
797        self.review_branch = None;
798        self.fresh_start = false;
799    }
800}
801
802/// A queue on disk.
803#[derive(Debug, Clone)]
804pub struct Queue {
805    root: PathBuf,
806}
807
808impl Queue {
809    /// The operator's queue, `<home>/queue`.
810    pub fn open() -> Self {
811        Self::at(crate::run::home().join("queue"))
812    }
813
814    /// A queue at an explicit root. Tests use this; so could an operator who
815    /// wants a queue per project.
816    pub fn at(root: PathBuf) -> Self {
817        Self { root }
818    }
819
820    /// Directory holding the task files.
821    pub fn root(&self) -> &Path {
822        &self.root
823    }
824
825    /// Path for one task id.
826    pub fn path_of(&self, id: &str) -> PathBuf {
827        self.root.join(format!("{id}.json"))
828    }
829
830    /// Write a task, atomically, so a daemon killed mid-write leaves the
831    /// previous state readable rather than a truncated file.
832    pub fn put(&self, task: &mut Task) -> Result<()> {
833        task.updated_at = Timestamp::now();
834        std::fs::create_dir_all(&self.root)
835            .with_context(|| format!("create {}", self.root.display()))?;
836        let body = serde_json::to_string_pretty(task).context("serialize task")?;
837        let path = self.path_of(&task.id);
838        let tmp = path.with_extension("json.tmp");
839        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
840        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
841        // A machine hold is news for the notification centre, filed beside
842        // this queue (`<home>/queue` -> `<home>/notifications`) rather than
843        // through a process-global, so a queue in a temp directory notifies
844        // into that directory.
845        if let (Some(notice), Some(home)) = (
846            crate::notices::task_held(task),
847            self.root.parent().filter(|p| !p.as_os_str().is_empty()),
848        ) {
849            crate::notices::raise_in(home, notice);
850        }
851        Ok(())
852    }
853
854    /// Load a task by id or unambiguous id prefix.
855    pub fn get(&self, id: &str) -> Result<Task> {
856        let resolved = self.resolve_id(id)?;
857        read_path(&self.path_of(&resolved))
858    }
859
860    /// Remove a task, and the claim lock that belongs to it.
861    ///
862    /// `in_flight` comes from the caller — a live daemon's heartbeat naming
863    /// this task — because the task's own `running` status cannot answer the
864    /// question. A daemon killed mid-competition leaves the status at
865    /// `running` and an orphaned `.lock` behind, and a guard that trusted
866    /// either would make the task undeletable for good: the phone showed
867    /// exactly that, refusing a task whose daemon had been gone for an hour.
868    ///
869    /// So the lock is removed with the task rather than respected. Any lock
870    /// still there once no live daemon claims the task is by definition stale,
871    /// and leaving it would make a deleted task look claimed to
872    /// [`Queue::claim`] and to whoever reads the directory.
873    ///
874    /// Anything still `blocked` on the id just deleted is quarantined to a
875    /// machine hold in the same call - see [`Removal::quarantined`] - rather
876    /// than left to wait on a dependency that no longer exists. Best-effort:
877    /// a dependent claimed by something else right now, or one whose write
878    /// fails, is simply left for `crate::daemon::resolve_blockers`'s own poll
879    /// (or `crate::triage::run_once`) to catch on its own next pass, and does
880    /// not fail this removal.
881    ///
882    /// `questions` is the store [`missing_blockers`] checks a `blocked_by` id
883    /// against before calling it gone - the same store the caller already
884    /// resolves `id`'s own home from, passed in rather than reopened here so
885    /// a test queue at an explicit root is never quarantined against the
886    /// operator's real questions directory.
887    pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
888        let resolved = self.resolve_id(id)?;
889        if in_flight {
890            bail!("task {resolved} is being run by a live daemon right now");
891        }
892        let path = self.path_of(&resolved);
893        std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
894        let lock = self.lock_path(&resolved);
895        if let Err(e) = std::fs::remove_file(&lock) {
896            if e.kind() != std::io::ErrorKind::NotFound {
897                return Err(e).with_context(|| format!("remove {}", lock.display()));
898            }
899        }
900        let quarantined = self.quarantine_dependents_of(&resolved, questions);
901        Ok(Removal {
902            id: resolved,
903            quarantined,
904        })
905    }
906
907    /// Move every `blocked` task naming `dependency` in its own `blocked_by`
908    /// to a machine hold, now that `dependency`'s own file is gone. See
909    /// [`Queue::remove`]'s own doc for why this is best-effort.
910    fn quarantine_dependents_of(&self, dependency: &str, questions: &Questions) -> Vec<String> {
911        let mut quarantined = Vec::new();
912        for listed in self.list() {
913            if listed.status != TaskStatus::Blocked
914                || !listed.blocked_by.iter().any(|b| b == dependency)
915            {
916                continue;
917            }
918            let Ok(_claim) = self.claim(&listed.id) else {
919                continue;
920            };
921            let Ok(mut task) = self.get(&listed.id) else {
922                continue;
923            };
924            if task.status != TaskStatus::Blocked
925                || !task.blocked_by.iter().any(|b| b == dependency)
926            {
927                continue;
928            }
929            let missing = missing_blockers(self, questions, &task.blocked_by);
930            task.hold_machine(Some(missing_blocker_hold_reason(
931                &task.blocked_by,
932                &missing,
933            )));
934            if self.put(&mut task).is_ok() {
935                quarantined.push(task.id.clone());
936            }
937        }
938        quarantined
939    }
940
941    /// Path of the claim lock for a task. One definition, so `claim` and
942    /// `remove` cannot end up naming different files.
943    fn lock_path(&self, id: &str) -> PathBuf {
944        self.root.join(format!("{id}.lock"))
945    }
946
947    /// Every task on disk, highest priority first and newest first within a
948    /// priority. This is what `magi task list` and `GET /api/queue` print, so
949    /// a raised priority has to move a task here the moment it is saved, not
950    /// only in [`Queue::next_runnable`]'s own ordering - the operator reading
951    /// the backlog and the loop about to drain it must agree on what "first"
952    /// means. Every existing task defaults to priority 0, so this is a no-op
953    /// change from the old newest-first order for a queue nobody has
954    /// reprioritised.
955    ///
956    /// Unreadable files are skipped rather than fatal: one corrupt task must
957    /// not take the queue - or the web UI, or an unattended daemon - down
958    /// with it.
959    pub fn list(&self) -> Vec<Task> {
960        let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
961            .into_iter()
962            .flatten()
963            .flatten()
964            .map(|e| e.path())
965            .filter(|p| p.extension().is_some_and(|x| x == "json"))
966            .filter_map(|p| read_path(&p).ok())
967            .collect();
968        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
969        tasks
970    }
971
972    /// Runs that a later attempt at the same task replaced, mapped to the id
973    /// of the attempt that replaced them.
974    ///
975    /// A task keeps its attempts in order, and the deck showed them as two
976    /// cards with the same title and no hint which was which: yukimemi asked
977    /// why `stalled` and `blocked` appeared twice for one task, and the
978    /// answer - "those are two tries, and the second one exists because of a
979    /// bug since fixed" - was not on the screen anywhere.
980    ///
981    /// Read from the queue rather than stored on the run, because the
982    /// ordering is the queue's fact: a `RunState` has no idea another attempt
983    /// happened after it.
984    pub fn superseded(&self) -> HashMap<String, String> {
985        let mut by = HashMap::new();
986        for task in self.list() {
987            for pair in task.runs.windows(2) {
988                if let [earlier, later] = pair {
989                    by.insert(earlier.clone(), later.clone());
990                }
991            }
992        }
993        by
994    }
995
996    /// Whether `run` is an earlier attempt a later one replaced, and if so
997    /// the id of that later attempt.
998    ///
999    /// Same walk as [`Queue::superseded`], narrowed to one run: a run detail
1000    /// page asks about exactly one run at a time, and this keeps that call
1001    /// site from building (and discarding) the whole map's `HashMap` just to
1002    /// read one entry out of it.
1003    pub fn superseded_by(&self, run: &str) -> Option<String> {
1004        for task in self.list() {
1005            if let Some(pos) = task.runs.iter().position(|r| r == run) {
1006                return task.runs.get(pos + 1).cloned();
1007            }
1008        }
1009        None
1010    }
1011
1012    /// The task's own most recent attempt, when `run` belongs to that task
1013    /// but is not already that attempt.
1014    ///
1015    /// Distinct from [`Queue::superseded_by`], which names only the very
1016    /// next attempt: a chain of retries (A superseded by B superseded by C)
1017    /// leaves an older run pointing at an intermediate one that may itself
1018    /// be unresolved, and a run's own detail page needs to know where the
1019    /// task's story currently stands - the chain's current head, C - not an
1020    /// attempt in the middle of it that a client would otherwise have to
1021    /// walk to by hand.
1022    pub fn latest_attempt(&self, run: &str) -> Option<String> {
1023        for task in self.list() {
1024            if task.runs.iter().any(|r| r == run) {
1025                return task.runs.last().filter(|last| **last != run).cloned();
1026            }
1027        }
1028        None
1029    }
1030
1031    /// The task a daemon should run next, or `None` when the queue is idle.
1032    ///
1033    /// Highest priority first, oldest first within a priority, so a burst of
1034    /// agent-filed work cannot starve the task a human filed this morning.
1035    pub fn next_runnable(&self) -> Option<Task> {
1036        let mut runnable: Vec<Task> = self
1037            .list()
1038            .into_iter()
1039            .filter(|t| t.status.runnable())
1040            .collect();
1041        runnable.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
1042        runnable.into_iter().next()
1043    }
1044
1045    /// Take exclusive ownership of a task.
1046    ///
1047    /// The lock is a `create_new` file next to the task, which is atomic on
1048    /// every platform magi targets. It exists so two daemons - or a daemon and
1049    /// a human running `magi run` - cannot drive one task into two competing
1050    /// runs. The returned guard releases on drop, including on panic.
1051    pub fn claim(&self, id: &str) -> Result<Claim> {
1052        std::fs::create_dir_all(&self.root)
1053            .with_context(|| format!("create {}", self.root.display()))?;
1054        let path = self.lock_path(id);
1055        match std::fs::OpenOptions::new()
1056            .write(true)
1057            .create_new(true)
1058            .open(&path)
1059        {
1060            Ok(mut f) => {
1061                use std::io::Write as _;
1062                // Best effort: the pid is for the human looking at a stale lock.
1063                let _ = writeln!(f, "{}", std::process::id());
1064                Ok(Claim { path })
1065            }
1066            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1067                bail!("task {id} is already claimed ({} exists)", path.display())
1068            }
1069            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
1070        }
1071    }
1072
1073    /// Expand an id prefix to exactly one task id.
1074    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1075        if self.path_of(prefix).is_file() {
1076            return Ok(prefix.to_owned());
1077        }
1078        let hits: Vec<String> = self
1079            .list()
1080            .into_iter()
1081            .map(|t| t.id)
1082            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1083            .collect();
1084        match hits.len() {
1085            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1086            0 => bail!("no task matches `{prefix}`"),
1087            _ => bail!(
1088                "`{prefix}` matches {} tasks: {}",
1089                hits.len(),
1090                hits.join(", ")
1091            ),
1092        }
1093    }
1094
1095    /// Change detection token for the queue.
1096    ///
1097    /// Combines file names and modification times of all task files in the
1098    /// queue, so adding, modifying, or deleting any task — even an older one —
1099    /// moves the revision and notifies connected clients via the change stream.
1100    /// Returns 0 when the queue is completely empty.
1101    pub fn revision(&self) -> u64 {
1102        use std::hash::{Hash as _, Hasher as _};
1103
1104        let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
1105            .into_iter()
1106            .flatten()
1107            .flatten()
1108            .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
1109            .filter_map(|e| {
1110                let name = e.file_name().to_string_lossy().into_owned();
1111                let mtime = e
1112                    .metadata()
1113                    .ok()?
1114                    .modified()
1115                    .ok()?
1116                    .duration_since(std::time::UNIX_EPOCH)
1117                    .ok()?
1118                    .as_millis() as u64;
1119                Some((name, mtime))
1120            })
1121            .collect();
1122
1123        if entries.is_empty() {
1124            return 0;
1125        }
1126
1127        entries.sort_unstable();
1128        let mut hasher = std::hash::DefaultHasher::new();
1129        for (name, mtime) in &entries {
1130            name.hash(&mut hasher);
1131            mtime.hash(&mut hasher);
1132        }
1133        let h = hasher.finish();
1134        if h == 0 { 1 } else { h }
1135    }
1136}
1137
1138/// What [`Queue::remove`] did, beyond deleting the named task's own file.
1139#[derive(Debug, Clone)]
1140pub struct Removal {
1141    /// The id actually removed - `id` expanded from a prefix, if it was one.
1142    pub id: String,
1143    /// Every `blocked` task that named [`Removal::id`] in its own
1144    /// `blocked_by` and was moved to a machine hold as a result, rather than
1145    /// left waiting on a dependency this call just erased.
1146    pub quarantined: Vec<String>,
1147}
1148
1149/// Exclusive ownership of a task, released on drop.
1150#[derive(Debug)]
1151pub struct Claim {
1152    path: PathBuf,
1153}
1154
1155impl Drop for Claim {
1156    fn drop(&mut self) {
1157        let _ = std::fs::remove_file(&self.path);
1158    }
1159}
1160
1161/// The first line of a task, trimmed to a title. Used when the caller gives a
1162/// body but no title, which is the normal case for an agent piping a file in.
1163pub fn title_from(instruction: &str, max: usize) -> String {
1164    // The first non-blank line, whatever it is. A markdown heading is the
1165    // task's own summary - agents pipe in `# Rework the config loader` and mean
1166    // exactly that - so it is preferred over the prose beneath it rather than
1167    // skipped as decoration. Leading list and heading markers are stripped
1168    // because they are syntax, not words.
1169    let line = instruction
1170        .lines()
1171        .map(str::trim)
1172        .find(|l| !l.is_empty())
1173        .unwrap_or("(empty task)")
1174        .trim_start_matches(['#', '-', '*', '>', ' '])
1175        .trim();
1176    if line.is_empty() {
1177        return "(empty task)".to_owned();
1178    }
1179    if line.chars().count() <= max {
1180        return line.to_owned();
1181    }
1182    let head: String = line.chars().take(max.saturating_sub(1)).collect();
1183    format!("{head}…")
1184}
1185
1186fn read_path(path: &Path) -> Result<Task> {
1187    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1188    let task: Task =
1189        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1190    // Greater-than, not not-equal: every field added since schema 1 carries
1191    // `#[serde(default)]`, so an older task has nothing to say about it and
1192    // defaulting is exactly as good a reading as a value that build never had
1193    // a chance to write. Only a schema *ahead* of this build - a meaning it
1194    // cannot possibly know - is refused rather than guessed at.
1195    if task.schema > SCHEMA {
1196        bail!(
1197            "task {} was written by a different magi (schema {}, this build \
1198             speaks {SCHEMA})",
1199            task.id,
1200            task.schema
1201        );
1202    }
1203    Ok(task)
1204}
1205
1206/// Ids inside a `blocked_by` list that name neither an existing task file nor
1207/// an existing question file - a dependency deleted (`magi task rm`, or by
1208/// hand) while something was still waiting on it.
1209///
1210/// Existence is decided by [`Queue::path_of`]/[`Questions::path_of`]
1211/// `is_file()` alone, never by [`Queue::get`]/[`Questions::get`] succeeding:
1212/// those also fail on a merely unreadable file - mid-write, corrupt, or from
1213/// a schema ahead of this build (see [`read_path`]) - and misreading "cannot
1214/// read it right now" as "it was deleted" would quarantine a task over a
1215/// transient failure. `blocked_by` always carries a full id, written by
1216/// `crate::conduct` or `crate::triage` from a real task's or question's own
1217/// `id`/`short`, never a prefix a caller typed - so the exact-path check is
1218/// complete on its own, with no [`Queue::resolve_id`] fallback needed.
1219pub fn missing_blockers(
1220    queue: &Queue,
1221    questions: &Questions,
1222    blocked_by: &[String],
1223) -> Vec<String> {
1224    blocked_by
1225        .iter()
1226        .filter(|id| !queue.path_of(id).is_file() && !questions.path_of(id).is_file())
1227        .cloned()
1228        .collect()
1229}
1230
1231/// The `hold_reason` text for a task quarantined because one or more of its
1232/// `blocked_by` ids no longer exist. Shared by `crate::daemon::resolve_blockers`,
1233/// `crate::triage::run_once`, and [`Queue::remove`]'s own dependent
1234/// quarantine, so the three call sites read as the same event to an operator
1235/// looking at `magi task show` rather than three different wordings for it.
1236///
1237/// Names the full original `blocked_by` list, not just `missing` - a task
1238/// quarantined here can also have named a dependency that was still
1239/// perfectly valid, and [`Task::hold_machine`] clears `blocked_by` on the way
1240/// in, so this text is the only place that information survives for an
1241/// operator deciding whether to release the task outright.
1242pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
1243    format!(
1244        "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
1245        blocked_by.join(", "),
1246        missing.join(", "),
1247    )
1248}
1249
1250fn short(id: &str) -> &str {
1251    id.split('-').next_back().unwrap_or(id)
1252}
1253
1254fn new_id() -> String {
1255    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1256    let seed = crate::rng::entropy();
1257    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1258}
1259
1260#[cfg(test)]
1261mod tests {
1262    use super::*;
1263
1264    #[test]
1265    fn triage_applied_survives_release_and_old_records_read_as_empty() {
1266        let mut t = Task::new(
1267            "t".to_owned(),
1268            "i".to_owned(),
1269            PathBuf::from("r"),
1270            Source::Human,
1271        );
1272        t.mark_triage_applied("q1");
1273        t.mark_triage_applied("q1");
1274        t.hold_machine(Some("x".to_owned()));
1275        t.release();
1276        assert_eq!(t.triage_applied, ["q1"]);
1277        assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
1278
1279        let mut v = serde_json::to_value(&t).unwrap();
1280        v.as_object_mut().unwrap().remove("triage_applied");
1281        let old: Task = serde_json::from_value(v).unwrap();
1282        assert!(old.triage_applied.is_empty());
1283    }
1284
1285    /// A queue of its own, with no process-global state - which is the point of
1286    /// `Queue::at`, and why these can run in parallel.
1287    fn queue() -> (tempfile::TempDir, Queue) {
1288        let dir = tempfile::tempdir().unwrap();
1289        let q = Queue::at(dir.path().join("queue"));
1290        (dir, q)
1291    }
1292
1293    #[test]
1294    fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
1295        let dir = tempfile::tempdir().unwrap();
1296        let q = Queue::at(dir.path().join("queue"));
1297        let mut t = task("held");
1298        q.put(&mut t).unwrap();
1299        assert_eq!(
1300            crate::notices::Notices::at(dir.path().join("notifications"))
1301                .list()
1302                .len(),
1303            0
1304        );
1305        t.hold_machine(Some("out of attempts".to_owned()));
1306        q.put(&mut t).unwrap();
1307        let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
1308        assert_eq!(listed.len(), 1);
1309        assert!(listed[0].message.contains("out of attempts"));
1310    }
1311
1312    fn task(title: &str) -> Task {
1313        Task::new(
1314            title.to_owned(),
1315            format!("do {title}"),
1316            PathBuf::from("."),
1317            Source::Human,
1318        )
1319    }
1320
1321    #[test]
1322    fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
1323        let (_dir, q) = queue();
1324        let mut t = task("retried");
1325        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1326        q.put(&mut t).unwrap();
1327
1328        assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
1329        assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
1330        assert_eq!(
1331            q.superseded_by("cccc"),
1332            None,
1333            "the latest attempt replaces nothing"
1334        );
1335        assert_eq!(
1336            q.superseded_by("never-heard-of-it"),
1337            None,
1338            "a run belonging to no task on this queue is not superseded"
1339        );
1340
1341        let mut by = HashMap::new();
1342        by.insert("aaaa".to_owned(), "bbbb".to_owned());
1343        by.insert("bbbb".to_owned(), "cccc".to_owned());
1344        assert_eq!(
1345            q.superseded(),
1346            by,
1347            "the whole-map and single-run forms must agree"
1348        );
1349    }
1350
1351    #[test]
1352    fn superseded_attempts_is_empty_until_the_task_is_done() {
1353        let mut t = task("retried");
1354        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
1355        t.status = TaskStatus::Failed;
1356        assert_eq!(
1357            t.superseded_attempts(true),
1358            &[] as &[String],
1359            "a task still retrying has no attempt yet that a later one made moot"
1360        );
1361
1362        t.status = TaskStatus::Running;
1363        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
1364    }
1365
1366    #[test]
1367    fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
1368        let mut t = task("retried");
1369        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1370        t.status = TaskStatus::Done;
1371        assert_eq!(
1372            t.superseded_attempts(true),
1373            &["aaaa".to_owned(), "bbbb".to_owned()],
1374            "cccc is the attempt whose success made the task done, and stays out"
1375        );
1376    }
1377
1378    #[test]
1379    fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
1380        let mut t = task("first try landed");
1381        t.runs = vec!["aaaa".to_owned()];
1382        t.status = TaskStatus::Done;
1383        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
1384    }
1385
1386    #[test]
1387    fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
1388        // `succeed` is reachable directly - `magi task done`, its web
1389        // equivalent, and the conductor's `Recovery::Done` - on a task in
1390        // any status, including one whose last recorded attempt is itself
1391        // `Blocked`/`Failed`/anything but `Merged`/`Ready`. `runs.last()`
1392        // alone cannot tell that apart from the loop's own settle path, so
1393        // the caller's own read of that run's status is what decides this.
1394        let mut t = task("closed by hand after a manual merge");
1395        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
1396        t.status = TaskStatus::Done;
1397        assert_eq!(
1398            t.superseded_attempts(false),
1399            &[] as &[String],
1400            "nothing here is provably why the task is done, so nothing is superseded"
1401        );
1402    }
1403
1404    #[test]
1405    fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
1406        let (_dir, q) = queue();
1407        let mut t = task("retried twice");
1408        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1409        q.put(&mut t).unwrap();
1410
1411        assert_eq!(
1412            q.latest_attempt("aaaa"),
1413            Some("cccc".to_owned()),
1414            "an old attempt points straight at the chain's current head, not the \
1415             next attempt in the middle of it"
1416        );
1417        assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
1418        assert_eq!(
1419            q.latest_attempt("cccc"),
1420            None,
1421            "the latest attempt is not superseded by anything"
1422        );
1423        assert_eq!(
1424            q.latest_attempt("never-heard-of-it"),
1425            None,
1426            "a run belonging to no task on this queue is not superseded"
1427        );
1428    }
1429
1430    #[test]
1431    fn a_markdown_heading_is_the_title_not_decoration() {
1432        // A task file's heading is the summary its author already wrote, so it
1433        // beats the prose underneath. Getting this backwards was visible in the
1434        // first smoke test: a task titled "# Rework the config loader" listed
1435        // as "It re-reads the file on every lookup".
1436        assert_eq!(
1437            title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
1438            "Rework the config loader"
1439        );
1440        assert_eq!(title_from("- fix the thing", 40), "fix the thing");
1441        assert_eq!(title_from("> quoted task", 40), "quoted task");
1442        // Nothing usable at all still has to produce something printable.
1443        assert_eq!(title_from("   \n\n", 40), "(empty task)");
1444        assert_eq!(title_from("###\n", 40), "(empty task)");
1445    }
1446
1447    #[test]
1448    fn a_long_title_is_elided_by_characters_not_bytes() {
1449        // Byte truncation would split a multi-byte character and panic.
1450        let long = "課題".repeat(30);
1451        let title = title_from(&long, 10);
1452        assert_eq!(title.chars().count(), 10);
1453        assert!(title.ends_with('…'));
1454    }
1455
1456    #[test]
1457    fn priority_wins_and_ties_break_oldest_first() {
1458        let (_dir, q) = queue();
1459        let mut a = task("first");
1460        let mut b = task("second");
1461        let mut c = task("urgent");
1462        // Ids carry a timestamp, so force a known order.
1463        a.id = "20260101-000001-aaaa".to_owned();
1464        b.id = "20260101-000002-bbbb".to_owned();
1465        c.id = "20260101-000003-cccc".to_owned();
1466        c.priority = 5;
1467        for t in [&mut a, &mut b, &mut c] {
1468            q.put(t).unwrap();
1469        }
1470
1471        // Priority first...
1472        assert_eq!(q.next_runnable().unwrap().id, c.id);
1473        c.hold_machine(None);
1474        q.put(&mut c).unwrap();
1475        // ...then oldest, so a burst of new work cannot starve older work.
1476        assert_eq!(q.next_runnable().unwrap().id, a.id);
1477        assert_eq!(q.list().len(), 3, "b is still waiting its turn");
1478    }
1479
1480    #[test]
1481    fn a_blocked_task_never_starves_another_runnable_one() {
1482        let (_dir, q) = queue();
1483        let mut blocked = task("blocked");
1484        blocked.block(vec!["something".to_owned()], None);
1485        q.put(&mut blocked).unwrap();
1486
1487        let mut runnable = task("free to go");
1488        q.put(&mut runnable).unwrap();
1489
1490        let next = q.next_runnable().expect("a runnable task is still offered");
1491        assert_eq!(next.id, runnable.id);
1492    }
1493
1494    #[test]
1495    fn a_held_task_is_never_offered_to_the_loop() {
1496        let (_dir, q) = queue();
1497        let mut t = task("held");
1498        q.put(&mut t).unwrap();
1499        assert!(q.next_runnable().is_some());
1500
1501        t.hold_machine(None);
1502        q.put(&mut t).unwrap();
1503        assert!(
1504            q.next_runnable().is_none(),
1505            "a held task must wait for a human"
1506        );
1507
1508        // A failed task, by contrast, is exactly what the loop should retry.
1509        t.status = TaskStatus::Failed;
1510        q.put(&mut t).unwrap();
1511        assert!(q.next_runnable().is_some());
1512    }
1513
1514    #[test]
1515    fn attempts_are_capped_and_then_the_task_is_held() {
1516        let mut t = task("doomed");
1517
1518        t.start("run-1".to_owned());
1519        t.fail("gate red", 2);
1520        assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
1521
1522        t.start("run-2".to_owned());
1523        t.fail("gate red", 2);
1524        assert_eq!(
1525            t.status,
1526            TaskStatus::Held,
1527            "out of attempts: stop spending money on it"
1528        );
1529        assert_eq!(t.runs, ["run-1", "run-2"]);
1530        assert_eq!(t.last_error.as_deref(), Some("gate red"));
1531    }
1532
1533    #[test]
1534    fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
1535        let mut t = task("stalled by quota");
1536
1537        t.start("run-1".to_owned());
1538        assert_eq!(t.attempts, 1);
1539        t.stall("judge-1, judge-2 out of quota");
1540        assert_eq!(
1541            t.attempts, 0,
1542            "a closed quota window must not spend the task's retry budget"
1543        );
1544        assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
1545        assert_eq!(
1546            t.last_error.as_deref(),
1547            Some("judge-1, judge-2 out of quota")
1548        );
1549
1550        // A task can therefore stall all night and still get its real attempts
1551        // once the quota resets - which is the whole point.
1552        for _ in 0..20 {
1553            t.start("run-n".to_owned());
1554            t.stall("still out of quota");
1555        }
1556        t.start("run-real".to_owned());
1557        t.fail("gate red", 2);
1558        assert_eq!(
1559            t.status,
1560            TaskStatus::Failed,
1561            "the first attempt that was really judged is attempt one"
1562        );
1563    }
1564
1565    #[test]
1566    fn releasing_a_held_task_gives_it_a_real_second_chance() {
1567        let mut t = task("retry me");
1568        t.start("run-1".to_owned());
1569        t.fail("gate red", 1);
1570        assert_eq!(t.status, TaskStatus::Held);
1571
1572        t.release();
1573        assert_eq!(t.status, TaskStatus::Queued);
1574        // Without resetting attempts the next failure would re-hold at once,
1575        // and a release would be a no-op the operator cannot see.
1576        assert_eq!(t.attempts, 0);
1577        assert!(t.last_error.is_none());
1578        assert_eq!(
1579            t.runs.len(),
1580            1,
1581            "history is kept: attempts reset, evidence does not"
1582        );
1583    }
1584
1585    #[test]
1586    fn a_hold_reason_survives_and_a_release_clears_it() {
1587        let mut t = task("waiting on something else");
1588        t.hold_manual(Some(
1589            "waiting for 20260101-000000-aaaa to land first".to_owned(),
1590        ));
1591        assert_eq!(t.status, TaskStatus::Held);
1592        assert_eq!(
1593            t.hold_reason.as_deref(),
1594            Some("waiting for 20260101-000000-aaaa to land first")
1595        );
1596
1597        // Holding again with no reason must not erase the one already there.
1598        t.hold_manual(None);
1599        assert_eq!(
1600            t.hold_reason.as_deref(),
1601            Some("waiting for 20260101-000000-aaaa to land first"),
1602            "a bare re-hold keeps whatever a human already wrote down"
1603        );
1604
1605        // A hold with no reason at all is still an ordinary, allowed hold.
1606        let mut plain = task("no reason given");
1607        plain.hold_manual(None);
1608        assert_eq!(plain.status, TaskStatus::Held);
1609        assert!(plain.hold_reason.is_none());
1610
1611        t.release();
1612        assert_eq!(t.status, TaskStatus::Queued);
1613        assert!(
1614            t.hold_reason.is_none(),
1615            "a stale reason must not greet the next person who holds this task"
1616        );
1617    }
1618
1619    #[test]
1620    fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
1621        // `done` can close a held task directly - neither `magi task done`
1622        // nor `POST /api/queue/{id}/done` requires a release first - so a
1623        // task held for "waiting on 3ed9" and then closed without ever being
1624        // released must not still read as waiting on it afterwards.
1625        let mut t = task("landed by hand while held");
1626        t.hold_manual(Some("waiting on 3ed9".to_owned()));
1627        assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
1628
1629        t.succeed();
1630        assert_eq!(t.status, TaskStatus::Done);
1631        assert!(
1632            t.hold_reason.is_none(),
1633            "a done task cannot still be waiting on something"
1634        );
1635    }
1636
1637    #[test]
1638    fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
1639        // The web UI's "Hold" and "Mark done" buttons are both reachable on a
1640        // `blocked` task, not just on `queued`/`held` ones - neither requires
1641        // a release first. A task moved off `Blocked` that way must not still
1642        // carry the dependency it was waiting on: a dependency graph built
1643        // from `blocked_by` would otherwise keep drawing an edge for a task
1644        // that is not blocked on anything any more.
1645        let mut held = task("held straight out of blocked");
1646        held.block(
1647            vec!["20260101-000000-dead".to_owned()],
1648            Some("waiting on the migration script".to_owned()),
1649        );
1650        assert_eq!(held.status, TaskStatus::Blocked);
1651
1652        held.hold_manual(None);
1653        assert_eq!(held.status, TaskStatus::Held);
1654        assert!(
1655            held.blocked_by.is_empty(),
1656            "hold overrides the wait, same as release"
1657        );
1658        assert!(held.block_reason.is_none());
1659
1660        let mut done = task("closed straight out of blocked");
1661        done.block(
1662            vec!["20260101-000000-dead".to_owned()],
1663            Some("waiting on the migration script".to_owned()),
1664        );
1665        done.succeed();
1666        assert_eq!(done.status, TaskStatus::Done);
1667        assert!(
1668            done.blocked_by.is_empty(),
1669            "a done task cannot still be waiting on a dependency"
1670        );
1671        assert!(done.block_reason.is_none());
1672    }
1673
1674    #[test]
1675    fn a_blocked_task_is_never_offered_to_the_loop() {
1676        let mut t = task("blocked");
1677        assert!(t.status.runnable());
1678        t.block(
1679            vec!["dep-id".to_owned()],
1680            Some("waits on dep-id".to_owned()),
1681        );
1682        assert_eq!(t.status, TaskStatus::Blocked);
1683        assert!(!t.status.runnable());
1684        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
1685    }
1686
1687    #[test]
1688    fn unblocking_the_last_dependency_returns_the_task_to_queued() {
1689        let mut t = task("blocked on two");
1690        t.block(
1691            vec!["a".to_owned(), "b".to_owned()],
1692            Some("waits on a and b".to_owned()),
1693        );
1694
1695        t.unblock("a");
1696        assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
1697        assert_eq!(t.blocked_by, ["b"]);
1698
1699        t.unblock("b");
1700        assert_eq!(t.status, TaskStatus::Queued);
1701        assert!(t.blocked_by.is_empty());
1702        assert!(t.block_reason.is_none());
1703    }
1704
1705    #[test]
1706    fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
1707        let mut t = task("never blocked");
1708        t.unblock("whatever");
1709        assert_eq!(t.status, TaskStatus::Queued);
1710    }
1711
1712    #[test]
1713    fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
1714        // The bug this guards: a task an operator (or `crate::triage`) has
1715        // deliberately held, once `crate::conduct` blocks it on a follow-up
1716        // question, must not silently re-enter the competition queue the
1717        // moment that question is answered - whatever the answer said.
1718        let mut t = task("held, then asked about");
1719        t.hold_machine(Some("out of attempts".to_owned()));
1720        assert_eq!(t.status, TaskStatus::Held);
1721
1722        t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
1723        assert_eq!(t.status, TaskStatus::Blocked);
1724
1725        t.record_answer("what now?".to_owned(), "leave it held".to_owned());
1726        t.unblock("q1");
1727        assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
1728        assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
1729        assert_eq!(t.hold_source, Some(HoldSource::Machine));
1730        assert!(t.blocked_from.is_none(), "consumed once restored");
1731    }
1732
1733    #[test]
1734    fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
1735        let mut t = task("manually held, then asked about");
1736        t.hold_manual(Some("waiting on a dependency".to_owned()));
1737
1738        t.block(vec!["q1".to_owned()], None);
1739        t.unblock("q1");
1740
1741        assert_eq!(t.status, TaskStatus::Held);
1742        assert_eq!(t.hold_source, Some(HoldSource::Manual));
1743    }
1744
1745    #[test]
1746    fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
1747        // A second `Task::block` call - `crate::conduct` adding a question on
1748        // top of an existing block - must not overwrite `blocked_from` with
1749        // `Blocked` itself, or the task would restore into itself.
1750        let mut t = task("held, blocked twice");
1751        t.hold_machine(None);
1752        t.block(vec!["q1".to_owned()], Some("first".to_owned()));
1753        t.block(
1754            vec!["q1".to_owned(), "q2".to_owned()],
1755            Some("second".to_owned()),
1756        );
1757
1758        t.unblock("q1");
1759        assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
1760        t.unblock("q2");
1761        assert_eq!(t.status, TaskStatus::Held);
1762    }
1763
1764    #[test]
1765    fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
1766        // Whatever process was driving the run is gone by the time a
1767        // conductor's question about it gets answered - there is nothing left
1768        // to resume into.
1769        let mut t = task("blocked mid-run");
1770        t.start("run-1".to_owned());
1771        assert_eq!(t.status, TaskStatus::Running);
1772
1773        t.block(vec!["q1".to_owned()], None);
1774        t.unblock("q1");
1775        assert_eq!(t.status, TaskStatus::Queued);
1776    }
1777
1778    #[test]
1779    fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
1780        // `blocked_from` is `None` for a record written before schema 4 (or,
1781        // equivalently, deserialized straight from an on-disk file that never
1782        // had the field). Held evidence surviving on the task - never cleared
1783        // by `block` - is the only way left to tell such a record apart from
1784        // one blocked straight out of `Queued`.
1785        let mut t = task("legacy record, held before it was blocked");
1786        t.hold_source = Some(HoldSource::Machine);
1787        t.hold_reason = Some("legacy hold reason".to_owned());
1788        t.status = TaskStatus::Blocked;
1789        t.blocked_by = vec!["q1".to_owned()];
1790        t.blocked_from = None;
1791
1792        t.unblock("q1");
1793        assert_eq!(t.status, TaskStatus::Held);
1794    }
1795
1796    #[test]
1797    fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
1798        let mut t = task("legacy record, ordinary dependency block");
1799        t.status = TaskStatus::Blocked;
1800        t.blocked_by = vec!["dep".to_owned()];
1801        t.blocked_from = None;
1802
1803        t.unblock("dep");
1804        assert_eq!(t.status, TaskStatus::Queued);
1805    }
1806
1807    #[test]
1808    fn answering_a_question_is_recorded_and_survives_a_release() {
1809        let mut t = task("asked something");
1810        t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
1811        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1812        t.unblock("q1");
1813        assert_eq!(t.status, TaskStatus::Queued);
1814        assert_eq!(t.answers.len(), 1);
1815        assert_eq!(t.answers[0].answer, "SQLite");
1816
1817        // A release resets attempts, not evidence - the same rule
1818        // `releasing_a_held_task_gives_it_a_real_second_chance` asserts for
1819        // `runs`.
1820        t.release();
1821        assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
1822    }
1823
1824    #[test]
1825    fn requesting_review_requeues_the_task_and_remembers_the_branch() {
1826        let mut t = task("blocked run with a surviving branch");
1827        t.start("run-1".to_owned());
1828        t.fail("blocked with major findings", 5);
1829        assert_eq!(t.status, TaskStatus::Failed);
1830
1831        t.request_review("magi/eba2/A".to_owned());
1832        assert_eq!(t.status, TaskStatus::Queued);
1833        assert_eq!(t.attempts, 0);
1834        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
1835
1836        // An ordinary release (a human overriding the choice) drops it again.
1837        t.release();
1838        assert!(t.review_branch.is_none());
1839    }
1840
1841    #[test]
1842    fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
1843        let mut t = task("retry");
1844        t.start("run-1".to_owned());
1845        t.requeue();
1846        assert!(t.fresh_start);
1847
1848        t.release();
1849        assert!(!t.fresh_start);
1850    }
1851
1852    #[test]
1853    fn priority_can_be_changed_while_queued_but_not_while_running() {
1854        let mut t = task("reprioritise me");
1855        t.set_priority(5).unwrap();
1856        assert_eq!(t.priority, 5);
1857
1858        t.start("run-1".to_owned());
1859        let err = t.set_priority(9).unwrap_err().to_string();
1860        assert!(err.contains("running"), "{err}");
1861        assert_eq!(t.priority, 5, "the rejected write must not partially apply");
1862    }
1863
1864    #[test]
1865    fn interrupt_can_be_marked_while_queued_but_not_while_running() {
1866        let mut t = task("interrupt me");
1867        assert!(!t.interrupt, "off unless asked, same as any other task");
1868
1869        t.set_interrupt(true).unwrap();
1870        assert!(t.interrupt);
1871
1872        t.start("run-1".to_owned());
1873        assert!(
1874            !t.interrupt,
1875            "the mark is one-shot: dispatching the task fulfils it, \
1876             whatever the run that follows ends up doing"
1877        );
1878        let err = t.set_interrupt(true).unwrap_err().to_string();
1879        assert!(err.contains("running"), "{err}");
1880        // Clearing is always allowed, even on a running task - there is
1881        // nothing left for it to interrupt once it has been claimed.
1882        t.set_interrupt(false).unwrap();
1883        assert!(!t.interrupt);
1884    }
1885
1886    /// R2-1-1: a task whose run fails and requeues must not go on
1887    /// re-triggering `crate::daemon`'s interrupt scheduler on every later
1888    /// boundary, attempt after attempt, until it exhausts its budget.
1889    #[test]
1890    fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
1891        let mut t = task("interrupt me");
1892        t.set_interrupt(true).unwrap();
1893        t.start("run-1".to_owned());
1894        t.fail("mock failure", 5);
1895        assert_eq!(t.status, TaskStatus::Failed);
1896        assert!(
1897            !t.interrupt,
1898            "one attempt already spent the mark; a retry is an ordinary \
1899             requeue, not a fresh interrupt request"
1900        );
1901    }
1902
1903    #[test]
1904    fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
1905        let (_dir, q) = queue();
1906        let mut a = task("first filed");
1907        let mut b = task("second filed");
1908        a.id = "20260101-000001-aaaa".to_owned();
1909        b.id = "20260101-000002-bbbb".to_owned();
1910        q.put(&mut a).unwrap();
1911        q.put(&mut b).unwrap();
1912
1913        assert_eq!(
1914            q.next_runnable().unwrap().id,
1915            a.id,
1916            "with equal priority the older task goes first, so a burst of \
1917             new work cannot starve it"
1918        );
1919        assert_eq!(
1920            q.list()[0].id,
1921            b.id,
1922            "but the list an operator reads is newest first, the same as \
1923             before priority existed - a's turn to run does not make it the \
1924             newest task"
1925        );
1926
1927        let mut a = q.get(&a.id).unwrap();
1928        a.set_priority(10).unwrap();
1929        q.put(&mut a).unwrap();
1930
1931        assert_eq!(
1932            q.next_runnable().unwrap().id,
1933            a.id,
1934            "a raised priority must be reflected the moment it is saved"
1935        );
1936        // `magi task list` and `GET /api/queue` both print `Queue::list()`
1937        // directly, so the raised task has to lead there too - not only in
1938        // what the loop would claim next.
1939        assert_eq!(
1940            q.list()[0].id,
1941            a.id,
1942            "the raised task must sort first in the list an operator reads, \
1943             not only in next_runnable's own ordering"
1944        );
1945    }
1946
1947    #[test]
1948    fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
1949        let mut t = Task::new(
1950            "old title".to_owned(),
1951            "old instruction".to_owned(),
1952            PathBuf::from("/repo"),
1953            Source::Agent {
1954                run: "20260101-000000-beef".to_owned(),
1955                node: "implement".to_owned(),
1956            },
1957        );
1958        let id = t.id.clone();
1959        let created_at = t.created_at;
1960        t.runs.push("20260101-000000-beef".to_owned());
1961
1962        t.edit("new title".to_owned(), "new instruction".to_owned())
1963            .unwrap();
1964
1965        assert_eq!(t.title, "new title");
1966        assert_eq!(t.instruction, "new instruction");
1967        assert_eq!(t.id, id, "editing must not mint a new id");
1968        assert_eq!(t.created_at, created_at);
1969        assert_eq!(
1970            t.source,
1971            Source::Agent {
1972                run: "20260101-000000-beef".to_owned(),
1973                node: "implement".to_owned(),
1974            },
1975            "editing must not turn agent attribution into human"
1976        );
1977        assert_eq!(t.runs, ["20260101-000000-beef"]);
1978    }
1979
1980    #[test]
1981    fn editing_is_refused_once_a_task_is_running_or_finished() {
1982        let mut running = task("in flight");
1983        running.start("run-1".to_owned());
1984        let err = running
1985            .edit("x".to_owned(), "y".to_owned())
1986            .unwrap_err()
1987            .to_string();
1988        assert!(err.contains("running"), "{err}");
1989
1990        let mut done = task("finished");
1991        done.succeed();
1992        let err = done
1993            .edit("x".to_owned(), "y".to_owned())
1994            .unwrap_err()
1995            .to_string();
1996        assert!(err.contains("done"), "{err}");
1997
1998        // Both queued and held are the point of the feature and must work.
1999        let mut queued = task("waiting");
2000        queued.edit("x".to_owned(), "y".to_owned()).unwrap();
2001        let mut held = task("parked");
2002        held.hold_machine(None);
2003        held.edit("x".to_owned(), "y".to_owned()).unwrap();
2004    }
2005
2006    #[test]
2007    fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
2008        let (_dir, q) = queue();
2009        let path = q.path_of("20260101-000000-aaaa");
2010        std::fs::create_dir_all(q.root()).unwrap();
2011        std::fs::write(
2012            &path,
2013            serde_json::json!({
2014                "schema": SCHEMA,
2015                "id": "20260101-000000-aaaa",
2016                "title": "from before hold reasons existed",
2017                "instruction": "from before hold reasons existed",
2018                "repo": ".",
2019                "source": { "kind": "human" },
2020                "status": "held",
2021                "created_at": Timestamp::now().to_string(),
2022                "updated_at": Timestamp::now().to_string(),
2023            })
2024            .to_string(),
2025        )
2026        .unwrap();
2027
2028        let task = q.get("20260101-000000-aaaa").expect("must still read");
2029        assert!(task.hold_reason.is_none());
2030        assert!(task.operator_held());
2031    }
2032
2033    #[test]
2034    fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
2035        let (_dir, q) = queue();
2036        let path = q.path_of("20260101-000000-bbbb");
2037        std::fs::create_dir_all(q.root()).unwrap();
2038        std::fs::write(
2039            &path,
2040            serde_json::json!({
2041                "schema": 2,
2042                "id": "20260101-000000-bbbb",
2043                "title": "old manual recovery",
2044                "instruction": "old manual recovery",
2045                "repo": ".",
2046                "source": { "kind": "human" },
2047                "status": "held",
2048                "hold_reason": "active manual recovery run20260912-224242-daf5",
2049                "created_at": Timestamp::now().to_string(),
2050                "updated_at": Timestamp::now().to_string(),
2051            })
2052            .to_string(),
2053        )
2054        .unwrap();
2055
2056        let task = q.get("20260101-000000-bbbb").expect("must still read");
2057        assert_eq!(task.hold_source, None);
2058        assert!(task.operator_held());
2059    }
2060
2061    #[test]
2062    fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
2063        let (_dir, q) = queue();
2064        let path = q.path_of("20260101-000000-aaaa");
2065        std::fs::create_dir_all(q.root()).unwrap();
2066        std::fs::write(
2067            &path,
2068            serde_json::json!({
2069                "schema": SCHEMA,
2070                "id": "20260101-000000-aaaa",
2071                "title": "from before diagnostics existed",
2072                "instruction": "from before diagnostics existed",
2073                "repo": ".",
2074                "source": { "kind": "human" },
2075                "status": "held",
2076                "created_at": Timestamp::now().to_string(),
2077                "updated_at": Timestamp::now().to_string(),
2078            })
2079            .to_string(),
2080        )
2081        .unwrap();
2082
2083        let task = q.get("20260101-000000-aaaa").expect("must still read");
2084        assert!(task.diagnostic.is_none());
2085    }
2086
2087    #[test]
2088    fn a_schema_1_task_with_no_blocking_fields_still_reads() {
2089        // Written by a build that predates `blocked_by`, `block_reason`,
2090        // `answers` and `review_branch` entirely - literal `"schema": 1`,
2091        // not `SCHEMA`, since the whole point is a build older than this one.
2092        let (_dir, q) = queue();
2093        let path = q.path_of("20260101-000000-aaaa");
2094        std::fs::create_dir_all(q.root()).unwrap();
2095        std::fs::write(
2096            &path,
2097            serde_json::json!({
2098                "schema": 1,
2099                "id": "20260101-000000-aaaa",
2100                "title": "from before blocking existed",
2101                "instruction": "from before blocking existed",
2102                "repo": ".",
2103                "source": { "kind": "human" },
2104                "status": "queued",
2105                "created_at": Timestamp::now().to_string(),
2106                "updated_at": Timestamp::now().to_string(),
2107            })
2108            .to_string(),
2109        )
2110        .unwrap();
2111
2112        let task = q.get("20260101-000000-aaaa").expect("must still read");
2113        assert!(task.blocked_by.is_empty());
2114        assert!(task.block_reason.is_none());
2115        assert!(task.answers.is_empty());
2116        assert!(task.review_branch.is_none());
2117    }
2118
2119    #[test]
2120    fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
2121        // A diagnostic belongs to the run that produced it. Left in place
2122        // across a release, an unrelated later failure - a config error, say -
2123        // would go on showing evidence for a problem that is no longer why the
2124        // task is stuck.
2125        let mut held = task("diagnosed");
2126        held.start("run-1".to_owned());
2127        held.fail("gate red", 1);
2128        held.diagnostic = Some("cargo test failed: ...".to_owned());
2129        assert_eq!(held.status, TaskStatus::Held);
2130
2131        held.release();
2132        assert!(held.diagnostic.is_none());
2133
2134        held.diagnostic = Some("cargo test failed: ...".to_owned());
2135        held.succeed();
2136        assert!(held.diagnostic.is_none());
2137    }
2138
2139    #[test]
2140    fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
2141        let mut t = task("retried");
2142        t.start("run-1".to_owned());
2143        t.diagnostic = Some("stale evidence from a previous hold".to_owned());
2144        t.fail("unrelated config error", 5);
2145        assert_eq!(t.status, TaskStatus::Failed);
2146        assert!(
2147            t.diagnostic.is_none(),
2148            "fail() must not let an old diagnostic outlive the run that produced it"
2149        );
2150    }
2151
2152    #[test]
2153    fn a_claim_is_exclusive_and_releases_on_drop() {
2154        let (_dir, q) = queue();
2155        let mut t = task("contended");
2156        q.put(&mut t).unwrap();
2157
2158        let held = q.claim(&t.id).unwrap();
2159        assert!(
2160            q.claim(&t.id).is_err(),
2161            "two daemons must not drive one task into two runs"
2162        );
2163        drop(held);
2164        assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
2165    }
2166
2167    #[test]
2168    fn a_round_trip_survives_disk() {
2169        let (_dir, q) = queue();
2170        let mut t = Task::new(
2171            "titled".to_owned(),
2172            "body".to_owned(),
2173            PathBuf::from("/repo"),
2174            Source::Agent {
2175                run: "20260101-000000-beef".to_owned(),
2176                node: "implement".to_owned(),
2177            },
2178        );
2179        t.priority = 3;
2180        q.put(&mut t).unwrap();
2181
2182        let back = q.get(&t.id).unwrap();
2183        assert_eq!(back.id, t.id);
2184        assert_eq!(back.priority, 3);
2185        assert_eq!(back.source.label(), "implement@beef");
2186        // A prefix is enough, the way run ids work everywhere else.
2187        assert_eq!(q.get(t.short()).unwrap().id, t.id);
2188    }
2189
2190    #[test]
2191    fn an_unreadable_task_does_not_take_the_queue_down() {
2192        let (_dir, q) = queue();
2193        let mut t = task("fine");
2194        q.put(&mut t).unwrap();
2195        std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
2196
2197        let listed = q.list();
2198        assert_eq!(listed.len(), 1, "the readable task still lists");
2199        assert_eq!(listed[0].id, t.id);
2200    }
2201
2202    #[test]
2203    fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
2204        let (_dir, q) = queue();
2205        let path = q.path_of("20260101-000000-aaaa");
2206        std::fs::create_dir_all(q.root()).unwrap();
2207        std::fs::write(
2208            &path,
2209            serde_json::json!({
2210                "schema": SCHEMA,
2211                "id": "20260101-000000-aaaa",
2212                "title": "from before solo existed",
2213                "instruction": "from before solo existed",
2214                "repo": ".",
2215                "source": { "kind": "human" },
2216                "status": "queued",
2217                "created_at": Timestamp::now().to_string(),
2218                "updated_at": Timestamp::now().to_string(),
2219            })
2220            .to_string(),
2221        )
2222        .unwrap();
2223
2224        let task = q.get("20260101-000000-aaaa").expect("must still read");
2225        assert!(!task.solo, "a queue file with no `solo` field means false");
2226    }
2227
2228    #[test]
2229    fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
2230        let (_dir, q) = queue();
2231        let path = q.path_of("20260101-000000-bbbb");
2232        std::fs::create_dir_all(q.root()).unwrap();
2233        std::fs::write(
2234            &path,
2235            serde_json::json!({
2236                "schema": SCHEMA,
2237                "id": "20260101-000000-bbbb",
2238                "title": "from before urgent existed",
2239                "instruction": "from before urgent existed",
2240                "repo": ".",
2241                "source": { "kind": "human" },
2242                "status": "queued",
2243                "created_at": Timestamp::now().to_string(),
2244                "updated_at": Timestamp::now().to_string(),
2245            })
2246            .to_string(),
2247        )
2248        .unwrap();
2249
2250        let task = q.get("20260101-000000-bbbb").expect("must still read");
2251        assert!(
2252            !task.urgent,
2253            "a queue file with no `urgent` field means false, same as `solo`"
2254        );
2255    }
2256
2257    #[test]
2258    fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
2259        let (_dir, q) = queue();
2260        let mut t = task("from the future");
2261        q.put(&mut t).unwrap();
2262        let path = q.path_of(&t.id);
2263        let body = std::fs::read_to_string(&path)
2264            .unwrap()
2265            .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
2266        std::fs::write(&path, body).unwrap();
2267
2268        let err = q.get(&t.id).unwrap_err().to_string();
2269        assert!(err.contains("schema 99"), "{err}");
2270    }
2271
2272    #[test]
2273    fn revision_moves_when_the_queue_changes() {
2274        let (_dir, q) = queue();
2275        assert_eq!(q.revision(), 0, "an empty queue has no revision");
2276        let mut t = task("first");
2277        q.put(&mut t).unwrap();
2278        assert!(q.revision() > 0, "a written task moves the revision");
2279    }
2280
2281    #[test]
2282    fn revision_moves_when_deleting_an_older_task() {
2283        let (dir, q) = queue();
2284        let questions = Questions::at(dir.path().join("questions"));
2285        let mut t1 = task("older");
2286        q.put(&mut t1).unwrap();
2287        // Ensure mtime ticks forward.
2288        std::thread::sleep(std::time::Duration::from_millis(10));
2289        let mut t2 = task("newer");
2290        q.put(&mut t2).unwrap();
2291
2292        let rev_before = q.revision();
2293        q.remove(&t1.id, false, &questions).unwrap();
2294        let rev_after = q.revision();
2295
2296        assert_ne!(
2297            rev_before, rev_after,
2298            "deleting an older task must change the revision so other clients see the deletion"
2299        );
2300    }
2301
2302    #[test]
2303    fn removing_a_task_takes_it_out_of_the_listing() {
2304        let (dir, q) = queue();
2305        let questions = Questions::at(dir.path().join("questions"));
2306        let mut t = task("delete me");
2307        q.put(&mut t).unwrap();
2308        let removed = q.remove(t.short(), false, &questions).unwrap();
2309        assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
2310        assert!(removed.quarantined.is_empty(), "nothing was blocked on it");
2311        assert!(q.list().is_empty());
2312        assert!(
2313            q.remove(&t.id, false, &questions).is_err(),
2314            "removing twice is an error"
2315        );
2316    }
2317
2318    #[test]
2319    fn removing_a_task_takes_its_stale_lock_with_it() {
2320        let (dir, q) = queue();
2321        let questions = Questions::at(dir.path().join("questions"));
2322        let mut t = task("interrupted");
2323        q.put(&mut t).unwrap();
2324
2325        // A daemon killed mid-run leaves this behind. Nothing holds it: the
2326        // process that would have dropped the guard is gone.
2327        let claim = q.claim(&t.id).unwrap();
2328        std::mem::forget(claim);
2329        assert!(
2330            q.claim(&t.id).is_err(),
2331            "the orphaned lock is what makes the task look claimed"
2332        );
2333
2334        // A live daemon on this task is refused, whatever the lock says.
2335        let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
2336        assert!(err.contains("live daemon"), "{err}");
2337        assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
2338
2339        // With no daemon behind it, the lock is stale and goes with the task.
2340        q.remove(&t.id, false, &questions).unwrap();
2341        assert!(q.list().is_empty());
2342        let mut again = task("interrupted");
2343        again.id = t.id.clone();
2344        q.put(&mut again).unwrap();
2345        assert!(
2346            q.claim(&t.id).is_ok(),
2347            "a task that comes back must be claimable, which a left-behind lock would prevent"
2348        );
2349    }
2350
2351    #[test]
2352    fn removing_a_task_quarantines_what_was_blocked_on_it() {
2353        let (dir, q) = queue();
2354        let questions = Questions::at(dir.path().join("questions"));
2355
2356        let mut dep = task("dependency");
2357        q.put(&mut dep).unwrap();
2358
2359        let mut still_valid = task("still valid");
2360        q.put(&mut still_valid).unwrap();
2361
2362        let mut blocked = task("waiting");
2363        blocked.block(
2364            vec![dep.id.clone(), still_valid.id.clone()],
2365            Some("waits on both".to_owned()),
2366        );
2367        q.put(&mut blocked).unwrap();
2368
2369        let removed = q.remove(&dep.id, false, &questions).unwrap();
2370        assert_eq!(removed.quarantined, [blocked.id.clone()]);
2371
2372        let after = q.get(&blocked.id).unwrap();
2373        assert_eq!(after.status, TaskStatus::Held);
2374        assert_eq!(after.hold_source, Some(HoldSource::Machine));
2375        assert!(after.blocked_by.is_empty());
2376        let reason = after.hold_reason.as_deref().unwrap_or_default();
2377        assert!(reason.contains(&dep.id), "{reason}");
2378        assert!(
2379            reason.contains(&still_valid.id),
2380            "the still-valid dependency must survive in the reason text: {reason}"
2381        );
2382    }
2383}