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/// 7: added [`Task::attachments`], names of files copied under
45/// `<id>.attachments/` beside the task file (a field only; `#[serde(default)]`,
46/// so an older record reads as empty and [`read_path`] still accepts it).
47///
48/// 6: added [`Task::resume_override`] (a field only; `#[serde(default)]`, so
49/// an older record reads as `None` and [`read_path`] still accepts it).
50///
51/// 5: added [`Task::triage_applied`], the ids of triage questions whose
52/// answer has already been applied to this task. A "resume" answer used to
53/// leave no trace ([`Task::release`] clears [`Task::hold_reason`], which was
54/// the only place the applied marker lived), so when the released task failed
55/// its attempts and went back to `held`, the next idle pass found the same
56/// answered question "not applied" and released it again with `attempts` reset
57/// to 0 - the `max_attempts` bound never held. `#[serde(default)]` so an older
58/// record reads as empty. A task already looping when this build arrives has
59/// no record, so it is released once more, recorded, and then stays held.
60///
61/// 8: added [`Task::followup`], the origin of a task `crate::followup` filed
62/// from a merged run's leftover findings. Field-only bump, `#[serde(default)]`.
63///
64/// 4: added [`Task::blocked_from`], the status a task had the moment it
65/// became [`TaskStatus::Blocked`], so [`Task::unblock`] restores it instead
66/// of always landing on [`TaskStatus::Queued`]. Without it, a task a human
67/// or `crate::triage` had deliberately left [`TaskStatus::Held`] — machine
68/// or manual — would lose that the instant `crate::conduct` blocked it on a
69/// follow-up question, and come back `Queued` the moment the question was
70/// answered, regardless of what the answer said: exactly the loop where a
71/// task the operator told to stay held instead re-enters the competition
72/// queue every time someone answers a question about it. `#[serde(default)]`
73/// so an older record reads as `None`; [`Task::unblock`] then falls back to
74/// inferring `Held` from surviving hold evidence ([`Task::hold_reason`] /
75/// [`Task::hold_source`], never cleared by [`Task::block`]) rather than
76/// guessing `Queued` outright — see [`Task::unblock`]'s own doc.
77///
78/// 9: added [`Task::held_at`], the start of the current hold, so a notice can
79/// tell a question filed for this hold from one about an older cause.
80/// Field-only, `#[serde(default)]`.
81///
82/// 10: added [`Task::overrides`] and [`Task::review_of`], so a run started by
83/// hand (`magi run` / `magi review`) is carried by a task without losing its
84/// command-line choices. Field-only.
85///
86/// 11: added [`TaskStatus::Parked`] and [`Task::park_reason`], so a run that
87/// stopped at a node boundary (an upgrade, an operator's park) is no longer
88/// recorded as a failed task. Variant plus `#[serde(default)]` field; an older
89/// build must not half-read the new status.
90///
91/// 12: added [`Task::origin_chat`], the talk a task descends from, so a
92/// follow-up still knows its chat after an ancestor task is deleted.
93/// Field-only, `#[serde(default)]`.
94///
95/// 3: added [`HoldSource`] so conductor recovery cannot release a hold an
96/// operator deliberately placed. Old records default to `None` and are
97/// protected as operator-held until an explicit release; the safe direction
98/// when their author was never recorded.
99///
100/// 2: added [`TaskStatus::Blocked`], [`Task::blocked_by`] and
101/// [`Task::block_reason`] (`crate::conduct`'s decisions) and
102/// [`Task::answers`] (operator answers carried forward to the next
103/// conductor prompt and the next run's instruction). All three are
104/// `#[serde(default)]`, so [`read_path`] accepts anything up to and
105/// including this schema rather than only an exact match — a task written
106/// by a build that only knew about schema 1 has nothing to say about
107/// blocking or answers, and defaulting those fields is exactly as good a
108/// reading as a value that build never had a chance to write.
109pub const SCHEMA: u32 = 12;
110
111/// Who placed the current hold.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
113#[serde(rename_all = "lowercase")]
114pub enum HoldSource {
115    /// An operator used the CLI or web UI.
116    Manual,
117    /// The daemon or conductor placed the hold as part of its own recovery.
118    Machine,
119}
120
121impl HoldSource {
122    /// Short human-facing label for reports and the CLI.
123    pub fn label(self) -> &'static str {
124        match self {
125            Self::Manual => "manual",
126            Self::Machine => "machine",
127        }
128    }
129}
130
131/// Where a task came from. Recorded because "who asked for this" is the first
132/// question about an autonomous run, and the answer is not recoverable later.
133#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
134#[serde(tag = "kind", rename_all = "lowercase")]
135pub enum Source {
136    /// A person, at a terminal or through the web UI.
137    Human,
138    /// An agent inside a run, via `magi task add`. Both ids are recorded so a
139    /// task can be traced back to the exact seat that asked for it.
140    Agent {
141        /// Run the asking agent belonged to.
142        run: String,
143        /// Node it was working in, e.g. `implement` or `review`.
144        node: String,
145    },
146    /// A GitHub issue, imported by number.
147    Issue {
148        /// Issue number.
149        number: u64,
150        /// `owner/repo`, as `gh` reports it.
151        repo: String,
152    },
153}
154
155/// The `node` a [`Source::Agent`] carries when the asker is a chat
156/// conversation (its `run` is then the conversation's id).
157pub const CHAT_NODE: &str = "chat";
158
159impl Source {
160    /// Short human-facing label, for lists and the web UI.
161    pub fn label(&self) -> String {
162        match self {
163            Self::Human => "human".to_owned(),
164            Self::Agent { run, node } => format!("{node}@{}", short(run)),
165            Self::Issue { number, .. } => format!("issue #{number}"),
166        }
167    }
168}
169
170/// Where a task is in its life.
171#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
172#[serde(rename_all = "lowercase")]
173pub enum TaskStatus {
174    /// Waiting to be claimed.
175    Queued,
176    /// Claimed by a daemon; a run is in flight.
177    Running,
178    /// A run finished and its gate passed.
179    Done,
180    /// A run finished without passing, and attempts remain.
181    Failed,
182    /// Out of attempts, or held by hand. The loop will not pick it up.
183    Held,
184    /// Waiting on another task or an unanswered question. See
185    /// [`Task::blocked_by`]. Set and cleared by `crate::conduct` and
186    /// `crate::daemon`'s deterministic resolver, never by hand.
187    Blocked,
188    /// The run stopped at a node boundary because the process was asked to
189    /// give itself back. Nothing failed: the run's work is intact and the next
190    /// loop resumes it. Runnable like [`TaskStatus::Queued`]; the reason is in
191    /// [`Task::park_reason`], never [`Task::last_error`].
192    Parked,
193}
194
195impl TaskStatus {
196    /// Is this task eligible for a daemon to claim?
197    pub fn runnable(self) -> bool {
198        matches!(self, Self::Queued | Self::Failed | Self::Parked)
199    }
200
201    /// Lowercase name, as it appears on disk and in the API.
202    pub fn as_str(self) -> &'static str {
203        match self {
204            Self::Queued => "queued",
205            Self::Running => "running",
206            Self::Done => "done",
207            Self::Failed => "failed",
208            Self::Held => "held",
209            Self::Blocked => "blocked",
210            Self::Parked => "parked",
211        }
212    }
213}
214
215/// How many tasks sit in each [`TaskStatus`], for a dashboard tile — never a
216/// per-task view, so it carries no ids.
217#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
218pub struct TaskCounts {
219    /// Waiting to be claimed.
220    pub queued: usize,
221    /// Claimed; a run is in flight.
222    pub running: usize,
223    /// A run finished and its gate passed.
224    pub done: usize,
225    /// A run finished without passing, and attempts remain.
226    pub failed: usize,
227    /// Out of attempts, or held by hand.
228    pub held: usize,
229    /// Waiting on another task or an unanswered question.
230    pub blocked: usize,
231    /// Run parked at a node boundary; resumable, not a failure.
232    pub parked: usize,
233}
234
235impl TaskCounts {
236    /// Tally `tasks` by status. A pure function over whatever [`Queue::list`]
237    /// already read, so it needs no root of its own and stays trivially
238    /// testable against a hand-built slice.
239    pub fn of(tasks: &[Task]) -> Self {
240        let mut counts = Self::default();
241        for t in tasks {
242            match t.status {
243                TaskStatus::Queued => counts.queued += 1,
244                TaskStatus::Running => counts.running += 1,
245                TaskStatus::Done => counts.done += 1,
246                TaskStatus::Failed => counts.failed += 1,
247                TaskStatus::Held => counts.held += 1,
248                TaskStatus::Blocked => counts.blocked += 1,
249                TaskStatus::Parked => counts.parked += 1,
250            }
251        }
252        counts
253    }
254}
255
256/// One unit of work.
257#[derive(Debug, Clone, Serialize, Deserialize)]
258#[serde(deny_unknown_fields)]
259pub struct Task {
260    /// On-disk format version.
261    pub schema: u32,
262    /// Task id, e.g. `20260902-140501-a1b2`.
263    pub id: String,
264    /// One line, for lists and notifications.
265    pub title: String,
266    /// The task itself, handed to the graph verbatim.
267    pub instruction: String,
268    /// Repository to work in.
269    pub repo: PathBuf,
270    /// Who asked.
271    pub source: Source,
272    /// Higher runs first; ties break oldest-first so nothing starves.
273    #[serde(default)]
274    pub priority: i32,
275    /// Run this task alone: one implementer, no panel of judges to convince.
276    ///
277    /// `#[serde(default)]` so a queue file written before this field existed
278    /// still reads, as `false` - the ordinary multi-candidate competition,
279    /// unchanged. A task set to `solo` still runs the whole graph; only the
280    /// candidate count the daemon builds it with changes, and
281    /// [`crate::graph::Runner`] already collapses a single-candidate run to
282    /// implement → review → gate → merge on its own (see
283    /// [`crate::graph::Runner::review`]'s doc), so nothing about judging,
284    /// deliberation or voting had to change to support this.
285    #[serde(default)]
286    pub solo: bool,
287    /// Current state.
288    pub status: TaskStatus,
289    /// How many times this task has been claimed.
290    #[serde(default)]
291    pub attempts: usize,
292    /// Runs this task has produced, oldest first.
293    #[serde(default)]
294    pub runs: Vec<String>,
295    /// Why the last attempt did not land.
296    #[serde(default)]
297    pub last_error: Option<String>,
298    /// What a human hold is waiting on.
299    ///
300    /// `None` covers both the ordinary cases: a hold the loop makes itself
301    /// (out of attempts, or the disk gate closed) explains itself through
302    /// [`Task::last_error`] instead, and a human hold nobody bothered to
303    /// explain is still a valid hold. The queue has no way to express a
304    /// dependency between two tasks, so on the occasions a hold really is
305    /// "wait for that other task first", this is the only place that reason
306    /// survives - see [`Task::hold_manual`] and [`Task::release`].
307    ///
308    /// `#[serde(default)]` so a queue file written before this field existed
309    /// still reads, with no reason recorded rather than a parse error.
310    #[serde(default)]
311    pub hold_reason: Option<String>,
312    /// Who placed [`Task::hold_reason`].  `None` is a compatible old record;
313    /// see [`Task::operator_held`] for its deliberately conservative meaning.
314    #[serde(default)]
315    pub hold_source: Option<HoldSource>,
316    /// Diagnostic detail excerpted from the run that led to a hold - what a
317    /// human would have found opening `artifacts/` by hand, not the one-line
318    /// reason in [`Task::last_error`]. Set only when a run's own attempts are
319    /// exhausted and the task becomes [`TaskStatus::Held`]; `daemon` computes
320    /// it from the run's own record, since this module has no notion of a
321    /// run's internals. Bounded in length by the writer - see
322    /// `daemon::diagnostic` - so a verbose run cannot make this file grow
323    /// without limit.
324    ///
325    /// `#[serde(default)]` so a queue file written before this field existed
326    /// still reads, with no diagnostic recorded rather than a parse error.
327    #[serde(default)]
328    pub diagnostic: Option<String>,
329    /// What this task is waiting on: other task ids, unanswered
330    /// `crate::ask::Question` ids, or both. Non-empty exactly when
331    /// [`TaskStatus::Blocked`]; emptying it — see [`Task::unblock`] — is what
332    /// puts the task back at [`TaskStatus::Queued`].
333    ///
334    /// Set by `crate::conduct`'s decisions and cleared deterministically by
335    /// `crate::daemon` as each dependency resolves, never by a person. Never
336    /// `#[serde(default)]` is skipped: a queue file from before this field
337    /// existed has nothing to report here, and an empty list is exactly that.
338    #[serde(default)]
339    pub blocked_by: Vec<String>,
340    /// One line explaining the current [`Task::blocked_by`], written by
341    /// `crate::conduct`. Cleared whenever `blocked_by` empties.
342    #[serde(default)]
343    pub block_reason: Option<String>,
344    /// The status this task had the moment [`Task::block`] most recently
345    /// moved it to [`TaskStatus::Blocked`] — what [`Task::unblock`] restores
346    /// once nothing is left in `blocked_by`, instead of always landing on
347    /// [`TaskStatus::Queued`]. See [`SCHEMA`]'s doc for schema 4 on why this
348    /// exists: an answer to a question `crate::conduct` filed about a
349    /// [`TaskStatus::Held`] task must not itself be what puts the task back
350    /// in the competition queue.
351    ///
352    /// `#[serde(default)]` so a queue file written before this field existed
353    /// reads as `None`; [`Task::unblock`] treats that the same as a task
354    /// blocked straight from `Queued`, unless surviving hold evidence says
355    /// otherwise.
356    #[serde(default)]
357    pub blocked_from: Option<TaskStatus>,
358    /// Questions `crate::conduct` asked about this task that the operator has
359    /// since answered, oldest first — what was asked, and what they said.
360    ///
361    /// A blocking question's id leaves [`Task::blocked_by`] the moment
362    /// [`crate::ask::QuestionStatus::Answered`] is observed, but the id alone
363    /// tells nobody what was decided. This is what carries the answer's
364    /// *content* forward: into the next conductor prompt for this task, and
365    /// into the instruction handed to the next run — see `crate::daemon`'s
366    /// deterministic blocker resolution. Kept for the task's whole life, the
367    /// same as [`Task::runs`]: a release resets attempts, not evidence.
368    #[serde(default)]
369    pub answers: Vec<AnsweredQuestion>,
370    /// Ids of the `crate::triage` questions whose answer has been applied to
371    /// this task. Unlike [`Task::hold_reason`], [`Task::release`] and every
372    /// hold transition leave it alone, so an answer is applied at most once
373    /// however many times the task is held again. See [`SCHEMA`]'s doc for
374    /// schema 5. `#[serde(default)]` so an older record reads as empty.
375    #[serde(default)]
376    pub triage_applied: Vec<String>,
377    /// Ids of the `magi ask` questions whose [`crate::ask::ChoiceAction`] has
378    /// been applied to this task. Separate from [`Task::triage_applied`]
379    /// (a different producer) and, like it, untouched by [`Task::release`],
380    /// so one answer acts at most once however often the task is held again.
381    /// `#[serde(default)]` so an older record reads as empty.
382    #[serde(default)]
383    pub actions_applied: Vec<String>,
384    /// The operator's "resume" answer to a triage question, kept until the
385    /// task actually runs (or is done) so `crate::conduct` cannot silently
386    /// undo it and `crate::triage` can tell that a hold it sees now came
387    /// *after* the answer. See [`OperatorResume`]. `#[serde(default)]`.
388    #[serde(default)]
389    pub resume_override: Option<OperatorResume>,
390    /// Set by `crate::conduct` when it chooses `Review` recovery for a task
391    /// whose branch survived a blocked run: the branch to reopen with
392    /// `crate::graph::Runner::review` instead of competing from scratch.
393    ///
394    /// Requeues the task the same way [`Task::release`] does, so it is
395    /// picked up by the ordinary loop; `crate::daemon` reads this field once,
396    /// when it actually starts the run, and clears it either way — consumed
397    /// on success, dropped if the branch no longer exists by then. Never set
398    /// from the conductor's own words: `crate::daemon` derives the branch
399    /// name itself from the task's last run, so a hallucinated branch can
400    /// never reach here.
401    #[serde(default)]
402    pub review_branch: Option<String>,
403    /// A release deliberately starts a new competition instead of resuming
404    /// the prior run. History remains as evidence in `runs`.
405    #[serde(default)]
406    pub fresh_start: bool,
407    /// Marked by an operator (`magi task interrupt`) to ask `magi serve` to
408    /// run this one ahead of whatever it already has in flight, once
409    /// `[daemon] pause_for_interrupts` is on - see
410    /// `crate::daemon::advance_interrupt`. Never set by the loop itself, and
411    /// deliberately a different operation from [`Task::set_priority`]: a
412    /// priority only reorders the queue a claim has not reached yet, while
413    /// this asks a run already in flight to park at its next safe boundary
414    /// and step aside. `#[serde(default)]` so a queue file written before
415    /// this field existed still reads, as `false` - no task interrupts
416    /// anything unless asked to, exactly as before.
417    #[serde(default)]
418    pub interrupt: bool,
419    /// Marked by `magi task add --urgent`: `crate::daemon::poll` dispatches
420    /// this task through its own one-slot `urgent_sem` the moment it is
421    /// runnable, in addition to whatever is already running under the
422    /// ordinary `[daemon] max_concurrent_runs` pool - never instead of it,
423    /// and never by pausing or otherwise touching that run. This is the
424    /// opposite direction from [`Task::interrupt`]: that one asks a run
425    /// already in flight to step aside; this one never asks anything to
426    /// step aside, it only spends one additional, temporary concurrency
427    /// slot. The two are independent and may both be set on the same task,
428    /// but this exemption stops at `[daemon] pause_for_interrupts`'s own
429    /// park/resume handoff (75dd): while an interrupt sequence is actively
430    /// parking, running, or resuming - its own, or an unrelated task's -
431    /// `crate::daemon::interrupt_gate` withholds an urgent candidate exactly
432    /// like an ordinary one, never exempted. 75dd's "at most one run, ever,
433    /// at once" guarantee takes precedence, because the alternative is a run
434    /// still genuinely in flight (only *asked* to park, not yet gone) ending
435    /// up alongside a second one this feature let through - the very thing
436    /// that guarantee exists to rule out.
437    ///
438    /// `#[serde(default)]` so a queue file written before this field existed
439    /// still reads, as `false` - no task claims the urgent slot unless asked
440    /// to, exactly as before.
441    #[serde(default)]
442    pub urgent: bool,
443    /// Files (typically screenshots) copied into `<id>.attachments/` beside
444    /// this task's file by [`Queue::attach`], as bare validated names. The
445    /// copy is what makes them reach the implementer: the original may be
446    /// cleaned up long before the task runs. Untouched by [`Task::edit`].
447    /// `#[serde(default)]` so an older record reads as empty.
448    #[serde(default)]
449    pub attachments: Vec<String>,
450    /// Set on a task `crate::followup` filed from the findings a merged run
451    /// left open: which run and findings it carries, and how many follow-ups
452    /// deep it is. `None` for every ordinary task. `#[serde(default)]`.
453    #[serde(default)]
454    pub followup: Option<FollowUp>,
455    /// Id of the chat this task descends from: set by [`Task::new`] when a
456    /// chat files it, inherited by the follow-ups `crate::followup` files, so
457    /// the provenance survives deleting an ancestor. `None` for a task written
458    /// before the field existed (`crate::consult` then walks the ancestry).
459    /// `#[serde(default)]`.
460    #[serde(default)]
461    pub origin_chat: Option<String>,
462    /// The command-line choices (`--merge`, `-c`, `--seed`, ...) of the
463    /// `magi run` / `magi review` that filed this task, applied on top of the
464    /// repository's config by whoever executes it - a daemon included - so
465    /// handing the task over does not change what it does. `None` for every
466    /// task filed any other way. `#[serde(default)]`.
467    #[serde(default)]
468    pub overrides: Option<RunOverrides>,
469    /// The branch an explicit `magi review <branch>` asked to review. Unlike
470    /// [`Task::review_branch`] (a recovery choice the daemon consumes and
471    /// drops back to a competition when the branch is gone), this is the whole
472    /// request: it is never consumed, and a missing branch fails the attempt
473    /// rather than paying for an implementation nobody asked for.
474    /// `#[serde(default)]`.
475    #[serde(default)]
476    pub review_of: Option<String>,
477    /// When the current hold began. Set by the transitions into
478    /// [`TaskStatus::Held`] (a re-hold keeps it), cleared by
479    /// [`Task::release`]. `crate::notices` uses it as the identity of the
480    /// cause: a question filed before it is about something older.
481    #[serde(default)]
482    pub held_at: Option<Timestamp>,
483    /// Why the run parked, while the task is [`TaskStatus::Parked`]. Kept apart
484    /// from [`Task::last_error`] because nothing failed. Cleared by every
485    /// transition out of the parked state. `#[serde(default)]`.
486    #[serde(default)]
487    pub park_reason: Option<String>,
488    /// When the task was filed.
489    pub created_at: Timestamp,
490    /// Last change to this file.
491    pub updated_at: Timestamp,
492}
493
494/// Command-line choices carried by a task. See [`Task::overrides`].
495#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
496pub struct RunOverrides {
497    /// `--merge`: `none`, `local` or `pr`.
498    #[serde(default)]
499    pub merge: Option<String>,
500    /// `-c` / `--implementers`: parallel implementations (persisted as `candidates`).
501    #[serde(default)]
502    pub candidates: Option<usize>,
503    /// `-j`: independent judges.
504    #[serde(default)]
505    pub judges: Option<usize>,
506    /// `--reviewers`: reviewers per round.
507    #[serde(default)]
508    pub reviewers: Option<usize>,
509    /// `--review-rounds`.
510    #[serde(default)]
511    pub review_rounds: Option<usize>,
512    /// `--seed`.
513    #[serde(default)]
514    pub seed: Option<u64>,
515    /// `--config`, absolute: the daemon's own working directory differs.
516    #[serde(default)]
517    pub config: Option<PathBuf>,
518}
519
520impl RunOverrides {
521    /// Lay `other` over these: every choice `other` made wins, the rest stay.
522    pub fn merge_over(&mut self, other: &RunOverrides) {
523        macro_rules! take {
524            ($($f:ident),*) => {$(
525                if other.$f.is_some() {
526                    self.$f.clone_from(&other.$f);
527                }
528            )*};
529        }
530        take!(
531            merge,
532            candidates,
533            judges,
534            reviewers,
535            review_rounds,
536            seed,
537            config
538        );
539    }
540
541    /// Apply these on top of `config`.
542    pub fn apply(&self, config: &mut crate::config::Config) {
543        if let Some(n) = self.candidates {
544            config.graph.implementers = n;
545        }
546        if let Some(n) = self.judges {
547            config.graph.judges = n;
548        }
549        if let Some(n) = self.reviewers {
550            config.graph.reviewers = n;
551        }
552        if let Some(n) = self.review_rounds {
553            config.graph.review_rounds = n;
554        }
555        if let Some(m) = &self.merge
556            && let Ok(mode) = crate::daemon::merge_mode(m)
557        {
558            config.merge.mode = mode;
559        }
560        if let Some(s) = self.seed {
561            config.blind.seed = Some(s);
562        }
563    }
564}
565
566/// What a follow-up task came from. See [`Task::followup`].
567#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
568pub struct FollowUp {
569    /// The merged run whose open findings this task carries.
570    pub run: String,
571    /// The queue task that run served, when it had one.
572    #[serde(default)]
573    pub origin_task: Option<String>,
574    /// The merged pull request.
575    pub pr: String,
576    /// Ids of the findings (e.g. `R3-1-1`) this task covers.
577    pub findings: Vec<String>,
578    /// Follow-up depth: 1 for a follow-up of an ordinary task's run, 2 for a
579    /// follow-up of that, and so on. An ordinary task is generation 0.
580    pub generation: u32,
581}
582
583/// A triage "resume" answer and what became of it. See
584/// [`Task::resume_override`].
585#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
586pub struct OperatorResume {
587    /// The triage question the operator answered.
588    pub question_id: String,
589    /// When the answer was applied.
590    pub at: Timestamp,
591    /// The reason `crate::conduct` gave for holding the task again after the
592    /// answer, if it did. The conductor may do this once.
593    #[serde(default)]
594    pub conductor_rehold: Option<String>,
595    /// The operator answered "resume" a second time, to the question about
596    /// that contradiction: the conductor may no longer hold this task.
597    #[serde(default)]
598    pub forced: bool,
599    /// Set when the answer was a structured `resume` action on a `magi ask`
600    /// choice ([`crate::ask::ChoiceAction::Resume`]): the run the operator
601    /// chose to continue. Its presence also stops `crate::conduct` from
602    /// requeuing the task into a fresh competition, which would discard
603    /// exactly the run that was named. Cleared with the rest of the record
604    /// once the task runs. `#[serde(default)]` so older records read as `None`.
605    #[serde(default)]
606    pub pinned_run: Option<String>,
607}
608
609/// One question `crate::conduct` asked about a task, and what the operator
610/// said back. See [`Task::answers`].
611#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
612pub struct AnsweredQuestion {
613    /// The question as asked, e.g. [`crate::ask::Question::summary`].
614    pub question: String,
615    /// What the operator answered.
616    pub answer: String,
617}
618
619impl Task {
620    /// File a new task. Persist it with [`Queue::put`].
621    pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
622        let now = Timestamp::now();
623        let origin_chat = match &source {
624            Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
625            _ => None,
626        };
627        Self {
628            schema: SCHEMA,
629            id: new_id(),
630            title,
631            instruction,
632            repo,
633            source,
634            priority: 0,
635            solo: false,
636            status: TaskStatus::Queued,
637            attempts: 0,
638            runs: Vec::new(),
639            last_error: None,
640            hold_reason: None,
641            hold_source: None,
642            diagnostic: None,
643            blocked_by: Vec::new(),
644            block_reason: None,
645            blocked_from: None,
646            answers: Vec::new(),
647            triage_applied: Vec::new(),
648            actions_applied: Vec::new(),
649            resume_override: None,
650            review_branch: None,
651            fresh_start: false,
652            interrupt: false,
653            urgent: false,
654            attachments: Vec::new(),
655            followup: None,
656            origin_chat,
657            overrides: None,
658            review_of: None,
659            held_at: None,
660            park_reason: None,
661            created_at: now,
662            updated_at: now,
663        }
664    }
665
666    /// The chat this task itself says it came from: the recorded
667    /// [`Task::origin_chat`], else its own source when a chat filed it.
668    pub fn chat_talk(&self) -> Option<&str> {
669        if let Some(id) = &self.origin_chat {
670            return Some(id);
671        }
672        match &self.source {
673            Source::Agent { run, node } if node == CHAT_NODE => Some(run),
674            _ => None,
675        }
676    }
677
678    /// Short form used in reports, matching a run's short id.
679    pub fn short(&self) -> &str {
680        short(&self.id)
681    }
682
683    /// Record that triage question `question_id`'s answer has been applied.
684    pub fn mark_triage_applied(&mut self, question_id: &str) {
685        if !self.triage_applied(question_id) {
686            self.triage_applied.push(question_id.to_owned());
687        }
688    }
689
690    /// Has the action of `magi ask` question `question_id` already been
691    /// applied, or is it being applied now? See [`Task::actions_applied`].
692    pub fn action_applied(&self, question_id: &str) -> bool {
693        self.actions_applied.iter().any(|id| id == question_id)
694    }
695
696    /// Record that `magi ask` question `question_id`'s action was applied.
697    pub fn mark_action_applied(&mut self, question_id: &str) {
698        if !self.action_applied(question_id) {
699            self.actions_applied.push(question_id.to_owned());
700        }
701    }
702
703    /// Has triage question `question_id`'s answer already been applied?
704    pub fn triage_applied(&self, question_id: &str) -> bool {
705        self.triage_applied.iter().any(|id| id == question_id)
706    }
707
708    /// Record that a run has started for this task.
709    ///
710    /// Clears [`Task::interrupt`]: a mark to run ahead of whatever else is
711    /// in flight is fulfilled the moment this task actually gets its turn,
712    /// dispatched same as any other. Without this, a task whose run fails
713    /// and requeues - still `runnable`, still carrying the mark from its
714    /// first attempt - would keep re-triggering `crate::daemon`'s interrupt
715    /// scheduler and re-parking whatever it interrupted on every later
716    /// boundary, for as long as its attempts hold out, instead of the
717    /// one-shot "let this go next" the mark is meant to be.
718    pub fn start(&mut self, run: String) {
719        self.status = TaskStatus::Running;
720        self.attempts += 1;
721        self.runs.push(run);
722        self.last_error = None;
723        self.park_reason = None;
724        self.fresh_start = false;
725        self.interrupt = false;
726        // The answer has been honoured: the task got its turn.
727        self.resume_override = None;
728    }
729
730    /// Note that `run` serves this task without otherwise changing its life:
731    /// no status, attempt or interrupt change, unlike [`Task::start`]. For a
732    /// run somebody else started on the task's behalf (`magi run --task`);
733    /// idempotent. Returns whether anything was added.
734    pub fn link_run(&mut self, run: &str) -> bool {
735        if self.runs.iter().any(|r| r == run) {
736            return false;
737        }
738        self.runs.push(run.to_owned());
739        true
740    }
741
742    /// Record a successful run.
743    ///
744    /// Both `magi task done` and `POST /api/queue/{id}/done` can close a held
745    /// *or blocked* task directly, with no release in between, so this clears
746    /// `hold_reason` and `blocked_by`/`block_reason` the same way
747    /// [`Task::release`] does. Otherwise a task held for "waiting on 3ed9", or
748    /// blocked on a dependency that never actually finished, and then closed
749    /// as done without ever being released would still read as waiting on
750    /// something in `magi task show` and on its card, after it no longer is.
751    pub fn succeed(&mut self) {
752        self.status = TaskStatus::Done;
753        self.resume_override = None;
754        self.last_error = None;
755        self.park_reason = None;
756        self.hold_reason = None;
757        self.hold_source = None;
758        self.diagnostic = None;
759        self.blocked_by.clear();
760        self.block_reason = None;
761        self.blocked_from = None;
762    }
763
764    /// Finish the task because the run's whole change turned out to be on the
765    /// base already ([`crate::run::RunStatus::AlreadyInBase`]): `Done`, with
766    /// `note` kept in [`Task::last_error`] so `magi task show` says why, and
767    /// the attempt refunded. Nothing went wrong and nothing was spent
768    /// misbehaving, so this is neither [`Task::fail`] nor
769    /// [`Task::handed_off`]; and unlike [`Task::succeed`] it does not pretend
770    /// the run landed anything.
771    pub fn already_landed(&mut self, note: impl Into<String>) {
772        self.succeed();
773        self.attempts = self.attempts.saturating_sub(1);
774        self.last_error = Some(note.into());
775    }
776
777    /// Earlier attempts at this task that a later one has since made moot —
778    /// empty unless the task is [`TaskStatus::Done`] *and* `last_run_succeeded`
779    /// says `runs.last()` is actually why.
780    ///
781    /// `runs` is oldest first, and [`Task::start`] is the only thing that
782    /// pushes to it, always right before the attempt it names either succeeds
783    /// or fails; `succeed` itself never touches `runs`. So whenever `status`
784    /// is `Done` *because* the loop itself saw that last attempt land
785    /// (`Merged`/`Ready`), everything before it in the same list is a retry
786    /// this task no longer needs. But `succeed` is also reachable directly —
787    /// `magi task done`, the web UI's equivalent, and the conductor's
788    /// `Recovery::Done` all call it on a task in *any* status, including one
789    /// whose last recorded attempt never landed at all (closed by hand after
790    /// a merge magi's own loop never saw). `runs.last()` alone cannot tell
791    /// those two cases apart — that requires the caller to have actually
792    /// looked at that run's own `status`, which this module has no way to
793    /// do — so `last_run_succeeded` is the caller's answer to exactly that
794    /// question, not something this function can derive from `Task` alone.
795    ///
796    /// Deliberately narrower than [`Queue::superseded`]'s "every earlier
797    /// attempt has a later one" walk, which fires the moment a retry starts
798    /// even though the retry itself might still fail: that reading is right
799    /// for the web UI's "a newer attempt exists, go look at that one
800    /// instead" note, but wrong for deciding a run no longer needs a human's
801    /// attention, which is only true once the task's story has actually
802    /// ended well. Two Blocked runs sitting side by side while a third
803    /// attempt is still in flight must not be touched by this — see
804    /// `daemon::supersede_prior_runs`, the caller that turns this list into
805    /// rewritten `run.json` files.
806    pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
807        if self.status != TaskStatus::Done || !last_run_succeeded || self.runs.len() < 2 {
808            return &[];
809        }
810        &self.runs[..self.runs.len() - 1]
811    }
812
813    /// The attempt right after `run` in this task's history, if there is one.
814    ///
815    /// The one place "a later attempt replaced this run" is decided:
816    /// [`Queue::superseded`] and [`Queue::superseded_by`] (the web UI's
817    /// note) read it, and so does [`Task::earlier_attempts`], so what is shown
818    /// and what `crate::handover` acts on cannot disagree.
819    pub fn successor_of(&self, run: &str) -> Option<&String> {
820        let pos = self.runs.iter().position(|r| r == run)?;
821        self.runs.get(pos + 1)
822    }
823
824    /// Every run already recorded for this task, i.e. every run that an
825    /// attempt being minted *right now* supersedes.
826    ///
827    /// The new run is not in [`Task::runs`] yet when it decides what to take
828    /// over (`Task::start` pushes it afterwards), so "has a later attempt" is
829    /// true of everything listed here by the time the new run exists.
830    pub fn earlier_attempts(&self) -> &[String] {
831        &self.runs
832    }
833
834    /// Stamp [`Task::held_at`] on the way into [`TaskStatus::Held`]; a task
835    /// that is already held keeps the time its hold began.
836    fn note_held(&mut self) {
837        if self.status != TaskStatus::Held || self.held_at.is_none() {
838            self.held_at = Some(Timestamp::now());
839        }
840    }
841
842    /// Record a failed attempt. Out of attempts means held for a human, rather
843    /// than retried until the money runs out.
844    ///
845    /// Clears [`Task::diagnostic`] unconditionally: it belongs to whatever run
846    /// produced it, and a caller that has one for *this* attempt sets it
847    /// itself right after calling this, once it knows the task actually ended
848    /// up [`TaskStatus::Held`] - see `daemon::diagnostic`. Without the clear, a
849    /// task released after a diagnosed hold and then failed again for an
850    /// unrelated, undiagnosed reason (a config error, say) would go on
851    /// showing the previous run's diagnostic as if it explained the new one.
852    ///
853    /// Also records `why` into [`Task::hold_reason`] when this ends up
854    /// [`TaskStatus::Held`], so the notification and `magi task show` say the
855    /// same thing as [`Task::last_error`] instead of leaving the hold's own
856    /// reason blank.
857    pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
858        let why = why.into();
859        self.diagnostic = None;
860        self.park_reason = None;
861        self.status = if self.attempts >= max_attempts {
862            self.note_held();
863            self.hold_source = Some(HoldSource::Machine);
864            self.hold_reason = Some(why.clone());
865            TaskStatus::Held
866        } else {
867            TaskStatus::Failed
868        };
869        self.last_error = Some(why);
870    }
871
872    /// Record an attempt that failed for a reason the task is not responsible
873    /// for - the agent CLIs ran out of quota and the judging panel collapsed.
874    ///
875    /// This refunds the attempt on purpose. A quota window closing at 4am must
876    /// not spend the backlog's retry budget: the operator would come back to a
877    /// queue of held tasks that were never actually judged, and would have to
878    /// release every one by hand to find out which had a real problem. The task
879    /// goes back to `Failed`, which the loop retries, so a reset quota picks the
880    /// work up where it stopped.
881    pub fn stall(&mut self, why: impl Into<String>) {
882        self.last_error = Some(why.into());
883        self.diagnostic = None;
884        self.attempts = self.attempts.saturating_sub(1);
885        self.status = TaskStatus::Failed;
886    }
887
888    /// Record a run that parked at a node boundary. Nothing failed: the attempt
889    /// is refunded, [`Task::last_error`] is left as it was, the run history and
890    /// `fresh_start` are kept so the next loop resumes the same run, and the
891    /// reason goes to [`Task::park_reason`]. Runnable like a requeued task and
892    /// never counted against `max_attempts`.
893    pub fn park(&mut self, why: impl Into<String>) {
894        self.diagnostic = None;
895        self.attempts = self.attempts.saturating_sub(1);
896        self.status = TaskStatus::Parked;
897        self.park_reason = Some(why.into());
898        // The variant and field are schema 11; stamp it so an older build
899        // refuses the record instead of half-reading it.
900        self.schema = self.schema.max(SCHEMA);
901    }
902
903    /// Whether this held task may only be released by an operator.
904    ///
905    /// Old files did not record a source. Preserve every such hold rather
906    /// than guessing that it was automatic and risking duplicate work. New
907    /// automatic holds record [`HoldSource::Machine`] and remain recoverable.
908    pub fn operator_held(&self) -> bool {
909        self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
910    }
911
912    /// Take this task out of the loop's reach by an operator action.
913    ///
914    /// Clears `blocked_by`/`block_reason` unconditionally, the same as
915    /// [`Task::release`] and for the same reason its own comment already
916    /// gives: a human choosing to hold a *blocked* task overrides its wait
917    /// outright, the same as it overrides an ordinary hold. Without this, a
918    /// task held straight out of [`TaskStatus::Blocked`] - the web UI's "Hold"
919    /// button is reachable on a blocked task, same as "Mark done" - kept
920    /// reading as still waiting on a dependency it no longer had any claim on.
921    pub fn hold_manual(&mut self, reason: Option<String>) {
922        self.park_reason = None;
923        self.note_held();
924        self.status = TaskStatus::Held;
925        if reason.is_some() {
926            self.hold_reason = reason;
927        }
928        self.hold_source = Some(HoldSource::Manual);
929        self.blocked_by.clear();
930        self.block_reason = None;
931        self.blocked_from = None;
932    }
933
934    /// Take this task out of the loop's reach during automatic recovery.
935    ///
936    /// Clears `blocked_by`/`block_reason` for the same reason
937    /// [`Task::hold_manual`] does.
938    pub fn hold_machine(&mut self, reason: Option<String>) {
939        self.park_reason = None;
940        self.note_held();
941        self.status = TaskStatus::Held;
942        if reason.is_some() {
943            self.hold_reason = reason;
944        }
945        self.hold_source = Some(HoldSource::Machine);
946        self.blocked_by.clear();
947        self.block_reason = None;
948        self.blocked_from = None;
949    }
950
951    /// Block this task on other task ids and/or open question ids, chosen by
952    /// `crate::conduct`. Pure: the caller still owns writing it back with
953    /// [`Queue::put`].
954    ///
955    /// Records [`Task::blocked_from`] the first time this moves the task into
956    /// [`TaskStatus::Blocked`], and leaves it alone on a later call that adds
957    /// or replaces `blocked_by` while the task is already `Blocked` - a
958    /// second question about an already-blocked task must not overwrite the
959    /// status it should eventually return to with `Blocked` itself.
960    pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
961        if self.status != TaskStatus::Blocked {
962            self.blocked_from = Some(self.status);
963        }
964        self.status = TaskStatus::Blocked;
965        self.blocked_by = blocked_by;
966        self.block_reason = reason;
967    }
968
969    /// Remove one resolved dependency (a task id that became [`TaskStatus::Done`],
970    /// or a question id that became [`crate::ask::QuestionStatus::Answered`]).
971    /// Once nothing is left in [`Task::blocked_by`], the task returns to
972    /// whatever [`Task::blocked_from`] recorded - deciding *why* a task was
973    /// blocked was `crate::conduct`'s job, but noticing a dependency resolved
974    /// needs no model at all, and restoring the status it interrupted needs
975    /// nothing more than what `block` already wrote down.
976    ///
977    /// A task blocked while `Running` restores to [`TaskStatus::Queued`]
978    /// instead: whatever process was running it is gone by the time this
979    /// runs, so there is nothing left to resume. A task with no recorded
980    /// `blocked_from` - a pre-schema-4 record, or one blocked before this
981    /// field existed - falls back to [`TaskStatus::Held`] when it still
982    /// carries hold evidence ([`Task::hold_reason`] or [`Task::hold_source`],
983    /// neither ever cleared by `block`), and to `Queued` otherwise: the same
984    /// choice `block` itself would have recorded, reconstructed from what
985    /// survived.
986    ///
987    /// A no-op, on purpose, for a task that is not [`TaskStatus::Blocked`]:
988    /// `crate::daemon`'s deterministic resolver runs over every task on every
989    /// poll, and a task that moved on for some other reason must not be
990    /// dragged back by a stale id it still happens to carry.
991    pub fn unblock(&mut self, resolved_id: &str) {
992        if self.status != TaskStatus::Blocked {
993            return;
994        }
995        self.blocked_by.retain(|id| id != resolved_id);
996        self.restore_if_unblocked();
997    }
998
999    /// A dependency this task waited on was deleted on purpose
1000    /// ([`Queue::remove`]): drop just that id from [`Task::blocked_by`] and,
1001    /// once nothing is left, return to the status the block interrupted, the
1002    /// same way [`Task::unblock`] does. Returns whether anything changed.
1003    ///
1004    /// Never a hold: the operator chose the deletion, so the dependent is not
1005    /// in trouble. Touches nothing but a `Blocked` task that actually names
1006    /// `deleted_id`, so a `Held` task (or a manual hold) is left exactly as it
1007    /// was. A dependency that vanished *without* going through a deletion is
1008    /// not this method's case - that stays a machine hold.
1009    pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
1010        if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
1011            return false;
1012        }
1013        self.blocked_by.retain(|id| id != deleted_id);
1014        self.restore_if_unblocked();
1015        true
1016    }
1017
1018    /// The shared tail of [`Task::unblock`] and [`Task::dependency_deleted`]:
1019    /// with nothing left in `blocked_by`, restore the interrupted status and
1020    /// clear the now-stale block bookkeeping.
1021    fn restore_if_unblocked(&mut self) {
1022        if self.blocked_by.is_empty() {
1023            self.status = match self.blocked_from {
1024                Some(TaskStatus::Running) => TaskStatus::Queued,
1025                Some(other) => other,
1026                None if self.hold_reason.is_some() || self.hold_source.is_some() => {
1027                    TaskStatus::Held
1028                }
1029                None => TaskStatus::Queued,
1030            };
1031            self.block_reason = None;
1032            self.blocked_from = None;
1033        }
1034    }
1035
1036    /// Record that a question `crate::conduct` asked about this task has been
1037    /// answered, so the answer's content — not just the fact that the
1038    /// question is gone — reaches the next conductor prompt and the next
1039    /// run's instruction. See [`Task::answers`].
1040    pub fn record_answer(&mut self, question: String, answer: String) {
1041        self.answers.push(AnsweredQuestion { question, answer });
1042    }
1043
1044    /// Requeue this task to reopen its last run as a review-only pass against
1045    /// `branch` (`crate::graph::Runner::review`) rather than competing from
1046    /// scratch. See [`Task::review_branch`].
1047    pub fn request_review(&mut self, branch: String) {
1048        self.release();
1049        self.review_branch = Some(branch);
1050    }
1051
1052    /// Requeue after a conductor chose a new competition. Unlike an ordinary
1053    /// operator release, this deliberately does not resume the old run.
1054    pub fn requeue(&mut self) {
1055        self.release();
1056        // A fresh competition is the opposite of a review of the old branch.
1057        self.review_branch = None;
1058        self.fresh_start = true;
1059    }
1060
1061    /// Hold this task because a takeover of `branch` was refused, keeping
1062    /// [`Task::review_branch`] so that once the operator has cleaned up and
1063    /// released it, the retry is a review of the same branch rather than a
1064    /// resume or a fresh competition. Spends no attempt.
1065    ///
1066    /// This is the only way a machine hold keeps a `review_branch`: the
1067    /// daemon takes it at the start of every attempt, so [`Task::release`]
1068    /// relies on that to tell this hold from every other.
1069    pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
1070        if branch.is_some() {
1071            self.review_branch = branch;
1072        }
1073        self.hold_machine(Some(reason));
1074    }
1075
1076    /// Change how urgently this task should run next.
1077    ///
1078    /// Refused once the task is `running`: priority only feeds the sort
1079    /// [`Queue::next_runnable`] does over tasks waiting to be claimed, and a
1080    /// running task has already left that pool. Accepting the write anyway
1081    /// would look like it worked while changing nothing until - and unless -
1082    /// this attempt fails and the task becomes runnable again, which is a
1083    /// surprise the phone should not hand back as a success.
1084    pub fn set_priority(&mut self, priority: i32) -> Result<()> {
1085        if self.status == TaskStatus::Running {
1086            bail!(
1087                "task {} is running; its priority cannot be changed until \
1088                 this attempt finishes",
1089                self.short()
1090            );
1091        }
1092        self.priority = priority;
1093        Ok(())
1094    }
1095
1096    /// Mark (or unmark) this task to interrupt whatever `magi serve` already
1097    /// has in flight, once `[daemon] pause_for_interrupts` is on. See
1098    /// [`Task::interrupt`].
1099    ///
1100    /// Setting it is restricted to a task the loop could pick up on its own
1101    /// right now - [`TaskStatus::runnable`] - for the same reason as
1102    /// [`Task::set_priority`]: a task already `running` has been claimed, and
1103    /// a task that is `done`, `held`, or `blocked` is not going to compete
1104    /// for the daemon's attention regardless of this flag. Unlike priority,
1105    /// this is never silently inert while `running` - it is refused outright,
1106    /// because the entire feature this flag drives (`crate::daemon`'s
1107    /// interrupt scheduler) is scoped to tasks still waiting to be claimed.
1108    /// Clearing it back to `false` carries no such risk and is always
1109    /// allowed, including on a task that moved on since it was set.
1110    pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
1111        if interrupt && !self.status.runnable() {
1112            bail!(
1113                "task {} is {}; only a queued or failed task can be marked \
1114                 to interrupt",
1115                self.short(),
1116                self.status.as_str()
1117            );
1118        }
1119        self.interrupt = interrupt;
1120        Ok(())
1121    }
1122
1123    /// Replace this task's title and instruction wholesale.
1124    ///
1125    /// Restricted to `queued` and `held`. A `running` task's instruction has
1126    /// already been handed to the graph, so a run in flight and the file on
1127    /// disk must not be allowed to disagree about what was asked; a `done` or
1128    /// `failed` task is a record of what actually happened and editing it
1129    /// after the fact would falsify that record. `id`, `created_at`,
1130    /// `source`, and `runs` are left untouched on purpose - an edit stands in
1131    /// for "delete and refile", and keeping the id, the timestamp, the
1132    /// attribution, and the run history is the entire reason it exists
1133    /// instead.
1134    pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
1135        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
1136            bail!(
1137                "task {} is {}; only a queued or held task's instruction can \
1138                 be edited",
1139                self.short(),
1140                self.status.as_str()
1141            );
1142        }
1143        self.title = title;
1144        self.instruction = instruction;
1145        Ok(())
1146    }
1147
1148    /// Record a run that produced a pull request without merging it.
1149    ///
1150    /// The task is held rather than retried, and it costs no further attempt
1151    /// either way. The work the task asked for exists: it is sitting on a
1152    /// branch, in a pull request, waiting for CI or for a person. Retrying
1153    /// would spend the whole competition budget a second time and then race a
1154    /// second branch against the pull request the first one opened - which is
1155    /// exactly what happened to run 01c2, whose finished and green pull request
1156    /// was re-competed from scratch four seconds after it opened.
1157    ///
1158    /// A pull request nobody merged is a request for a person, not a failure.
1159    ///
1160    /// Records `why` into [`Task::hold_reason`] as well as
1161    /// [`Task::last_error`], so the notification centre and `magi task show`
1162    /// say why the task is held rather than "no reason recorded". This is
1163    /// also the path a verified no-op with an outstanding `magi ask` question
1164    /// settles through - see `daemon::settle` and `daemon::settle_and_diagnose`,
1165    /// which append the question id to `hold_reason` when one is still open
1166    /// for the run.
1167    pub fn handed_off(&mut self, why: impl Into<String>) {
1168        let why = why.into();
1169        self.diagnostic = None;
1170        self.note_held();
1171        self.status = TaskStatus::Held;
1172        self.hold_source = Some(HoldSource::Machine);
1173        self.hold_reason = Some(why.clone());
1174        self.last_error = Some(why);
1175    }
1176
1177    /// Put a held or finished task back in line, with its attempt count reset
1178    /// so a release is a real second chance rather than an instant re-hold.
1179    /// The run history is kept: attempts reset, evidence does not.
1180    pub fn release(&mut self) {
1181        let refused_handover = self.status == TaskStatus::Held
1182            && self.hold_source == Some(HoldSource::Machine)
1183            && self.review_branch.is_some();
1184        self.status = TaskStatus::Queued;
1185        self.held_at = None;
1186        self.attempts = 0;
1187        self.last_error = None;
1188        self.park_reason = None;
1189        // Otherwise the next person who holds this task reads a reason that
1190        // belonged to whatever it was waiting on last time.
1191        self.hold_reason = None;
1192        self.hold_source = None;
1193        self.diagnostic = None;
1194        // A release also un-blocks: the dependency or question `blocked_by`
1195        // named may still be unresolved, but a human (or `crate::conduct`)
1196        // choosing to release the task overrides that wait outright, the same
1197        // as it overrides an ordinary hold.
1198        self.blocked_by.clear();
1199        self.block_reason = None;
1200        self.blocked_from = None;
1201        // A machine hold that still names a review branch is a refused
1202        // handover (see [`Task::hold_for_handover`]): the retry must review
1203        // that same branch. Any other release drops it.
1204        if !refused_handover {
1205            self.review_branch = None;
1206        }
1207        self.fresh_start = false;
1208    }
1209}
1210
1211/// Copy `src` into `dir` as `name`, or `stem-2.ext`, `stem-3.ext`, ... when
1212/// that is taken. `create_new` makes the collision check atomic and also
1213/// catches a case-insensitive filesystem. Returns the stored name and path.
1214fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
1215    use std::io::ErrorKind;
1216    let (stem, ext) = match name.rfind('.') {
1217        Some(i) if i > 0 => (&name[..i], &name[i..]),
1218        _ => (name, ""),
1219    };
1220    for n in 1u32.. {
1221        let candidate = if n == 1 {
1222            name.to_owned()
1223        } else {
1224            let suffix = format!("-{n}");
1225            let room = 64usize.saturating_sub(suffix.len() + ext.len());
1226            let stem: String = stem.chars().take(room).collect();
1227            format!("{stem}{suffix}{ext}")
1228        };
1229        if !crate::ask::valid_asset_name(&candidate) {
1230            bail!("no valid attachment name is left for `{name}`");
1231        }
1232        let path = dir.join(&candidate);
1233        match std::fs::OpenOptions::new()
1234            .write(true)
1235            .create_new(true)
1236            .open(&path)
1237        {
1238            Ok(mut out) => {
1239                let copied = std::fs::File::open(src)
1240                    .and_then(|mut input| std::io::copy(&mut input, &mut out));
1241                if let Err(e) = copied {
1242                    drop(out);
1243                    let _ = std::fs::remove_file(&path);
1244                    return Err(e).with_context(|| format!("copy {}", src.display()));
1245                }
1246                return Ok((candidate, path));
1247            }
1248            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
1249            Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
1250        }
1251    }
1252    unreachable!("the counter never runs out")
1253}
1254
1255/// How long a task's write lock may stand before it is read as left behind by
1256/// a writer that died.
1257const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
1258
1259/// Guard for [`Queue::lock_task`]; removes the lock file on drop, but only
1260/// while the file still carries this guard's owner token.
1261struct TaskLock {
1262    path: PathBuf,
1263    token: String,
1264}
1265
1266/// A token no other holder shares: pid, then a mix of entropy and a process
1267/// counter so threads born in the same nanosecond still differ.
1268fn owner_token() -> String {
1269    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
1270    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
1271    let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
1272    format!("{}-{:016x}", std::process::id(), r.next_u64())
1273}
1274
1275/// The marker that serializes everyone removing the lock that carries `token`.
1276/// Hashed (FNV-1a) so an empty or foreign token is still a valid file name.
1277fn break_marker(path: &Path, token: &str) -> PathBuf {
1278    let mut h: u64 = 0xcbf29ce484222325;
1279    for b in token.bytes() {
1280        h ^= u64::from(b);
1281        h = h.wrapping_mul(0x100000001b3);
1282    }
1283    let mut name = path.as_os_str().to_owned();
1284    name.push(format!(".break-{h:016x}"));
1285    PathBuf::from(name)
1286}
1287
1288fn older_than_stale(path: &Path) -> bool {
1289    std::fs::metadata(path)
1290        .and_then(|m| m.modified())
1291        .ok()
1292        .and_then(|t| t.elapsed().ok())
1293        .is_some_and(|age| age > TASK_LOCK_STALE)
1294}
1295
1296/// How many levels of "a stale marker guarding a stale marker" are recovered
1297/// before giving up. Each level needs its own crashed remover, so the cap is
1298/// never reached without several independent crashes.
1299const MAX_MARKER_DEPTH: u8 = 3;
1300
1301/// Take the break marker for `token`, or `None` if another remover holds it.
1302/// The marker carries its own owner token. One older than [`TASK_LOCK_STALE`]
1303/// was left by a remover that died; it is cleared by the same compare-and-
1304/// remove discipline as a lock, guarded by a marker of its own, so a recoverer
1305/// that judged it stale cannot delete a fresh marker that replaced it.
1306fn take_marker(path: &Path, token: &str, depth: u8) -> Option<(PathBuf, String)> {
1307    use std::io::Write;
1308    let marker = break_marker(path, token);
1309    for _ in 0..2 {
1310        match std::fs::OpenOptions::new()
1311            .write(true)
1312            .create_new(true)
1313            .open(&marker)
1314        {
1315            Ok(mut f) => {
1316                let mine = owner_token();
1317                if f.write_all(mine.as_bytes()).is_err() {
1318                    drop(f);
1319                    let _ = std::fs::remove_file(&marker);
1320                    return None;
1321                }
1322                return Some((marker, mine));
1323            }
1324            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1325                let judged = std::fs::read_to_string(&marker).ok();
1326                match judged.filter(|_| older_than_stale(&marker)) {
1327                    Some(judged) if depth < MAX_MARKER_DEPTH => {
1328                        remove_lock_if(&marker, &judged, true, depth + 1)?;
1329                    }
1330                    _ => return None,
1331                }
1332            }
1333            Err(_) => return None,
1334        }
1335    }
1336    None
1337}
1338
1339/// Remove the lock at `path` if it still carries `token` (and, when
1340/// `require_stale`, is still stale). Removal is serialized per token by the
1341/// break marker, so a remover that judged an old lock cannot delete the fresh
1342/// one that replaced it. `None` means the marker was busy: try again.
1343fn remove_lock_if(path: &Path, token: &str, require_stale: bool, depth: u8) -> Option<bool> {
1344    let (marker, mine) = take_marker(path, token, depth)?;
1345    let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
1346        && (!require_stale || older_than_stale(path));
1347    if still {
1348        let _ = std::fs::remove_file(path);
1349    }
1350    // Release the marker only if it is still ours.
1351    if depth >= MAX_MARKER_DEPTH {
1352        if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
1353            let _ = std::fs::remove_file(&marker);
1354        }
1355    } else {
1356        let _ = remove_lock_if(&marker, &mine, false, depth + 1);
1357    }
1358    Some(still)
1359}
1360
1361/// Break the lock judged stale while it held `judged`. Returns whether it was
1362/// removed; a lock that has since been replaced is left alone.
1363fn break_stale(path: &Path, judged: &str) -> bool {
1364    remove_lock_if(path, judged, true, 0).unwrap_or(false)
1365}
1366
1367impl Drop for TaskLock {
1368    fn drop(&mut self) {
1369        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
1370        loop {
1371            match remove_lock_if(&self.path, &self.token, false, 0) {
1372                Some(_) => return,
1373                None if std::time::Instant::now() > deadline => return,
1374                None => std::thread::sleep(std::time::Duration::from_millis(5)),
1375            }
1376        }
1377    }
1378}
1379
1380/// A queue on disk.
1381#[derive(Debug, Clone)]
1382pub struct Queue {
1383    root: PathBuf,
1384}
1385
1386impl Queue {
1387    /// The operator's queue, `<home>/queue`.
1388    pub fn open() -> Self {
1389        Self::at(crate::run::home().join("queue"))
1390    }
1391
1392    /// A queue at an explicit root. Tests use this; so could an operator who
1393    /// wants a queue per project.
1394    pub fn at(root: PathBuf) -> Self {
1395        Self { root }
1396    }
1397
1398    /// Directory holding the task files.
1399    pub fn root(&self) -> &Path {
1400        &self.root
1401    }
1402
1403    /// Path for one task id.
1404    pub fn path_of(&self, id: &str) -> PathBuf {
1405        self.root.join(format!("{id}.json"))
1406    }
1407
1408    /// Directory holding a task's attachments. A sibling of the task file,
1409    /// not a `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
1410    pub fn attachments_dir(&self, id: &str) -> PathBuf {
1411        self.root.join(format!("{id}.attachments"))
1412    }
1413
1414    /// Copy each of `sources` into `task`'s attachment directory and record
1415    /// the stored names on `task` (persist with [`Queue::put`]). Returns the
1416    /// names, in order.
1417    ///
1418    /// Every source is checked (a readable file, a name passing
1419    /// [`crate::ask::valid_asset_name`]) before anything is copied, and a
1420    /// copy that fails part-way removes only what this call created. A name
1421    /// already taken is never overwritten: it becomes `stem-2.ext`,
1422    /// `stem-3.ext`, ... A name that does not validate is refused rather than
1423    /// sanitised - the operator renames the file.
1424    pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
1425        let mut wanted = Vec::new();
1426        for src in sources {
1427            let name = src
1428                .file_name()
1429                .and_then(|n| n.to_str())
1430                .with_context(|| format!("`{}` has no usable file name", src.display()))?;
1431            if !crate::ask::valid_asset_name(name) {
1432                bail!(
1433                    "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
1434                     with no `..`; rename the file and try again"
1435                );
1436            }
1437            if !src.is_file() {
1438                bail!("attachment `{}` is not a file", src.display());
1439            }
1440            wanted.push((src, name));
1441        }
1442        let dir = self.attachments_dir(&task.id);
1443        let existed = dir.is_dir();
1444        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
1445        let mut created: Vec<PathBuf> = Vec::new();
1446        let mut names = Vec::new();
1447        let mut copy_all = || -> Result<()> {
1448            for (src, name) in &wanted {
1449                let (stored, path) = copy_new(&dir, src, name)?;
1450                created.push(path);
1451                names.push(stored);
1452            }
1453            Ok(())
1454        };
1455        if let Err(e) = copy_all() {
1456            for path in &created {
1457                let _ = std::fs::remove_file(path);
1458            }
1459            if !existed {
1460                let _ = std::fs::remove_dir(&dir);
1461            }
1462            return Err(e);
1463        }
1464        task.attachments.extend(names.iter().cloned());
1465        Ok(names)
1466    }
1467
1468    /// [`Queue::attach`] then [`Queue::put`], undoing the copies when the
1469    /// record cannot be written. Without the undo the files sit in
1470    /// `<id>.attachments/` with no task pointing at them.
1471    ///
1472    /// Only what this call copied is removed (the names `attach` returned,
1473    /// and the directory itself only when it did not exist before and is
1474    /// empty), never an attachment an earlier save recorded. `task` is rolled
1475    /// back too, and the error the caller sees is `put`'s own. This relies on
1476    /// a failed `put` leaving the stored record untouched, which its
1477    /// write-then-rename guarantees.
1478    pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
1479        let dir = self.attachments_dir(&task.id);
1480        let existed = dir.is_dir();
1481        let before = task.attachments.len();
1482        let names = self.attach(task, sources)?;
1483        if let Err(e) = self.put(task) {
1484            for name in &names {
1485                let _ = std::fs::remove_file(dir.join(name));
1486            }
1487            if !existed {
1488                let _ = std::fs::remove_dir(&dir);
1489            }
1490            task.attachments.truncate(before);
1491            return Err(e);
1492        }
1493        Ok(names)
1494    }
1495
1496    /// Absolute paths of `task`'s attachments, whatever shape this queue's
1497    /// root has. Absolute because the prompt hands them to an agent whose
1498    /// working directory is somewhere else entirely.
1499    pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
1500        let dir = self.attachments_dir(&task.id);
1501        task.attachments
1502            .iter()
1503            .map(|n| {
1504                let p = dir.join(n);
1505                std::path::absolute(&p).unwrap_or(p)
1506            })
1507            .collect()
1508    }
1509
1510    /// Write a task, atomically, so a daemon killed mid-write leaves the
1511    /// previous state readable rather than a truncated file.
1512    ///
1513    /// Runs already recorded on disk that `task` does not carry are kept, not
1514    /// dropped: `magi run --task` links a run into a task from another
1515    /// process ([`Queue::link_run`]) while a daemon may hold a snapshot taken
1516    /// before it, and writing that snapshot back whole would erase the link.
1517    /// Nothing ever removes a run from a task, so the union loses nothing.
1518    pub fn put(&self, task: &mut Task) -> Result<()> {
1519        let _lock = self.lock_task(&task.id)?;
1520        self.put_unlocked(task)
1521    }
1522
1523    /// Write `task` only if no task with its id exists yet; `Ok(false)` when
1524    /// one does. Unlike [`Queue::put`] it never replaces a record, so a
1525    /// producer with a deterministic id cannot rewind a task that has since
1526    /// started running or finished.
1527    pub fn create_new(&self, task: &mut Task) -> Result<bool> {
1528        let _lock = self.lock_task(&task.id)?;
1529        if self.path_of(&task.id).exists() {
1530            return Ok(false);
1531        }
1532        self.put_unlocked(task)?;
1533        Ok(true)
1534    }
1535
1536    /// [`Queue::put`] for a caller already holding [`Queue::lock_task`].
1537    fn put_unlocked(&self, task: &mut Task) -> Result<()> {
1538        if let Ok(stored) = read_path(&self.path_of(&task.id)) {
1539            for run in stored.runs {
1540                if !task.runs.contains(&run) {
1541                    task.runs.push(run);
1542                }
1543            }
1544        }
1545        task.updated_at = Timestamp::now();
1546        std::fs::create_dir_all(&self.root)
1547            .with_context(|| format!("create {}", self.root.display()))?;
1548        let body = serde_json::to_string_pretty(task).context("serialize task")?;
1549        let path = self.path_of(&task.id);
1550        let tmp = path.with_extension("json.tmp");
1551        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
1552        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
1553        // A machine hold is news for the notification centre, filed beside
1554        // this queue (`<home>/queue` -> `<home>/notifications`) rather than
1555        // through a process-global, so a queue in a temp directory notifies
1556        // into that directory.
1557        if let (Some(notice), Some(home)) = (
1558            crate::notices::task_held(task),
1559            self.root.parent().filter(|p| !p.as_os_str().is_empty()),
1560        ) {
1561            crate::notices::raise_in(home, notice);
1562        }
1563        Ok(())
1564    }
1565
1566    /// Append `run` to the runs of the task `id` (or an unambiguous prefix),
1567    /// leaving everything else about it alone — see [`Task::link_run`]. Read
1568    /// and written back in one breath, because [`Queue::put`] replaces the
1569    /// whole record. Returns the task as stored.
1570    pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
1571        let id = self.resolve_id(id)?;
1572        // Read inside the lock, so the record written back is the current one
1573        // and a daemon's write cannot slip between the read and the write.
1574        let _lock = self.lock_task(&id)?;
1575        let mut task = self.get(&id)?;
1576        if task.link_run(run) {
1577            self.put_unlocked(&mut task)?;
1578        }
1579        Ok(task)
1580    }
1581
1582    /// Exclusive right to rewrite task `id`'s record, held until the guard
1583    /// drops. Every writer ([`Queue::put`], [`Queue::link_run`]) takes it, so
1584    /// a process linking a run and the daemon saving a transition are
1585    /// serialized instead of last-writer-wins. A lock older than
1586    /// [`TASK_LOCK_STALE`] belongs to a writer that died mid-update and is
1587    /// broken. Not the claim lock (`<id>.lock`), which a daemon holds for a
1588    /// whole run.
1589    fn lock_task(&self, id: &str) -> Result<TaskLock> {
1590        std::fs::create_dir_all(&self.root)
1591            .with_context(|| format!("create {}", self.root.display()))?;
1592        let path = self.root.join(format!("{id}.write-lock"));
1593        let started = std::time::Instant::now();
1594        loop {
1595            match std::fs::OpenOptions::new()
1596                .write(true)
1597                .create_new(true)
1598                .open(&path)
1599            {
1600                Ok(mut file) => {
1601                    use std::io::Write;
1602                    let token = owner_token();
1603                    if let Err(e) = file.write_all(token.as_bytes()) {
1604                        drop(file);
1605                        let _ = std::fs::remove_file(&path);
1606                        return Err(e).with_context(|| format!("lock {}", path.display()));
1607                    }
1608                    return Ok(TaskLock { path, token });
1609                }
1610                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1611                    // Content first, then age: a lock replaced in between
1612                    // reads fresh, never stale.
1613                    let judged = std::fs::read_to_string(&path).ok();
1614                    let broken = judged
1615                        .filter(|_| older_than_stale(&path))
1616                        .is_some_and(|judged| break_stale(&path, &judged));
1617                    // A break that does not happen (marker busy, recovery
1618                    // exhausted) is a wait like any other, so it meets the
1619                    // same deadline instead of spinning forever.
1620                    if !broken {
1621                        if started.elapsed() > TASK_LOCK_STALE {
1622                            bail!("could not lock task {id}");
1623                        }
1624                        std::thread::sleep(std::time::Duration::from_millis(15));
1625                    }
1626                }
1627                // On Windows, `create_new` on a file whose delete is still
1628                // pending fails with ERROR_ACCESS_DENIED, not `AlreadyExists`.
1629                // Treat it as a race and retry until the deadline.
1630                Err(e)
1631                    if e.kind() == std::io::ErrorKind::PermissionDenied
1632                        && started.elapsed() <= TASK_LOCK_STALE =>
1633                {
1634                    std::thread::sleep(std::time::Duration::from_millis(15));
1635                }
1636                Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
1637            }
1638        }
1639    }
1640
1641    /// Load a task by id or unambiguous id prefix.
1642    pub fn get(&self, id: &str) -> Result<Task> {
1643        let resolved = self.resolve_id(id)?;
1644        read_path(&self.path_of(&resolved))
1645    }
1646
1647    /// Remove a task, and the claim lock that belongs to it.
1648    ///
1649    /// `in_flight` comes from the caller — a live daemon's heartbeat naming
1650    /// this task — because the task's own `running` status cannot answer the
1651    /// question. A daemon killed mid-competition leaves the status at
1652    /// `running` and an orphaned `.lock` behind, and a guard that trusted
1653    /// either would make the task undeletable for good: the phone showed
1654    /// exactly that, refusing a task whose daemon had been gone for an hour.
1655    ///
1656    /// So the lock is removed with the task rather than respected. Any lock
1657    /// still there once no live daemon claims the task is by definition stale,
1658    /// and leaving it would make a deleted task look claimed to
1659    /// [`Queue::claim`] and to whoever reads the directory.
1660    ///
1661    /// A deletion is deliberate, so whatever was `blocked` on the id is
1662    /// resolved, not held: a `<id>.removed` tombstone is written first (it
1663    /// is what tells [`missing_blockers`] and the daemon's resolver that this
1664    /// id was deleted on purpose, so a pass that races this call cannot
1665    /// mistake it for a vanished dependency), the record is deleted (the
1666    /// tombstone is taken back if that fails), and then each dependent is
1667    /// rewritten under its claim - see [`Queue::release_dependents_of`].
1668    /// Best-effort for the dependents: one claimed by something else right
1669    /// now, or whose write fails, is released silently by
1670    /// `crate::daemon::resolve_blockers` (or `crate::triage::run_once`) on
1671    /// its next pass, because the tombstone is still there. It does not fail
1672    /// this removal.
1673    ///
1674    /// `questions` is the store [`missing_blockers`] checks a `blocked_by` id
1675    /// against - the same store the caller already resolves `id`'s own home
1676    /// from, passed in rather than reopened here so a test queue at an
1677    /// explicit root never reads the operator's real questions directory.
1678    pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
1679        let _ = questions;
1680        let resolved = self.resolve_id(id)?;
1681        if in_flight {
1682            bail!("task {resolved} is being run by a live daemon right now");
1683        }
1684        self.write_tombstone(&resolved)?;
1685        if let Err(e) = self.remove_record_with_attachments(&resolved, |p| std::fs::remove_file(p))
1686        {
1687            // A record that is still there was not deleted: take the marker
1688            // back. One already gone keeps it, so the deletion still reads
1689            // as deliberate.
1690            if self.path_of(&resolved).exists() {
1691                let _ = std::fs::remove_file(self.tombstone_path(&resolved));
1692            }
1693            return Err(e);
1694        }
1695        let (released, still_blocked) = self.release_dependents_of(&resolved);
1696        Ok(Removal {
1697            id: resolved,
1698            released,
1699            still_blocked,
1700        })
1701    }
1702
1703    /// Path of the marker saying task `id` was deleted on purpose. Not a
1704    /// `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
1705    fn tombstone_path(&self, id: &str) -> PathBuf {
1706        self.root.join(format!("{id}.removed"))
1707    }
1708
1709    fn write_tombstone(&self, id: &str) -> Result<()> {
1710        let path = self.tombstone_path(id);
1711        let tmp = self.root.join(format!("{id}.removed.tmp"));
1712        std::fs::write(&tmp, b"")
1713            .and_then(|()| std::fs::rename(&tmp, &path))
1714            .with_context(|| format!("write {}", path.display()))
1715    }
1716
1717    /// Was `id` deleted through [`Queue::remove`] (and is its record gone)?
1718    /// A live record always wins: a tombstone never makes an existing task
1719    /// look deleted.
1720    fn was_deleted(&self, id: &str) -> bool {
1721        self.tombstone_path(id).is_file() && !self.path_of(id).exists()
1722    }
1723
1724    /// Apply [`Task::dependency_deleted`] to `task` for every `blocked_by` id
1725    /// that [`Queue::remove`] deleted. Returns those ids. The caller holds
1726    /// the task's claim and saves it.
1727    pub fn apply_deleted_blockers(&self, task: &mut Task) -> Vec<String> {
1728        let deleted = deleted_blockers(self, &task.blocked_by);
1729        deleted
1730            .into_iter()
1731            .filter(|id| task.dependency_deleted(id))
1732            .collect()
1733    }
1734
1735    /// Record, as a fixed-wording info notice, that `dependent` stopped
1736    /// waiting on the deleted task `deleted`. Best-effort and beside the
1737    /// queue, like the hold notice [`Queue::put`] files.
1738    pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
1739        let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
1740            return;
1741        };
1742        let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
1743        let waiting = dependent.status == TaskStatus::Blocked;
1744        let message = match (ja, waiting) {
1745            (true, false) => format!(
1746                "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
1747                dependent.short(),
1748                short(deleted)
1749            ),
1750            (true, true) => format!(
1751                "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
1752                dependent.short(),
1753                short(deleted)
1754            ),
1755            (false, false) => format!(
1756                "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
1757                dependent.short(),
1758                short(deleted)
1759            ),
1760            (false, true) => format!(
1761                "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
1762                dependent.short(),
1763                short(deleted)
1764            ),
1765        };
1766        crate::notices::raise_in(
1767            home,
1768            crate::notices::Notice::info(
1769                &format!("unblocked:{}:{}", dependent.id, deleted),
1770                message,
1771            ),
1772        );
1773    }
1774
1775    /// Resolve every `blocked` task naming `dependency` (just deleted) with
1776    /// [`Task::dependency_deleted`]. Returns the ids released to another
1777    /// status and those that remain `blocked` on something else. Each
1778    /// dependent is re-read inside its claim, never written from a stale copy.
1779    fn release_dependents_of(&self, dependency: &str) -> (Vec<String>, Vec<String>) {
1780        let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
1781        for listed in self.list() {
1782            if listed.status != TaskStatus::Blocked
1783                || !listed.blocked_by.iter().any(|b| b == dependency)
1784            {
1785                continue;
1786            }
1787            let Ok(_claim) = self.claim(&listed.id) else {
1788                continue;
1789            };
1790            let Ok(mut task) = self.get(&listed.id) else {
1791                continue;
1792            };
1793            if !task.dependency_deleted(dependency) {
1794                continue;
1795            }
1796            if self.put(&mut task).is_err() {
1797                continue;
1798            }
1799            self.note_dependency_deleted(&task, dependency);
1800            if task.status == TaskStatus::Blocked {
1801                still_blocked.push(task.id.clone());
1802            } else {
1803                released.push(task.id.clone());
1804            }
1805        }
1806        (released, still_blocked)
1807    }
1808
1809    /// The attachment-and-record half of [`Queue::remove`]. `remove_record` is
1810    /// how the record file is deleted; production passes `remove_file`, and a
1811    /// test passes a failing one to prove the attachments come back.
1812    fn remove_record_with_attachments(
1813        &self,
1814        resolved: &str,
1815        remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
1816    ) -> Result<()> {
1817        // Neither step may strand the other. The attachments are set aside by a
1818        // rename (cheap, and undone if the record cannot be removed), then the
1819        // record goes, and only then is the set-aside directory deleted for
1820        // real. A failure before the record is gone loses nothing; a failure
1821        // after it leaves at most an orphan `.removing` directory, which the
1822        // next removal sweeps.
1823        self.sweep_removed_attachments();
1824        let attachments = self.attachments_dir(resolved);
1825        let aside = self.root.join(format!("{resolved}.attachments.removing"));
1826        let moved = match std::fs::rename(&attachments, &aside) {
1827            Ok(()) => true,
1828            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
1829            Err(e) => {
1830                return Err(e).with_context(|| format!("remove {}", attachments.display()));
1831            }
1832        };
1833        let path = self.path_of(resolved);
1834        if let Err(e) = remove_record(&path) {
1835            if moved {
1836                let _ = std::fs::rename(&aside, &attachments);
1837            }
1838            return Err(e).with_context(|| format!("remove {}", path.display()));
1839        }
1840        if moved {
1841            if let Err(e) = std::fs::remove_dir_all(&aside) {
1842                tracing::warn!("leftover attachments {}: {e}", aside.display());
1843            }
1844        }
1845        let lock = self.lock_path(resolved);
1846        if let Err(e) = std::fs::remove_file(&lock) {
1847            if e.kind() != std::io::ErrorKind::NotFound {
1848                return Err(e).with_context(|| format!("remove {}", lock.display()));
1849            }
1850        }
1851        Ok(())
1852    }
1853
1854    /// Delete `*.attachments.removing` directories a previous [`Queue::remove`]
1855    /// could not finish deleting. The task record is already gone by then, so
1856    /// the id no longer resolves and the removal cannot be retried by name;
1857    /// every later removal sweeps them instead. A directory whose record still
1858    /// exists belongs to a removal in progress and is left alone. Best-effort.
1859    fn sweep_removed_attachments(&self) {
1860        let Ok(entries) = std::fs::read_dir(&self.root) else {
1861            return;
1862        };
1863        for entry in entries.flatten() {
1864            let name = entry.file_name();
1865            let name = name.to_string_lossy();
1866            let Some(id) = name.strip_suffix(".attachments.removing") else {
1867                continue;
1868            };
1869            // A record still on disk means a removal is mid-flight (or about
1870            // to roll back): the directory is its to delete or restore.
1871            if !self.path_of(id).exists() {
1872                if let Err(e) = std::fs::remove_dir_all(entry.path()) {
1873                    tracing::warn!("leftover attachments {}: {e}", entry.path().display());
1874                }
1875            }
1876        }
1877        self.sweep_tombstones();
1878    }
1879
1880    /// Delete `*.removed` markers that are no longer needed: the record is
1881    /// gone, no task's `blocked_by` names the id, and the marker is older than
1882    /// [`TOMBSTONE_GRACE`]. The age is what makes this safe against a
1883    /// concurrent writer: the task list read here can be stale, so a dependent
1884    /// that was just blocked on an id (a conductor applying a decision while a
1885    /// removal is under way) would otherwise lose the marker and be held as a
1886    /// vanished dependency. A marker whose record still exists belongs to a
1887    /// removal in progress and is never touched.
1888    fn sweep_tombstones(&self) {
1889        let Ok(entries) = std::fs::read_dir(&self.root) else {
1890            return;
1891        };
1892        let tasks = self.list();
1893        for entry in entries.flatten() {
1894            let name = entry.file_name();
1895            let name = name.to_string_lossy();
1896            let Some(id) = name.strip_suffix(".removed") else {
1897                continue;
1898            };
1899            if self.path_of(id).exists()
1900                || tasks.iter().any(|t| t.blocked_by.iter().any(|b| b == id))
1901            {
1902                continue;
1903            }
1904            let old = entry
1905                .metadata()
1906                .and_then(|m| m.modified())
1907                .ok()
1908                .and_then(|m| m.elapsed().ok())
1909                .is_some_and(|age| age >= TOMBSTONE_GRACE);
1910            if old {
1911                let _ = std::fs::remove_file(entry.path());
1912            }
1913        }
1914    }
1915
1916    /// Path of the claim lock for a task. One definition, so `claim` and
1917    /// `remove` cannot end up naming different files.
1918    fn lock_path(&self, id: &str) -> PathBuf {
1919        self.root.join(format!("{id}.lock"))
1920    }
1921
1922    /// Every task on disk, highest priority first and newest first within a
1923    /// priority. This is what `magi task list` and `GET /api/queue` print, so
1924    /// a raised priority has to move a task here the moment it is saved, not
1925    /// only in [`Queue::next_runnable`]'s own ordering - the operator reading
1926    /// the backlog and the loop about to drain it must agree on what "first"
1927    /// means. Every existing task defaults to priority 0, so this is a no-op
1928    /// change from the old newest-first order for a queue nobody has
1929    /// reprioritised.
1930    ///
1931    /// Unreadable files are skipped rather than fatal: one corrupt task must
1932    /// not take the queue - or the web UI, or an unattended daemon - down
1933    /// with it.
1934    pub fn list(&self) -> Vec<Task> {
1935        let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
1936            .into_iter()
1937            .flatten()
1938            .flatten()
1939            .map(|e| e.path())
1940            .filter(|p| p.extension().is_some_and(|x| x == "json"))
1941            .filter_map(|p| read_path(&p).ok())
1942            .collect();
1943        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1944        tasks
1945    }
1946
1947    /// Runs that a later attempt at the same task replaced, mapped to the id
1948    /// of the attempt that replaced them.
1949    ///
1950    /// A task keeps its attempts in order, and the deck showed them as two
1951    /// cards with the same title and no hint which was which: yukimemi asked
1952    /// why `stalled` and `blocked` appeared twice for one task, and the
1953    /// answer - "those are two tries, and the second one exists because of a
1954    /// bug since fixed" - was not on the screen anywhere.
1955    ///
1956    /// Read from the queue rather than stored on the run, because the
1957    /// ordering is the queue's fact: a `RunState` has no idea another attempt
1958    /// happened after it.
1959    pub fn superseded(&self) -> HashMap<String, String> {
1960        let mut by = HashMap::new();
1961        for task in self.list() {
1962            for earlier in &task.runs {
1963                if let Some(later) = task.successor_of(earlier) {
1964                    by.insert(earlier.clone(), later.clone());
1965                }
1966            }
1967        }
1968        by
1969    }
1970
1971    /// Whether `run` is an earlier attempt a later one replaced, and if so
1972    /// the id of that later attempt.
1973    ///
1974    /// Same walk as [`Queue::superseded`], narrowed to one run: a run detail
1975    /// page asks about exactly one run at a time, and this keeps that call
1976    /// site from building (and discarding) the whole map's `HashMap` just to
1977    /// read one entry out of it.
1978    pub fn superseded_by(&self, run: &str) -> Option<String> {
1979        for task in self.list() {
1980            if task.runs.iter().any(|r| r == run) {
1981                return task.successor_of(run).cloned();
1982            }
1983        }
1984        None
1985    }
1986
1987    /// The task's own most recent attempt, when `run` belongs to that task
1988    /// but is not already that attempt.
1989    ///
1990    /// Distinct from [`Queue::superseded_by`], which names only the very
1991    /// next attempt: a chain of retries (A superseded by B superseded by C)
1992    /// leaves an older run pointing at an intermediate one that may itself
1993    /// be unresolved, and a run's own detail page needs to know where the
1994    /// task's story currently stands - the chain's current head, C - not an
1995    /// attempt in the middle of it that a client would otherwise have to
1996    /// walk to by hand.
1997    pub fn latest_attempt(&self, run: &str) -> Option<String> {
1998        for task in self.list() {
1999            if task.runs.iter().any(|r| r == run) {
2000                return task.runs.last().filter(|last| **last != run).cloned();
2001            }
2002        }
2003        None
2004    }
2005
2006    /// The task a daemon should run next, or `None` when the queue is idle.
2007    ///
2008    /// Highest priority first, oldest first within a priority, so a burst of
2009    /// agent-filed work cannot starve the task a human filed this morning.
2010    pub fn next_runnable(&self) -> Option<Task> {
2011        let mut runnable: Vec<Task> = self
2012            .list()
2013            .into_iter()
2014            .filter(|t| t.status.runnable())
2015            .collect();
2016        runnable.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
2017        runnable.into_iter().next()
2018    }
2019
2020    /// Take exclusive ownership of a task.
2021    ///
2022    /// The lock is a `create_new` file next to the task, which is atomic on
2023    /// every platform magi targets. It exists so two daemons - or a daemon and
2024    /// a human running `magi run` - cannot drive one task into two competing
2025    /// runs. The returned guard releases on drop, including on panic.
2026    pub fn claim(&self, id: &str) -> Result<Claim> {
2027        std::fs::create_dir_all(&self.root)
2028            .with_context(|| format!("create {}", self.root.display()))?;
2029        let path = self.lock_path(id);
2030        match std::fs::OpenOptions::new()
2031            .write(true)
2032            .create_new(true)
2033            .open(&path)
2034        {
2035            Ok(mut f) => {
2036                use std::io::Write as _;
2037                // Best effort: the pid is for the human looking at a stale lock.
2038                let _ = writeln!(f, "{}", std::process::id());
2039                Ok(Claim { path })
2040            }
2041            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2042                bail!("task {id} is already claimed ({} exists)", path.display())
2043            }
2044            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
2045        }
2046    }
2047
2048    /// Expand an id prefix to exactly one task id.
2049    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
2050        if self.path_of(prefix).is_file() {
2051            return Ok(prefix.to_owned());
2052        }
2053        let hits: Vec<String> = self
2054            .list()
2055            .into_iter()
2056            .map(|t| t.id)
2057            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
2058            .collect();
2059        match hits.len() {
2060            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
2061            0 => bail!("no task matches `{prefix}`"),
2062            _ => bail!(
2063                "`{prefix}` matches {} tasks: {}",
2064                hits.len(),
2065                hits.join(", ")
2066            ),
2067        }
2068    }
2069
2070    /// Change detection token for the queue.
2071    ///
2072    /// Combines file names and modification times of all task files in the
2073    /// queue, so adding, modifying, or deleting any task — even an older one —
2074    /// moves the revision and notifies connected clients via the change stream.
2075    /// Returns 0 when the queue is completely empty.
2076    pub fn revision(&self) -> u64 {
2077        self.revision_excluding(&std::collections::BTreeSet::new())
2078    }
2079
2080    /// [`Queue::revision`] ignoring the files of the named task ids, for a
2081    /// caller that tracks those tasks' content some other way.
2082    pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
2083        use std::hash::{Hash as _, Hasher as _};
2084
2085        let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
2086            .into_iter()
2087            .flatten()
2088            .flatten()
2089            .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
2090            .filter(|e| {
2091                let path = e.path();
2092                !path
2093                    .file_stem()
2094                    .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
2095            })
2096            .filter_map(|e| {
2097                let name = e.file_name().to_string_lossy().into_owned();
2098                let mtime = e
2099                    .metadata()
2100                    .ok()?
2101                    .modified()
2102                    .ok()?
2103                    .duration_since(std::time::UNIX_EPOCH)
2104                    .ok()?
2105                    .as_millis() as u64;
2106                Some((name, mtime))
2107            })
2108            .collect();
2109
2110        if entries.is_empty() {
2111            return 0;
2112        }
2113
2114        entries.sort_unstable();
2115        let mut hasher = std::hash::DefaultHasher::new();
2116        for (name, mtime) in &entries {
2117            name.hash(&mut hasher);
2118            mtime.hash(&mut hasher);
2119        }
2120        let h = hasher.finish();
2121        if h == 0 { 1 } else { h }
2122    }
2123}
2124
2125/// How long a deletion marker is kept after its record is gone, even with
2126/// nothing referencing it. See [`Queue::sweep_tombstones`].
2127const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
2128
2129/// What [`Queue::remove`] did, beyond deleting the named task's own file.
2130#[derive(Debug, Clone)]
2131pub struct Removal {
2132    /// The id actually removed - `id` expanded from a prefix, if it was one.
2133    pub id: String,
2134    /// Every task that was `blocked` on [`Removal::id`] and left the block
2135    /// (back to the status it interrupted) because that was its only
2136    /// remaining dependency.
2137    pub released: Vec<String>,
2138    /// Every task that named [`Removal::id`] and is still `blocked` on
2139    /// another dependency.
2140    pub still_blocked: Vec<String>,
2141}
2142
2143/// Exclusive ownership of a task, released on drop.
2144#[derive(Debug)]
2145pub struct Claim {
2146    path: PathBuf,
2147}
2148
2149impl Drop for Claim {
2150    fn drop(&mut self) {
2151        let _ = std::fs::remove_file(&self.path);
2152    }
2153}
2154
2155/// The first line of a task, trimmed to a title. Used when the caller gives a
2156/// body but no title, which is the normal case for an agent piping a file in.
2157pub fn title_from(instruction: &str, max: usize) -> String {
2158    let Some(line) = first_line(instruction) else {
2159        return "(empty task)".to_owned();
2160    };
2161    if line.chars().count() <= max {
2162        return line.to_owned();
2163    }
2164    let head: String = line.chars().take(max.saturating_sub(1)).collect();
2165    format!("{head}…")
2166}
2167
2168/// The first non-blank line, whatever it is. A markdown heading is the
2169/// task's own summary - agents pipe in `# Rework the config loader` and mean
2170/// exactly that - so it is preferred over the prose beneath it rather than
2171/// skipped as decoration. Leading list and heading markers are stripped
2172/// because they are syntax, not words. `None` when nothing is left.
2173pub(crate) fn first_line(instruction: &str) -> Option<&str> {
2174    let line = instruction
2175        .lines()
2176        .map(str::trim)
2177        .find(|l| !l.is_empty())?
2178        .trim_start_matches(['#', '-', '*', '>', ' '])
2179        .trim();
2180    (!line.is_empty()).then_some(line)
2181}
2182
2183fn read_path(path: &Path) -> Result<Task> {
2184    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
2185    let task: Task =
2186        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
2187    // Greater-than, not not-equal: every field added since schema 1 carries
2188    // `#[serde(default)]`, so an older task has nothing to say about it and
2189    // defaulting is exactly as good a reading as a value that build never had
2190    // a chance to write. Only a schema *ahead* of this build - a meaning it
2191    // cannot possibly know - is refused rather than guessed at.
2192    if task.schema > SCHEMA {
2193        bail!(
2194            "task {} was written by a different magi (schema {}, this build \
2195             speaks {SCHEMA})",
2196            task.id,
2197            task.schema
2198        );
2199    }
2200    Ok(task)
2201}
2202
2203/// Ids inside a `blocked_by` list that name neither an existing task file nor
2204/// an existing question file - a dependency deleted (`magi task rm`, or by
2205/// hand) while something was still waiting on it.
2206///
2207/// Existence is decided by [`Queue::path_of`]/[`Questions::path_of`]
2208/// `is_file()` alone, never by [`Queue::get`]/[`Questions::get`] succeeding:
2209/// those also fail on a merely unreadable file - mid-write, corrupt, or from
2210/// a schema ahead of this build (see [`read_path`]) - and misreading "cannot
2211/// read it right now" as "it was deleted" would quarantine a task over a
2212/// transient failure. `blocked_by` always carries a full id, written by
2213/// `crate::conduct` or `crate::triage` from a real task's or question's own
2214/// `id`/`short`, never a prefix a caller typed - so the exact-path check is
2215/// complete on its own, with no [`Queue::resolve_id`] fallback needed.
2216pub fn missing_blockers(
2217    queue: &Queue,
2218    questions: &Questions,
2219    blocked_by: &[String],
2220) -> Vec<String> {
2221    blocked_by
2222        .iter()
2223        .filter(|id| {
2224            !queue.path_of(id).is_file()
2225                && !questions.path_of(id).is_file()
2226                && !queue.was_deleted(id)
2227        })
2228        .cloned()
2229        .collect()
2230}
2231
2232/// Ids in `blocked_by` that [`Queue::remove`] deleted on purpose: tombstoned
2233/// and with no record. A live task is never included, tombstone or not. These
2234/// are resolved with [`Task::dependency_deleted`], not held; an id that
2235/// vanished without a tombstone stays [`missing_blockers`]' to report.
2236pub fn deleted_blockers(queue: &Queue, blocked_by: &[String]) -> Vec<String> {
2237    blocked_by
2238        .iter()
2239        .filter(|id| queue.was_deleted(id))
2240        .cloned()
2241        .collect()
2242}
2243
2244/// The `hold_reason` text for a task quarantined because one or more of its
2245/// `blocked_by` ids no longer exist. Shared by `crate::daemon::resolve_blockers`,
2246/// `crate::triage::run_once`, and [`Queue::remove`]'s own dependent
2247/// quarantine, so the three call sites read as the same event to an operator
2248/// looking at `magi task show` rather than three different wordings for it.
2249///
2250/// Names the full original `blocked_by` list, not just `missing` - a task
2251/// quarantined here can also have named a dependency that was still
2252/// perfectly valid, and [`Task::hold_machine`] clears `blocked_by` on the way
2253/// in, so this text is the only place that information survives for an
2254/// operator deciding whether to release the task outright.
2255pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
2256    missing_blocker_hold_reason_in(blocked_by, missing, "en")
2257}
2258
2259/// [`missing_blocker_hold_reason`] in `language` (Japanese, else English).
2260pub fn missing_blocker_hold_reason_in(
2261    blocked_by: &[String],
2262    missing: &[String],
2263    language: &str,
2264) -> String {
2265    if crate::lang::is_japanese(language) {
2266        format!(
2267            "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
2268            blocked_by.join(", "),
2269            missing.join(", "),
2270        )
2271    } else {
2272        format!(
2273            "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
2274            blocked_by.join(", "),
2275            missing.join(", "),
2276        )
2277    }
2278}
2279
2280/// The last dash-separated part of an id, the form people say aloud.
2281pub fn short(id: &str) -> &str {
2282    id.split('-').next_back().unwrap_or(id)
2283}
2284
2285fn new_id() -> String {
2286    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
2287    let seed = crate::rng::entropy();
2288    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
2289}
2290
2291#[cfg(test)]
2292mod tests {
2293    #[test]
2294    fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
2295        let mut base = RunOverrides {
2296            merge: Some("pr".to_owned()),
2297            candidates: Some(3),
2298            ..RunOverrides::default()
2299        };
2300        base.merge_over(&RunOverrides {
2301            merge: Some("none".to_owned()),
2302            seed: Some(7),
2303            ..RunOverrides::default()
2304        });
2305        assert_eq!(base.merge.as_deref(), Some("none"));
2306        assert_eq!(base.candidates, Some(3));
2307        assert_eq!(base.seed, Some(7));
2308    }
2309
2310    #[test]
2311    fn an_already_landed_task_is_done_with_its_attempt_refunded() {
2312        let mut t = task("relanded");
2313        t.attempts = 1;
2314        t.status = TaskStatus::Running;
2315        t.already_landed("already in main as 0e368de");
2316        assert_eq!(t.status, TaskStatus::Done);
2317        assert_eq!(t.attempts, 0);
2318        assert!(t.hold_reason.is_none());
2319        assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
2320    }
2321
2322    #[test]
2323    fn missing_blocker_reason_follows_the_language() {
2324        let b = vec!["a".to_owned()];
2325        let en = missing_blocker_hold_reason_in(&b, &b, "en");
2326        assert_eq!(en, missing_blocker_hold_reason(&b, &b));
2327        assert!(en.starts_with("blocked on a"));
2328        assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
2329        assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
2330    }
2331
2332    use super::*;
2333
2334    #[test]
2335    fn triage_applied_survives_release_and_old_records_read_as_empty() {
2336        let mut t = Task::new(
2337            "t".to_owned(),
2338            "i".to_owned(),
2339            PathBuf::from("r"),
2340            Source::Human,
2341        );
2342        t.mark_triage_applied("q1");
2343        t.mark_triage_applied("q1");
2344        t.hold_machine(Some("x".to_owned()));
2345        t.release();
2346        assert_eq!(t.triage_applied, ["q1"]);
2347        assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
2348
2349        let mut v = serde_json::to_value(&t).unwrap();
2350        v.as_object_mut().unwrap().remove("triage_applied");
2351        let old: Task = serde_json::from_value(v).unwrap();
2352        assert!(old.triage_applied.is_empty());
2353    }
2354
2355    #[test]
2356    fn task_counts_of_empty_is_all_zero() {
2357        assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
2358    }
2359
2360    #[test]
2361    fn task_counts_of_tallies_every_status() {
2362        let mut queued = Task::new(
2363            "q".to_owned(),
2364            "i".to_owned(),
2365            PathBuf::from("."),
2366            Source::Human,
2367        );
2368        queued.status = TaskStatus::Queued;
2369        let mut running = queued.clone();
2370        running.status = TaskStatus::Running;
2371        let mut done = queued.clone();
2372        done.status = TaskStatus::Done;
2373        let mut failed = queued.clone();
2374        failed.status = TaskStatus::Failed;
2375        let mut held = queued.clone();
2376        held.status = TaskStatus::Held;
2377        let mut blocked = queued.clone();
2378        blocked.status = TaskStatus::Blocked;
2379
2380        let mut parked = queued.clone();
2381        parked.status = TaskStatus::Parked;
2382
2383        let counts = TaskCounts::of(&[
2384            queued,
2385            running,
2386            done.clone(),
2387            done,
2388            failed,
2389            held,
2390            blocked,
2391            parked,
2392        ]);
2393        assert_eq!(
2394            counts,
2395            TaskCounts {
2396                queued: 1,
2397                running: 1,
2398                done: 2,
2399                failed: 1,
2400                held: 1,
2401                blocked: 1,
2402                parked: 1,
2403            }
2404        );
2405    }
2406
2407    /// A queue of its own, with no process-global state - which is the point of
2408    /// `Queue::at`, and why these can run in parallel.
2409    fn queue() -> (tempfile::TempDir, Queue) {
2410        let dir = tempfile::tempdir().unwrap();
2411        let q = Queue::at(dir.path().join("queue"));
2412        (dir, q)
2413    }
2414
2415    #[test]
2416    fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
2417        let dir = tempfile::tempdir().unwrap();
2418        let q = Queue::at(dir.path().join("queue"));
2419        let mut t = task("held");
2420        q.put(&mut t).unwrap();
2421        assert_eq!(
2422            crate::notices::Notices::at(dir.path().join("notifications"))
2423                .list()
2424                .len(),
2425            0
2426        );
2427        t.hold_machine(Some("out of attempts".to_owned()));
2428        q.put(&mut t).unwrap();
2429        let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
2430        assert_eq!(listed.len(), 1);
2431        assert!(listed[0].message.contains("out of attempts"));
2432    }
2433
2434    fn task(title: &str) -> Task {
2435        Task::new(
2436            title.to_owned(),
2437            format!("do {title}"),
2438            PathBuf::from("."),
2439            Source::Human,
2440        )
2441    }
2442
2443    #[test]
2444    fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
2445        let mut t = task("retried");
2446        assert!(
2447            t.earlier_attempts().is_empty(),
2448            "a first attempt takes nothing over"
2449        );
2450        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
2451        assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
2452        // What the web note shows and what a takeover acts on are one rule.
2453        assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
2454        assert_eq!(t.successor_of("bbbb"), None);
2455        assert_eq!(t.successor_of("zzzz"), None);
2456    }
2457
2458    #[test]
2459    fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
2460        let (_dir, q) = queue();
2461        let mut t = task("retried");
2462        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
2463        q.put(&mut t).unwrap();
2464
2465        assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
2466        assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
2467        assert_eq!(
2468            q.superseded_by("cccc"),
2469            None,
2470            "the latest attempt replaces nothing"
2471        );
2472        assert_eq!(
2473            q.superseded_by("never-heard-of-it"),
2474            None,
2475            "a run belonging to no task on this queue is not superseded"
2476        );
2477
2478        let mut by = HashMap::new();
2479        by.insert("aaaa".to_owned(), "bbbb".to_owned());
2480        by.insert("bbbb".to_owned(), "cccc".to_owned());
2481        assert_eq!(
2482            q.superseded(),
2483            by,
2484            "the whole-map and single-run forms must agree"
2485        );
2486    }
2487
2488    #[test]
2489    fn superseded_attempts_is_empty_until_the_task_is_done() {
2490        let mut t = task("retried");
2491        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
2492        t.status = TaskStatus::Failed;
2493        assert_eq!(
2494            t.superseded_attempts(true),
2495            &[] as &[String],
2496            "a task still retrying has no attempt yet that a later one made moot"
2497        );
2498
2499        t.status = TaskStatus::Running;
2500        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
2501    }
2502
2503    #[test]
2504    fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
2505        let mut t = task("retried");
2506        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
2507        t.status = TaskStatus::Done;
2508        assert_eq!(
2509            t.superseded_attempts(true),
2510            &["aaaa".to_owned(), "bbbb".to_owned()],
2511            "cccc is the attempt whose success made the task done, and stays out"
2512        );
2513    }
2514
2515    #[test]
2516    fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
2517        let mut t = task("first try landed");
2518        t.runs = vec!["aaaa".to_owned()];
2519        t.status = TaskStatus::Done;
2520        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
2521    }
2522
2523    #[test]
2524    fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
2525        // `succeed` is reachable directly - `magi task done`, its web
2526        // equivalent, and the conductor's `Recovery::Done` - on a task in
2527        // any status, including one whose last recorded attempt is itself
2528        // `Blocked`/`Failed`/anything but `Merged`/`Ready`. `runs.last()`
2529        // alone cannot tell that apart from the loop's own settle path, so
2530        // the caller's own read of that run's status is what decides this.
2531        let mut t = task("closed by hand after a manual merge");
2532        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
2533        t.status = TaskStatus::Done;
2534        assert_eq!(
2535            t.superseded_attempts(false),
2536            &[] as &[String],
2537            "nothing here is provably why the task is done, so nothing is superseded"
2538        );
2539    }
2540
2541    #[test]
2542    fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
2543        let (_dir, q) = queue();
2544        let mut t = task("retried twice");
2545        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
2546        q.put(&mut t).unwrap();
2547
2548        assert_eq!(
2549            q.latest_attempt("aaaa"),
2550            Some("cccc".to_owned()),
2551            "an old attempt points straight at the chain's current head, not the \
2552             next attempt in the middle of it"
2553        );
2554        assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
2555        assert_eq!(
2556            q.latest_attempt("cccc"),
2557            None,
2558            "the latest attempt is not superseded by anything"
2559        );
2560        assert_eq!(
2561            q.latest_attempt("never-heard-of-it"),
2562            None,
2563            "a run belonging to no task on this queue is not superseded"
2564        );
2565    }
2566
2567    #[test]
2568    fn a_markdown_heading_is_the_title_not_decoration() {
2569        // A task file's heading is the summary its author already wrote, so it
2570        // beats the prose underneath. Getting this backwards was visible in the
2571        // first smoke test: a task titled "# Rework the config loader" listed
2572        // as "It re-reads the file on every lookup".
2573        assert_eq!(
2574            title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
2575            "Rework the config loader"
2576        );
2577        assert_eq!(title_from("- fix the thing", 40), "fix the thing");
2578        assert_eq!(title_from("> quoted task", 40), "quoted task");
2579        // Nothing usable at all still has to produce something printable.
2580        assert_eq!(title_from("   \n\n", 40), "(empty task)");
2581        assert_eq!(title_from("###\n", 40), "(empty task)");
2582    }
2583
2584    #[test]
2585    fn a_long_title_is_elided_by_characters_not_bytes() {
2586        // Byte truncation would split a multi-byte character and panic.
2587        let long = "課題".repeat(30);
2588        let title = title_from(&long, 10);
2589        assert_eq!(title.chars().count(), 10);
2590        assert!(title.ends_with('…'));
2591    }
2592
2593    #[test]
2594    fn priority_wins_and_ties_break_oldest_first() {
2595        let (_dir, q) = queue();
2596        let mut a = task("first");
2597        let mut b = task("second");
2598        let mut c = task("urgent");
2599        // Ids carry a timestamp, so force a known order.
2600        a.id = "20260101-000001-aaaa".to_owned();
2601        b.id = "20260101-000002-bbbb".to_owned();
2602        c.id = "20260101-000003-cccc".to_owned();
2603        c.priority = 5;
2604        for t in [&mut a, &mut b, &mut c] {
2605            q.put(t).unwrap();
2606        }
2607
2608        // Priority first...
2609        assert_eq!(q.next_runnable().unwrap().id, c.id);
2610        c.hold_machine(None);
2611        q.put(&mut c).unwrap();
2612        // ...then oldest, so a burst of new work cannot starve older work.
2613        assert_eq!(q.next_runnable().unwrap().id, a.id);
2614        assert_eq!(q.list().len(), 3, "b is still waiting its turn");
2615    }
2616
2617    #[test]
2618    fn a_blocked_task_never_starves_another_runnable_one() {
2619        let (_dir, q) = queue();
2620        let mut blocked = task("blocked");
2621        blocked.block(vec!["something".to_owned()], None);
2622        q.put(&mut blocked).unwrap();
2623
2624        let mut runnable = task("free to go");
2625        q.put(&mut runnable).unwrap();
2626
2627        let next = q.next_runnable().expect("a runnable task is still offered");
2628        assert_eq!(next.id, runnable.id);
2629    }
2630
2631    #[test]
2632    fn a_held_task_is_never_offered_to_the_loop() {
2633        let (_dir, q) = queue();
2634        let mut t = task("held");
2635        q.put(&mut t).unwrap();
2636        assert!(q.next_runnable().is_some());
2637
2638        t.hold_machine(None);
2639        q.put(&mut t).unwrap();
2640        assert!(
2641            q.next_runnable().is_none(),
2642            "a held task must wait for a human"
2643        );
2644
2645        // A failed task, by contrast, is exactly what the loop should retry.
2646        t.status = TaskStatus::Failed;
2647        q.put(&mut t).unwrap();
2648        assert!(q.next_runnable().is_some());
2649    }
2650
2651    #[test]
2652    fn attempts_are_capped_and_then_the_task_is_held() {
2653        let mut t = task("doomed");
2654
2655        t.start("run-1".to_owned());
2656        t.fail("gate red", 2);
2657        assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
2658
2659        t.start("run-2".to_owned());
2660        t.fail("gate red", 2);
2661        assert_eq!(
2662            t.status,
2663            TaskStatus::Held,
2664            "out of attempts: stop spending money on it"
2665        );
2666        assert_eq!(t.runs, ["run-1", "run-2"]);
2667        assert_eq!(t.last_error.as_deref(), Some("gate red"));
2668        assert_eq!(
2669            t.hold_reason.as_deref(),
2670            Some("gate red"),
2671            "the hold must say why, not leave hold_reason null next to a \
2672             populated last_error"
2673        );
2674    }
2675
2676    #[test]
2677    fn handing_off_a_task_records_a_hold_reason_too() {
2678        let mut t = task("left a pull request");
2679        t.start("run-1".to_owned());
2680        t.handed_off("run ended with a pull request open [run run-1]");
2681        assert_eq!(t.status, TaskStatus::Held);
2682        assert_eq!(t.hold_source, Some(HoldSource::Machine));
2683        assert_eq!(
2684            t.hold_reason.as_deref(),
2685            Some("run ended with a pull request open [run run-1]")
2686        );
2687        assert_eq!(t.hold_reason, t.last_error);
2688    }
2689
2690    #[test]
2691    fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
2692        let mut t = task("stalled by quota");
2693
2694        t.start("run-1".to_owned());
2695        assert_eq!(t.attempts, 1);
2696        t.stall("judge-1, judge-2 out of quota");
2697        assert_eq!(
2698            t.attempts, 0,
2699            "a closed quota window must not spend the task's retry budget"
2700        );
2701        assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
2702        assert_eq!(
2703            t.last_error.as_deref(),
2704            Some("judge-1, judge-2 out of quota")
2705        );
2706
2707        // A task can therefore stall all night and still get its real attempts
2708        // once the quota resets - which is the whole point.
2709        for _ in 0..20 {
2710            t.start("run-n".to_owned());
2711            t.stall("still out of quota");
2712        }
2713        t.start("run-real".to_owned());
2714        t.fail("gate red", 2);
2715        assert_eq!(
2716            t.status,
2717            TaskStatus::Failed,
2718            "the first attempt that was really judged is attempt one"
2719        );
2720    }
2721
2722    #[test]
2723    fn releasing_a_held_task_gives_it_a_real_second_chance() {
2724        let mut t = task("retry me");
2725        t.start("run-1".to_owned());
2726        t.fail("gate red", 1);
2727        assert_eq!(t.status, TaskStatus::Held);
2728
2729        t.release();
2730        assert_eq!(t.status, TaskStatus::Queued);
2731        // Without resetting attempts the next failure would re-hold at once,
2732        // and a release would be a no-op the operator cannot see.
2733        assert_eq!(t.attempts, 0);
2734        assert!(t.last_error.is_none());
2735        assert_eq!(
2736            t.runs.len(),
2737            1,
2738            "history is kept: attempts reset, evidence does not"
2739        );
2740    }
2741
2742    #[test]
2743    fn a_hold_reason_survives_and_a_release_clears_it() {
2744        let mut t = task("waiting on something else");
2745        t.hold_manual(Some(
2746            "waiting for 20260101-000000-aaaa to land first".to_owned(),
2747        ));
2748        assert_eq!(t.status, TaskStatus::Held);
2749        assert_eq!(
2750            t.hold_reason.as_deref(),
2751            Some("waiting for 20260101-000000-aaaa to land first")
2752        );
2753
2754        // Holding again with no reason must not erase the one already there.
2755        t.hold_manual(None);
2756        assert_eq!(
2757            t.hold_reason.as_deref(),
2758            Some("waiting for 20260101-000000-aaaa to land first"),
2759            "a bare re-hold keeps whatever a human already wrote down"
2760        );
2761
2762        // A hold with no reason at all is still an ordinary, allowed hold.
2763        let mut plain = task("no reason given");
2764        plain.hold_manual(None);
2765        assert_eq!(plain.status, TaskStatus::Held);
2766        assert!(plain.hold_reason.is_none());
2767
2768        t.release();
2769        assert_eq!(t.status, TaskStatus::Queued);
2770        assert!(
2771            t.hold_reason.is_none(),
2772            "a stale reason must not greet the next person who holds this task"
2773        );
2774    }
2775
2776    #[test]
2777    fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
2778        // `done` can close a held task directly - neither `magi task done`
2779        // nor `POST /api/queue/{id}/done` requires a release first - so a
2780        // task held for "waiting on 3ed9" and then closed without ever being
2781        // released must not still read as waiting on it afterwards.
2782        let mut t = task("landed by hand while held");
2783        t.hold_manual(Some("waiting on 3ed9".to_owned()));
2784        assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
2785
2786        t.succeed();
2787        assert_eq!(t.status, TaskStatus::Done);
2788        assert!(
2789            t.hold_reason.is_none(),
2790            "a done task cannot still be waiting on something"
2791        );
2792    }
2793
2794    #[test]
2795    fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
2796        // The web UI's "Hold" and "Mark done" buttons are both reachable on a
2797        // `blocked` task, not just on `queued`/`held` ones - neither requires
2798        // a release first. A task moved off `Blocked` that way must not still
2799        // carry the dependency it was waiting on: a dependency graph built
2800        // from `blocked_by` would otherwise keep drawing an edge for a task
2801        // that is not blocked on anything any more.
2802        let mut held = task("held straight out of blocked");
2803        held.block(
2804            vec!["20260101-000000-dead".to_owned()],
2805            Some("waiting on the migration script".to_owned()),
2806        );
2807        assert_eq!(held.status, TaskStatus::Blocked);
2808
2809        held.hold_manual(None);
2810        assert_eq!(held.status, TaskStatus::Held);
2811        assert!(
2812            held.blocked_by.is_empty(),
2813            "hold overrides the wait, same as release"
2814        );
2815        assert!(held.block_reason.is_none());
2816
2817        let mut done = task("closed straight out of blocked");
2818        done.block(
2819            vec!["20260101-000000-dead".to_owned()],
2820            Some("waiting on the migration script".to_owned()),
2821        );
2822        done.succeed();
2823        assert_eq!(done.status, TaskStatus::Done);
2824        assert!(
2825            done.blocked_by.is_empty(),
2826            "a done task cannot still be waiting on a dependency"
2827        );
2828        assert!(done.block_reason.is_none());
2829    }
2830
2831    #[test]
2832    fn a_blocked_task_is_never_offered_to_the_loop() {
2833        let mut t = task("blocked");
2834        assert!(t.status.runnable());
2835        t.block(
2836            vec!["dep-id".to_owned()],
2837            Some("waits on dep-id".to_owned()),
2838        );
2839        assert_eq!(t.status, TaskStatus::Blocked);
2840        assert!(!t.status.runnable());
2841        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
2842    }
2843
2844    #[test]
2845    fn unblocking_the_last_dependency_returns_the_task_to_queued() {
2846        let mut t = task("blocked on two");
2847        t.block(
2848            vec!["a".to_owned(), "b".to_owned()],
2849            Some("waits on a and b".to_owned()),
2850        );
2851
2852        t.unblock("a");
2853        assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
2854        assert_eq!(t.blocked_by, ["b"]);
2855
2856        t.unblock("b");
2857        assert_eq!(t.status, TaskStatus::Queued);
2858        assert!(t.blocked_by.is_empty());
2859        assert!(t.block_reason.is_none());
2860    }
2861
2862    #[test]
2863    fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
2864        let mut t = task("never blocked");
2865        t.unblock("whatever");
2866        assert_eq!(t.status, TaskStatus::Queued);
2867    }
2868
2869    #[test]
2870    fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
2871        // The bug this guards: a task an operator (or `crate::triage`) has
2872        // deliberately held, once `crate::conduct` blocks it on a follow-up
2873        // question, must not silently re-enter the competition queue the
2874        // moment that question is answered - whatever the answer said.
2875        let mut t = task("held, then asked about");
2876        t.hold_machine(Some("out of attempts".to_owned()));
2877        assert_eq!(t.status, TaskStatus::Held);
2878
2879        t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
2880        assert_eq!(t.status, TaskStatus::Blocked);
2881
2882        t.record_answer("what now?".to_owned(), "leave it held".to_owned());
2883        t.unblock("q1");
2884        assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
2885        assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
2886        assert_eq!(t.hold_source, Some(HoldSource::Machine));
2887        assert!(t.blocked_from.is_none(), "consumed once restored");
2888    }
2889
2890    #[test]
2891    fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
2892        let mut t = task("manually held, then asked about");
2893        t.hold_manual(Some("waiting on a dependency".to_owned()));
2894
2895        t.block(vec!["q1".to_owned()], None);
2896        t.unblock("q1");
2897
2898        assert_eq!(t.status, TaskStatus::Held);
2899        assert_eq!(t.hold_source, Some(HoldSource::Manual));
2900    }
2901
2902    #[test]
2903    fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
2904        // A second `Task::block` call - `crate::conduct` adding a question on
2905        // top of an existing block - must not overwrite `blocked_from` with
2906        // `Blocked` itself, or the task would restore into itself.
2907        let mut t = task("held, blocked twice");
2908        t.hold_machine(None);
2909        t.block(vec!["q1".to_owned()], Some("first".to_owned()));
2910        t.block(
2911            vec!["q1".to_owned(), "q2".to_owned()],
2912            Some("second".to_owned()),
2913        );
2914
2915        t.unblock("q1");
2916        assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
2917        t.unblock("q2");
2918        assert_eq!(t.status, TaskStatus::Held);
2919    }
2920
2921    #[test]
2922    fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
2923        // Whatever process was driving the run is gone by the time a
2924        // conductor's question about it gets answered - there is nothing left
2925        // to resume into.
2926        let mut t = task("blocked mid-run");
2927        t.start("run-1".to_owned());
2928        assert_eq!(t.status, TaskStatus::Running);
2929
2930        t.block(vec!["q1".to_owned()], None);
2931        t.unblock("q1");
2932        assert_eq!(t.status, TaskStatus::Queued);
2933    }
2934
2935    #[test]
2936    fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
2937        // `blocked_from` is `None` for a record written before schema 4 (or,
2938        // equivalently, deserialized straight from an on-disk file that never
2939        // had the field). Held evidence surviving on the task - never cleared
2940        // by `block` - is the only way left to tell such a record apart from
2941        // one blocked straight out of `Queued`.
2942        let mut t = task("legacy record, held before it was blocked");
2943        t.hold_source = Some(HoldSource::Machine);
2944        t.hold_reason = Some("legacy hold reason".to_owned());
2945        t.status = TaskStatus::Blocked;
2946        t.blocked_by = vec!["q1".to_owned()];
2947        t.blocked_from = None;
2948
2949        t.unblock("q1");
2950        assert_eq!(t.status, TaskStatus::Held);
2951    }
2952
2953    #[test]
2954    fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
2955        let mut t = task("legacy record, ordinary dependency block");
2956        t.status = TaskStatus::Blocked;
2957        t.blocked_by = vec!["dep".to_owned()];
2958        t.blocked_from = None;
2959
2960        t.unblock("dep");
2961        assert_eq!(t.status, TaskStatus::Queued);
2962    }
2963
2964    #[test]
2965    fn answering_a_question_is_recorded_and_survives_a_release() {
2966        let mut t = task("asked something");
2967        t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
2968        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
2969        t.unblock("q1");
2970        assert_eq!(t.status, TaskStatus::Queued);
2971        assert_eq!(t.answers.len(), 1);
2972        assert_eq!(t.answers[0].answer, "SQLite");
2973
2974        // A release resets attempts, not evidence - the same rule
2975        // `releasing_a_held_task_gives_it_a_real_second_chance` asserts for
2976        // `runs`.
2977        t.release();
2978        assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
2979    }
2980
2981    #[test]
2982    fn a_refused_handover_keeps_the_review_branch_across_release() {
2983        let mut t = task("refused takeover");
2984        t.start("run-1".to_owned());
2985        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
2986        assert_eq!(t.status, TaskStatus::Held);
2987        assert_eq!(t.attempts, 1);
2988        t.release();
2989        assert_eq!(t.status, TaskStatus::Queued);
2990        assert_eq!(t.attempts, 0);
2991        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
2992
2993        // A fresh competition chosen afterwards is not a review.
2994        t.hold_for_handover(None, "again".to_owned());
2995        t.requeue();
2996        assert!(t.review_branch.is_none());
2997
2998        // A manual hold never keeps one.
2999        let mut m = task("manual");
3000        m.review_branch = Some("magi/x/A".to_owned());
3001        m.hold_manual(None);
3002        m.release();
3003        assert!(m.review_branch.is_none());
3004    }
3005
3006    #[test]
3007    fn requesting_review_requeues_the_task_and_remembers_the_branch() {
3008        let mut t = task("blocked run with a surviving branch");
3009        t.start("run-1".to_owned());
3010        t.fail("blocked with major findings", 5);
3011        assert_eq!(t.status, TaskStatus::Failed);
3012
3013        t.request_review("magi/eba2/A".to_owned());
3014        assert_eq!(t.status, TaskStatus::Queued);
3015        assert_eq!(t.attempts, 0);
3016        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
3017
3018        // An ordinary release (a human overriding the choice) drops it again.
3019        t.release();
3020        assert!(t.review_branch.is_none());
3021    }
3022
3023    #[test]
3024    fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
3025        let mut t = task("retry");
3026        t.start("run-1".to_owned());
3027        t.requeue();
3028        assert!(t.fresh_start);
3029
3030        t.release();
3031        assert!(!t.fresh_start);
3032    }
3033
3034    #[test]
3035    fn priority_can_be_changed_while_queued_but_not_while_running() {
3036        let mut t = task("reprioritise me");
3037        t.set_priority(5).unwrap();
3038        assert_eq!(t.priority, 5);
3039
3040        t.start("run-1".to_owned());
3041        let err = t.set_priority(9).unwrap_err().to_string();
3042        assert!(err.contains("running"), "{err}");
3043        assert_eq!(t.priority, 5, "the rejected write must not partially apply");
3044    }
3045
3046    #[test]
3047    fn interrupt_can_be_marked_while_queued_but_not_while_running() {
3048        let mut t = task("interrupt me");
3049        assert!(!t.interrupt, "off unless asked, same as any other task");
3050
3051        t.set_interrupt(true).unwrap();
3052        assert!(t.interrupt);
3053
3054        t.start("run-1".to_owned());
3055        assert!(
3056            !t.interrupt,
3057            "the mark is one-shot: dispatching the task fulfils it, \
3058             whatever the run that follows ends up doing"
3059        );
3060        let err = t.set_interrupt(true).unwrap_err().to_string();
3061        assert!(err.contains("running"), "{err}");
3062        // Clearing is always allowed, even on a running task - there is
3063        // nothing left for it to interrupt once it has been claimed.
3064        t.set_interrupt(false).unwrap();
3065        assert!(!t.interrupt);
3066    }
3067
3068    /// R2-1-1: a task whose run fails and requeues must not go on
3069    /// re-triggering `crate::daemon`'s interrupt scheduler on every later
3070    /// boundary, attempt after attempt, until it exhausts its budget.
3071    #[test]
3072    fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
3073        let mut t = task("interrupt me");
3074        t.set_interrupt(true).unwrap();
3075        t.start("run-1".to_owned());
3076        t.fail("mock failure", 5);
3077        assert_eq!(t.status, TaskStatus::Failed);
3078        assert!(
3079            !t.interrupt,
3080            "one attempt already spent the mark; a retry is an ordinary \
3081             requeue, not a fresh interrupt request"
3082        );
3083    }
3084
3085    #[test]
3086    fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
3087        let (_dir, q) = queue();
3088        let mut a = task("first filed");
3089        let mut b = task("second filed");
3090        a.id = "20260101-000001-aaaa".to_owned();
3091        b.id = "20260101-000002-bbbb".to_owned();
3092        q.put(&mut a).unwrap();
3093        q.put(&mut b).unwrap();
3094
3095        assert_eq!(
3096            q.next_runnable().unwrap().id,
3097            a.id,
3098            "with equal priority the older task goes first, so a burst of \
3099             new work cannot starve it"
3100        );
3101        assert_eq!(
3102            q.list()[0].id,
3103            b.id,
3104            "but the list an operator reads is newest first, the same as \
3105             before priority existed - a's turn to run does not make it the \
3106             newest task"
3107        );
3108
3109        let mut a = q.get(&a.id).unwrap();
3110        a.set_priority(10).unwrap();
3111        q.put(&mut a).unwrap();
3112
3113        assert_eq!(
3114            q.next_runnable().unwrap().id,
3115            a.id,
3116            "a raised priority must be reflected the moment it is saved"
3117        );
3118        // `magi task list` and `GET /api/queue` both print `Queue::list()`
3119        // directly, so the raised task has to lead there too - not only in
3120        // what the loop would claim next.
3121        assert_eq!(
3122            q.list()[0].id,
3123            a.id,
3124            "the raised task must sort first in the list an operator reads, \
3125             not only in next_runnable's own ordering"
3126        );
3127    }
3128
3129    #[test]
3130    fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
3131        let mut t = Task::new(
3132            "old title".to_owned(),
3133            "old instruction".to_owned(),
3134            PathBuf::from("/repo"),
3135            Source::Agent {
3136                run: "20260101-000000-beef".to_owned(),
3137                node: "implement".to_owned(),
3138            },
3139        );
3140        let id = t.id.clone();
3141        let created_at = t.created_at;
3142        t.runs.push("20260101-000000-beef".to_owned());
3143
3144        t.edit("new title".to_owned(), "new instruction".to_owned())
3145            .unwrap();
3146
3147        assert_eq!(t.title, "new title");
3148        assert_eq!(t.instruction, "new instruction");
3149        assert_eq!(t.id, id, "editing must not mint a new id");
3150        assert_eq!(t.created_at, created_at);
3151        assert_eq!(
3152            t.source,
3153            Source::Agent {
3154                run: "20260101-000000-beef".to_owned(),
3155                node: "implement".to_owned(),
3156            },
3157            "editing must not turn agent attribution into human"
3158        );
3159        assert_eq!(t.runs, ["20260101-000000-beef"]);
3160    }
3161
3162    #[test]
3163    fn editing_is_refused_once_a_task_is_running_or_finished() {
3164        let mut running = task("in flight");
3165        running.start("run-1".to_owned());
3166        let err = running
3167            .edit("x".to_owned(), "y".to_owned())
3168            .unwrap_err()
3169            .to_string();
3170        assert!(err.contains("running"), "{err}");
3171
3172        let mut done = task("finished");
3173        done.succeed();
3174        let err = done
3175            .edit("x".to_owned(), "y".to_owned())
3176            .unwrap_err()
3177            .to_string();
3178        assert!(err.contains("done"), "{err}");
3179
3180        // Both queued and held are the point of the feature and must work.
3181        let mut queued = task("waiting");
3182        queued.edit("x".to_owned(), "y".to_owned()).unwrap();
3183        let mut held = task("parked");
3184        held.hold_machine(None);
3185        held.edit("x".to_owned(), "y".to_owned()).unwrap();
3186    }
3187
3188    #[test]
3189    fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
3190        let (_dir, q) = queue();
3191        let path = q.path_of("20260101-000000-aaaa");
3192        std::fs::create_dir_all(q.root()).unwrap();
3193        std::fs::write(
3194            &path,
3195            serde_json::json!({
3196                "schema": SCHEMA,
3197                "id": "20260101-000000-aaaa",
3198                "title": "from before hold reasons existed",
3199                "instruction": "from before hold reasons existed",
3200                "repo": ".",
3201                "source": { "kind": "human" },
3202                "status": "held",
3203                "created_at": Timestamp::now().to_string(),
3204                "updated_at": Timestamp::now().to_string(),
3205            })
3206            .to_string(),
3207        )
3208        .unwrap();
3209
3210        let task = q.get("20260101-000000-aaaa").expect("must still read");
3211        assert!(task.hold_reason.is_none());
3212        assert!(task.operator_held());
3213    }
3214
3215    #[test]
3216    fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
3217        let (_dir, q) = queue();
3218        let path = q.path_of("20260101-000000-bbbb");
3219        std::fs::create_dir_all(q.root()).unwrap();
3220        std::fs::write(
3221            &path,
3222            serde_json::json!({
3223                "schema": 2,
3224                "id": "20260101-000000-bbbb",
3225                "title": "old manual recovery",
3226                "instruction": "old manual recovery",
3227                "repo": ".",
3228                "source": { "kind": "human" },
3229                "status": "held",
3230                "hold_reason": "active manual recovery run20260912-224242-daf5",
3231                "created_at": Timestamp::now().to_string(),
3232                "updated_at": Timestamp::now().to_string(),
3233            })
3234            .to_string(),
3235        )
3236        .unwrap();
3237
3238        let task = q.get("20260101-000000-bbbb").expect("must still read");
3239        assert_eq!(task.hold_source, None);
3240        assert!(task.operator_held());
3241    }
3242
3243    #[test]
3244    fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
3245        let (_dir, q) = queue();
3246        let path = q.path_of("20260101-000000-aaaa");
3247        std::fs::create_dir_all(q.root()).unwrap();
3248        std::fs::write(
3249            &path,
3250            serde_json::json!({
3251                "schema": SCHEMA,
3252                "id": "20260101-000000-aaaa",
3253                "title": "from before diagnostics existed",
3254                "instruction": "from before diagnostics existed",
3255                "repo": ".",
3256                "source": { "kind": "human" },
3257                "status": "held",
3258                "created_at": Timestamp::now().to_string(),
3259                "updated_at": Timestamp::now().to_string(),
3260            })
3261            .to_string(),
3262        )
3263        .unwrap();
3264
3265        let task = q.get("20260101-000000-aaaa").expect("must still read");
3266        assert!(task.diagnostic.is_none());
3267    }
3268
3269    #[test]
3270    fn a_schema_1_task_with_no_blocking_fields_still_reads() {
3271        // Written by a build that predates `blocked_by`, `block_reason`,
3272        // `answers` and `review_branch` entirely - literal `"schema": 1`,
3273        // not `SCHEMA`, since the whole point is a build older than this one.
3274        let (_dir, q) = queue();
3275        let path = q.path_of("20260101-000000-aaaa");
3276        std::fs::create_dir_all(q.root()).unwrap();
3277        std::fs::write(
3278            &path,
3279            serde_json::json!({
3280                "schema": 1,
3281                "id": "20260101-000000-aaaa",
3282                "title": "from before blocking existed",
3283                "instruction": "from before blocking existed",
3284                "repo": ".",
3285                "source": { "kind": "human" },
3286                "status": "queued",
3287                "created_at": Timestamp::now().to_string(),
3288                "updated_at": Timestamp::now().to_string(),
3289            })
3290            .to_string(),
3291        )
3292        .unwrap();
3293
3294        let task = q.get("20260101-000000-aaaa").expect("must still read");
3295        assert!(task.blocked_by.is_empty());
3296        assert!(task.block_reason.is_none());
3297        assert!(task.answers.is_empty());
3298        assert!(task.review_branch.is_none());
3299    }
3300
3301    #[test]
3302    fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
3303        // A diagnostic belongs to the run that produced it. Left in place
3304        // across a release, an unrelated later failure - a config error, say -
3305        // would go on showing evidence for a problem that is no longer why the
3306        // task is stuck.
3307        let mut held = task("diagnosed");
3308        held.start("run-1".to_owned());
3309        held.fail("gate red", 1);
3310        held.diagnostic = Some("cargo test failed: ...".to_owned());
3311        assert_eq!(held.status, TaskStatus::Held);
3312
3313        held.release();
3314        assert!(held.diagnostic.is_none());
3315
3316        held.diagnostic = Some("cargo test failed: ...".to_owned());
3317        held.succeed();
3318        assert!(held.diagnostic.is_none());
3319    }
3320
3321    #[test]
3322    fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
3323        let mut t = task("retried");
3324        t.start("run-1".to_owned());
3325        t.diagnostic = Some("stale evidence from a previous hold".to_owned());
3326        t.fail("unrelated config error", 5);
3327        assert_eq!(t.status, TaskStatus::Failed);
3328        assert!(
3329            t.diagnostic.is_none(),
3330            "fail() must not let an old diagnostic outlive the run that produced it"
3331        );
3332    }
3333
3334    #[test]
3335    fn a_claim_is_exclusive_and_releases_on_drop() {
3336        let (_dir, q) = queue();
3337        let mut t = task("contended");
3338        q.put(&mut t).unwrap();
3339
3340        let held = q.claim(&t.id).unwrap();
3341        assert!(
3342            q.claim(&t.id).is_err(),
3343            "two daemons must not drive one task into two runs"
3344        );
3345        drop(held);
3346        assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
3347    }
3348
3349    #[test]
3350    fn a_round_trip_survives_disk() {
3351        let (_dir, q) = queue();
3352        let mut t = Task::new(
3353            "titled".to_owned(),
3354            "body".to_owned(),
3355            PathBuf::from("/repo"),
3356            Source::Agent {
3357                run: "20260101-000000-beef".to_owned(),
3358                node: "implement".to_owned(),
3359            },
3360        );
3361        t.priority = 3;
3362        q.put(&mut t).unwrap();
3363
3364        let back = q.get(&t.id).unwrap();
3365        assert_eq!(back.id, t.id);
3366        assert_eq!(back.priority, 3);
3367        assert_eq!(back.source.label(), "implement@beef");
3368        // A prefix is enough, the way run ids work everywhere else.
3369        assert_eq!(q.get(t.short()).unwrap().id, t.id);
3370    }
3371
3372    #[test]
3373    fn an_unreadable_task_does_not_take_the_queue_down() {
3374        let (_dir, q) = queue();
3375        let mut t = task("fine");
3376        q.put(&mut t).unwrap();
3377        std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
3378
3379        let listed = q.list();
3380        assert_eq!(listed.len(), 1, "the readable task still lists");
3381        assert_eq!(listed[0].id, t.id);
3382    }
3383
3384    #[test]
3385    fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
3386        let (_dir, q) = queue();
3387        let path = q.path_of("20260101-000000-aaaa");
3388        std::fs::create_dir_all(q.root()).unwrap();
3389        std::fs::write(
3390            &path,
3391            serde_json::json!({
3392                "schema": SCHEMA,
3393                "id": "20260101-000000-aaaa",
3394                "title": "from before solo existed",
3395                "instruction": "from before solo existed",
3396                "repo": ".",
3397                "source": { "kind": "human" },
3398                "status": "queued",
3399                "created_at": Timestamp::now().to_string(),
3400                "updated_at": Timestamp::now().to_string(),
3401            })
3402            .to_string(),
3403        )
3404        .unwrap();
3405
3406        let task = q.get("20260101-000000-aaaa").expect("must still read");
3407        assert!(!task.solo, "a queue file with no `solo` field means false");
3408    }
3409
3410    #[test]
3411    fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
3412        let (_dir, q) = queue();
3413        let path = q.path_of("20260101-000000-bbbb");
3414        std::fs::create_dir_all(q.root()).unwrap();
3415        std::fs::write(
3416            &path,
3417            serde_json::json!({
3418                "schema": SCHEMA,
3419                "id": "20260101-000000-bbbb",
3420                "title": "from before urgent existed",
3421                "instruction": "from before urgent existed",
3422                "repo": ".",
3423                "source": { "kind": "human" },
3424                "status": "queued",
3425                "created_at": Timestamp::now().to_string(),
3426                "updated_at": Timestamp::now().to_string(),
3427            })
3428            .to_string(),
3429        )
3430        .unwrap();
3431
3432        let task = q.get("20260101-000000-bbbb").expect("must still read");
3433        assert!(
3434            !task.urgent,
3435            "a queue file with no `urgent` field means false, same as `solo`"
3436        );
3437    }
3438
3439    #[test]
3440    fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
3441        let (_dir, q) = queue();
3442        let mut t = task("from the future");
3443        q.put(&mut t).unwrap();
3444        let path = q.path_of(&t.id);
3445        let body = std::fs::read_to_string(&path)
3446            .unwrap()
3447            .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
3448        std::fs::write(&path, body).unwrap();
3449
3450        let err = q.get(&t.id).unwrap_err().to_string();
3451        assert!(err.contains("schema 99"), "{err}");
3452    }
3453
3454    #[test]
3455    fn revision_moves_when_the_queue_changes() {
3456        let (_dir, q) = queue();
3457        assert_eq!(q.revision(), 0, "an empty queue has no revision");
3458        let mut t = task("first");
3459        q.put(&mut t).unwrap();
3460        assert!(q.revision() > 0, "a written task moves the revision");
3461    }
3462
3463    #[test]
3464    fn revision_moves_when_deleting_an_older_task() {
3465        let (dir, q) = queue();
3466        let questions = Questions::at(dir.path().join("questions"));
3467        let mut t1 = task("older");
3468        q.put(&mut t1).unwrap();
3469        // Ensure mtime ticks forward.
3470        std::thread::sleep(std::time::Duration::from_millis(10));
3471        let mut t2 = task("newer");
3472        q.put(&mut t2).unwrap();
3473
3474        let rev_before = q.revision();
3475        q.remove(&t1.id, false, &questions).unwrap();
3476        let rev_after = q.revision();
3477
3478        assert_ne!(
3479            rev_before, rev_after,
3480            "deleting an older task must change the revision so other clients see the deletion"
3481        );
3482    }
3483
3484    #[test]
3485    fn removing_a_task_takes_it_out_of_the_listing() {
3486        let (dir, q) = queue();
3487        let questions = Questions::at(dir.path().join("questions"));
3488        let mut t = task("delete me");
3489        q.put(&mut t).unwrap();
3490        let removed = q.remove(t.short(), false, &questions).unwrap();
3491        assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
3492        assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
3493        assert!(q.list().is_empty());
3494        assert!(
3495            q.remove(&t.id, false, &questions).is_err(),
3496            "removing twice is an error"
3497        );
3498    }
3499
3500    #[test]
3501    fn removing_a_task_takes_its_stale_lock_with_it() {
3502        let (dir, q) = queue();
3503        let questions = Questions::at(dir.path().join("questions"));
3504        let mut t = task("interrupted");
3505        q.put(&mut t).unwrap();
3506
3507        // A daemon killed mid-run leaves this behind. Nothing holds it: the
3508        // process that would have dropped the guard is gone.
3509        let claim = q.claim(&t.id).unwrap();
3510        std::mem::forget(claim);
3511        assert!(
3512            q.claim(&t.id).is_err(),
3513            "the orphaned lock is what makes the task look claimed"
3514        );
3515
3516        // A live daemon on this task is refused, whatever the lock says.
3517        let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
3518        assert!(err.contains("live daemon"), "{err}");
3519        assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
3520
3521        // With no daemon behind it, the lock is stale and goes with the task.
3522        q.remove(&t.id, false, &questions).unwrap();
3523        assert!(q.list().is_empty());
3524        let mut again = task("interrupted");
3525        again.id = t.id.clone();
3526        q.put(&mut again).unwrap();
3527        assert!(
3528            q.claim(&t.id).is_ok(),
3529            "a task that comes back must be claimable, which a left-behind lock would prevent"
3530        );
3531    }
3532
3533    fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
3534        crate::notices::Notices::at(dir.join("notifications")).list()
3535    }
3536
3537    #[test]
3538    fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
3539        let (dir, q) = queue();
3540        let questions = Questions::at(dir.path().join("questions"));
3541        let mut dep = task("dependency");
3542        q.put(&mut dep).unwrap();
3543        let mut blocked = task("waiting");
3544        blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
3545        q.put(&mut blocked).unwrap();
3546
3547        let removed = q.remove(&dep.id, false, &questions).unwrap();
3548        assert_eq!(removed.released, [blocked.id.clone()]);
3549        assert!(removed.still_blocked.is_empty());
3550
3551        let after = q.get(&blocked.id).unwrap();
3552        assert_eq!(after.status, TaskStatus::Queued);
3553        assert!(after.blocked_by.is_empty());
3554        assert!(after.block_reason.is_none());
3555        let notes = notices_of(dir.path());
3556        assert_eq!(notes.len(), 1, "{notes:?}");
3557        assert_eq!(notes[0].severity, crate::notices::Severity::Info);
3558    }
3559
3560    #[test]
3561    fn removing_one_of_two_dependencies_keeps_the_other() {
3562        let (dir, q) = queue();
3563        let questions = Questions::at(dir.path().join("questions"));
3564        let mut dep = task("dependency");
3565        q.put(&mut dep).unwrap();
3566        let mut other = task("other");
3567        q.put(&mut other).unwrap();
3568        let mut blocked = task("waiting");
3569        blocked.block(
3570            vec![dep.id.clone(), other.id.clone()],
3571            Some("waits on both".to_owned()),
3572        );
3573        q.put(&mut blocked).unwrap();
3574
3575        let removed = q.remove(&dep.id, false, &questions).unwrap();
3576        assert!(removed.released.is_empty());
3577        assert_eq!(removed.still_blocked, [blocked.id.clone()]);
3578
3579        let after = q.get(&blocked.id).unwrap();
3580        assert_eq!(after.status, TaskStatus::Blocked);
3581        assert_eq!(after.blocked_by, [other.id.clone()]);
3582        // The tombstone stays while a task still names the id... only this
3583        // one's dependency is gone, so nothing references it and it may go.
3584        assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
3585    }
3586
3587    #[test]
3588    fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
3589        let (dir, q) = queue();
3590        let questions = Questions::at(dir.path().join("questions"));
3591        let mut dep = task("dependency");
3592        q.put(&mut dep).unwrap();
3593        let mut blocked = task("waiting");
3594        blocked.block(vec![dep.id.clone()], None);
3595        q.put(&mut blocked).unwrap();
3596
3597        // The dependent is claimed elsewhere, so `remove` has to skip it.
3598        let claim = q.claim(&blocked.id).unwrap();
3599        let removed = q.remove(&dep.id, false, &questions).unwrap();
3600        assert!(removed.released.is_empty());
3601        drop(claim);
3602
3603        let mut task = q.get(&blocked.id).unwrap();
3604        assert_eq!(task.status, TaskStatus::Blocked);
3605        assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
3606        assert_eq!(q.apply_deleted_blockers(&mut task), [dep.id.clone()]);
3607        assert_eq!(task.status, TaskStatus::Queued);
3608    }
3609
3610    #[test]
3611    fn a_dependency_without_a_tombstone_is_still_missing() {
3612        let (dir, q) = queue();
3613        let questions = Questions::at(dir.path().join("questions"));
3614        let mut dep = task("dependency");
3615        q.put(&mut dep).unwrap();
3616        std::fs::remove_file(q.path_of(&dep.id)).unwrap();
3617        assert_eq!(
3618            missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
3619            [dep.id.clone()]
3620        );
3621        assert!(deleted_blockers(&q, std::slice::from_ref(&dep.id)).is_empty());
3622    }
3623
3624    #[test]
3625    fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
3626        let mut t = task("held");
3627        t.hold_machine(Some("because".to_owned()));
3628        t.blocked_by = vec!["gone".to_owned()];
3629        assert!(!t.dependency_deleted("gone"));
3630        assert_eq!(t.status, TaskStatus::Held);
3631    }
3632
3633    #[test]
3634    fn a_failed_record_removal_takes_the_tombstone_back() {
3635        let (_dir, q) = queue();
3636        let mut t = task("stays");
3637        q.put(&mut t).unwrap();
3638        q.write_tombstone(&t.id).unwrap();
3639        let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
3640        assert!(err.is_err());
3641        // `remove` is what withdraws the marker; a live record is never
3642        // treated as deleted whatever is on disk.
3643        assert!(!q.was_deleted(&t.id));
3644    }
3645
3646    fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
3647        let p = dir.join(name);
3648        std::fs::write(&p, body).unwrap();
3649        p
3650    }
3651
3652    #[test]
3653    fn an_attachment_copy_survives_deleting_its_source() {
3654        let (dir, q) = queue();
3655        let src = source_file(dir.path(), "shot.png", "pixels");
3656        let mut t = task("with a picture");
3657        let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
3658        q.put(&mut t).unwrap();
3659        std::fs::remove_file(&src).unwrap();
3660        assert_eq!(names, ["shot.png"]);
3661        let loaded = q.get(&t.id).unwrap();
3662        let paths = q.attachment_paths(&loaded);
3663        assert_eq!(paths.len(), 1);
3664        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
3665    }
3666
3667    #[test]
3668    fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
3669        let (dir, q) = queue();
3670        let mut t = task("bad names");
3671        for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
3672            let src = source_file(dir.path(), name, "x");
3673            assert!(
3674                q.attach(&mut t, &[src]).is_err(),
3675                "`{name}` must be refused"
3676            );
3677        }
3678        // A drive-qualified name cannot exist as a file on Windows (joining it
3679        // to a directory yields a drive-relative path to `foo.png` instead),
3680        // so the rule is asserted on the name itself, everywhere.
3681        assert!(!crate::ask::valid_asset_name("C:foo.png"));
3682        #[cfg(not(windows))]
3683        {
3684            let src = source_file(dir.path(), "C:foo.png", "x");
3685            assert!(q.attach(&mut t, &[src]).is_err());
3686        }
3687        let long = format!("{}.png", "a".repeat(70));
3688        let src = source_file(dir.path(), &long, "x");
3689        assert!(q.attach(&mut t, &[src]).is_err());
3690        assert!(t.attachments.is_empty());
3691        assert!(!q.attachments_dir(&t.id).exists());
3692    }
3693
3694    #[test]
3695    fn a_taken_attachment_name_is_numbered_not_overwritten() {
3696        let (dir, q) = queue();
3697        let a = source_file(dir.path(), "shot.png", "one");
3698        let sub = dir.path().join("other");
3699        std::fs::create_dir_all(&sub).unwrap();
3700        let b = source_file(&sub, "shot.png", "two");
3701        let mut t = task("collision");
3702        q.attach(&mut t, &[a]).unwrap();
3703        q.attach(&mut t, &[b]).unwrap();
3704        assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
3705        let paths = q.attachment_paths(&t);
3706        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
3707        assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
3708    }
3709
3710    #[test]
3711    fn a_renumbered_name_stays_inside_the_length_bound() {
3712        let (dir, q) = queue();
3713        let name = format!("{}.png", "a".repeat(60));
3714        assert_eq!(name.len(), 64);
3715        let a = source_file(dir.path(), &name, "one");
3716        let sub = dir.path().join("other");
3717        std::fs::create_dir_all(&sub).unwrap();
3718        let b = source_file(&sub, &name, "two");
3719        let mut t = task("long");
3720        q.attach(&mut t, &[a, b]).unwrap();
3721        assert_eq!(t.attachments.len(), 2);
3722        assert!(
3723            t.attachments
3724                .iter()
3725                .all(|n| crate::ask::valid_asset_name(n))
3726        );
3727        assert!(t.attachments[1].ends_with("-2.png"));
3728    }
3729
3730    #[test]
3731    fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
3732        let (dir, q) = queue();
3733        let good = source_file(dir.path(), "good.png", "ok");
3734        let mut t = task("partial");
3735        q.attach(&mut t, &[good]).unwrap();
3736        let more = source_file(dir.path(), "more.png", "ok");
3737        let missing = dir.path().join("missing.png");
3738        assert!(q.attach(&mut t, &[more, missing]).is_err());
3739        assert_eq!(t.attachments, ["good.png"]);
3740        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
3741            .unwrap()
3742            .flatten()
3743            .collect();
3744        assert_eq!(on_disk.len(), 1);
3745    }
3746
3747    /// Make the next `put` of `t` fail: its temp file's path is a directory.
3748    fn block_put(q: &Queue, t: &Task) -> PathBuf {
3749        let tmp = q.path_of(&t.id).with_extension("json.tmp");
3750        std::fs::create_dir_all(&tmp).unwrap();
3751        tmp
3752    }
3753
3754    #[test]
3755    fn a_failed_put_leaves_no_new_attachment_directory() {
3756        let (dir, q) = queue();
3757        let mut t = task("fresh");
3758        let tmp = block_put(&q, &t);
3759        let src = source_file(dir.path(), "shot.png", "x");
3760        assert!(q.attach_and_put(&mut t, &[src]).is_err());
3761        assert!(t.attachments.is_empty());
3762        assert!(!q.attachments_dir(&t.id).exists());
3763        assert!(!q.path_of(&t.id).exists());
3764        std::fs::remove_dir(tmp).unwrap();
3765    }
3766
3767    #[test]
3768    fn a_failed_put_removes_only_the_copy_it_just_made() {
3769        let (dir, q) = queue();
3770        let mut t = task("edited");
3771        let first = source_file(dir.path(), "first.png", "1");
3772        q.attach_and_put(&mut t, &[first]).unwrap();
3773        block_put(&q, &t);
3774        let second = source_file(dir.path(), "second.png", "2");
3775        assert!(q.attach_and_put(&mut t, &[second]).is_err());
3776        assert_eq!(t.attachments, ["first.png"]);
3777        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
3778            .unwrap()
3779            .flatten()
3780            .map(|e| e.file_name().to_string_lossy().into_owned())
3781            .collect();
3782        assert_eq!(on_disk, ["first.png"]);
3783        assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
3784    }
3785
3786    #[test]
3787    fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
3788        let (dir, q) = queue();
3789        let questions = Questions::at(dir.path().join("questions"));
3790        let gone = task("gone");
3791        let mut other = task("other");
3792        let mut live = task("live");
3793        q.put(&mut other).unwrap();
3794        q.put(&mut live).unwrap();
3795        // `gone` has no record: its removal finished deleting the record but
3796        // not the set-aside attachments.
3797        let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
3798        std::fs::create_dir_all(&orphan).unwrap();
3799        std::fs::write(orphan.join("shot.png"), "x").unwrap();
3800        // `live` still has a record, so its `.removing` belongs to a removal
3801        // in progress and must be left alone.
3802        let busy = q.root.join(format!("{}.attachments.removing", live.id));
3803        std::fs::create_dir_all(&busy).unwrap();
3804
3805        q.remove(&other.id, false, &questions).unwrap();
3806        assert!(!orphan.exists(), "an orphan is swept");
3807        assert!(busy.exists(), "a removal in progress is left alone");
3808    }
3809
3810    #[test]
3811    fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
3812        let (dir, q) = queue();
3813        let questions = Questions::at(dir.path().join("questions"));
3814        let mut t = task("stuck");
3815        let src = source_file(dir.path(), "shot.png", "x");
3816        q.attach_and_put(&mut t, &[src]).unwrap();
3817        // A non-empty directory already at the set-aside name makes the rename
3818        // fail; its record is present, so the sweep leaves it in place.
3819        let aside = q.root.join(format!("{}.attachments.removing", t.id));
3820        std::fs::create_dir_all(&aside).unwrap();
3821        std::fs::write(aside.join("old.png"), "o").unwrap();
3822        assert!(q.remove(&t.id, false, &questions).is_err());
3823        assert!(q.path_of(&t.id).exists());
3824        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
3825    }
3826
3827    #[test]
3828    fn a_failed_record_removal_puts_the_attachments_back() {
3829        let (dir, q) = queue();
3830        let mut t = task("rollback");
3831        let src = source_file(dir.path(), "shot.png", "x");
3832        q.attach_and_put(&mut t, &[src]).unwrap();
3833        let err = q
3834            .remove_record_with_attachments(&t.id, |_| {
3835                Err(std::io::Error::other("injected failure"))
3836            })
3837            .unwrap_err();
3838        assert!(format!("{err:#}").contains("injected failure"));
3839        assert!(q.path_of(&t.id).exists());
3840        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
3841        assert!(
3842            !q.root
3843                .join(format!("{}.attachments.removing", t.id))
3844                .exists()
3845        );
3846    }
3847
3848    #[test]
3849    fn editing_a_task_keeps_its_attachments() {
3850        let (dir, q) = queue();
3851        let src = source_file(dir.path(), "shot.png", "x");
3852        let mut t = task("editable");
3853        q.attach(&mut t, &[src]).unwrap();
3854        t.edit("new".to_owned(), "new text".to_owned()).unwrap();
3855        q.put(&mut t).unwrap();
3856        assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
3857    }
3858
3859    #[test]
3860    fn removing_a_task_deletes_its_attachments() {
3861        let (dir, q) = queue();
3862        let questions = Questions::at(dir.path().join("questions"));
3863        let src = source_file(dir.path(), "shot.png", "x");
3864        let mut t = task("doomed");
3865        q.attach(&mut t, &[src]).unwrap();
3866        q.put(&mut t).unwrap();
3867        assert!(q.attachments_dir(&t.id).is_dir());
3868        q.remove(&t.id, false, &questions).unwrap();
3869        assert!(!q.attachments_dir(&t.id).exists());
3870        assert!(q.list().is_empty());
3871    }
3872
3873    #[test]
3874    fn a_task_written_before_attachments_still_reads() {
3875        let (_dir, q) = queue();
3876        let mut t = task("old");
3877        q.put(&mut t).unwrap();
3878        let path = q.path_of(&t.id);
3879        let mut v: serde_json::Value =
3880            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3881        v.as_object_mut().unwrap().remove("attachments");
3882        std::fs::write(&path, v.to_string()).unwrap();
3883        assert!(q.get(&t.id).unwrap().attachments.is_empty());
3884    }
3885
3886    #[test]
3887    fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
3888        let q = Queue::at(PathBuf::from("relative-queue"));
3889        let mut t = task("rel");
3890        t.attachments.push("shot.png".to_owned());
3891        let paths = q.attachment_paths(&t);
3892        assert!(paths[0].is_absolute(), "{}", paths[0].display());
3893        assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
3894    }
3895
3896    #[test]
3897    fn link_run_adds_a_run_once_and_touches_nothing_else() {
3898        let dir = tempfile::tempdir().unwrap();
3899        let queue = Queue::at(dir.path().join("queue"));
3900        let mut t = Task::new(
3901            "t".to_owned(),
3902            "do it".to_owned(),
3903            PathBuf::from("."),
3904            Source::Human,
3905        );
3906        queue.put(&mut t).unwrap();
3907        let before = queue.get(&t.id).unwrap();
3908
3909        let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
3910        assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
3911        assert_eq!(linked.status, before.status);
3912        assert_eq!(linked.attempts, before.attempts);
3913        assert_eq!(linked.interrupt, before.interrupt);
3914
3915        let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
3916        assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
3917        assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
3918        assert!(queue.link_run("no-such-task", "r").is_err());
3919    }
3920
3921    #[test]
3922    fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
3923        let dir = tempfile::tempdir().unwrap();
3924        let queue = Queue::at(dir.path().join("queue"));
3925        let mut t = Task::new(
3926            "t".to_owned(),
3927            "do it".to_owned(),
3928            PathBuf::from("."),
3929            Source::Human,
3930        );
3931        queue.put(&mut t).unwrap();
3932        // The daemon's copy, taken before the link.
3933        let mut snapshot = queue.get(&t.id).unwrap();
3934        queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
3935
3936        snapshot.start("20260930-000000-aaaa".to_owned());
3937        queue.put(&mut snapshot).unwrap();
3938
3939        let stored = queue.get(&t.id).unwrap();
3940        assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
3941        assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
3942        assert_eq!(stored.attempts, 1);
3943    }
3944
3945    #[test]
3946    fn concurrent_links_and_daemon_saves_lose_nothing() {
3947        let dir = tempfile::tempdir().unwrap();
3948        let queue = Queue::at(dir.path().join("queue"));
3949        let mut t = Task::new(
3950            "t".to_owned(),
3951            "do it".to_owned(),
3952            PathBuf::from("."),
3953            Source::Human,
3954        );
3955        queue.put(&mut t).unwrap();
3956        let id = t.id.clone();
3957
3958        let linkers: Vec<_> = (0..4)
3959            .map(|n| {
3960                let (queue, id) = (queue.clone(), id.clone());
3961                std::thread::spawn(move || {
3962                    for k in 0..10 {
3963                        queue
3964                            .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
3965                            .unwrap();
3966                    }
3967                })
3968            })
3969            .collect();
3970        // The daemon's side: transitions saved from its own, ever staler,
3971        // copy of the task.
3972        let mut mine = queue.get(&id).unwrap();
3973        for k in 0..10 {
3974            mine.start(format!("20260930-000009-d{k:03}"));
3975            queue.put(&mut mine).unwrap();
3976        }
3977        for l in linkers {
3978            l.join().unwrap();
3979        }
3980
3981        let stored = queue.get(&id).unwrap();
3982        assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
3983        assert_eq!(
3984            stored.attempts, 10,
3985            "linking never rewinds the daemon's work"
3986        );
3987    }
3988
3989    fn age_lock(path: &Path) {
3990        let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
3991        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
3992            .unwrap();
3993    }
3994
3995    #[test]
3996    fn concurrent_stale_takeover_yields_one_holder() {
3997        use std::sync::atomic::{AtomicUsize, Ordering};
3998        use std::sync::{Arc, Barrier};
3999        for _ in 0..5 {
4000            let dir = tempfile::tempdir().unwrap();
4001            let q = Queue::at(dir.path().to_path_buf());
4002            let lock = dir.path().join("t.write-lock");
4003            std::fs::write(&lock, "dead-0000").unwrap();
4004            age_lock(&lock);
4005            let n = 6;
4006            let barrier = Arc::new(Barrier::new(n));
4007            let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
4008            let handles: Vec<_> = (0..n)
4009                .map(|_| {
4010                    let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
4011                    std::thread::spawn(move || {
4012                        b.wait();
4013                        let g = q.lock_task("t").unwrap();
4014                        let held = now.fetch_add(1, Ordering::SeqCst) + 1;
4015                        max.fetch_max(held, Ordering::SeqCst);
4016                        std::thread::sleep(std::time::Duration::from_millis(20));
4017                        now.fetch_sub(1, Ordering::SeqCst);
4018                        drop(g);
4019                    })
4020                })
4021                .collect();
4022            for h in handles {
4023                h.join().unwrap();
4024            }
4025            assert_eq!(max.load(Ordering::SeqCst), 1);
4026            assert!(!lock.exists());
4027        }
4028    }
4029
4030    #[test]
4031    fn dropping_a_stolen_lock_leaves_the_new_holders_lock() {
4032        let dir = tempfile::tempdir().unwrap();
4033        let q = Queue::at(dir.path().to_path_buf());
4034        let lock = dir.path().join("t.write-lock");
4035        let a = q.lock_task("t").unwrap();
4036        age_lock(&lock);
4037        let b = q.lock_task("t").unwrap();
4038        assert_ne!(a.token, b.token);
4039        drop(a);
4040        assert_eq!(std::fs::read_to_string(&lock).unwrap(), b.token);
4041        drop(b);
4042        assert!(!lock.exists());
4043    }
4044
4045    #[test]
4046    fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
4047        let dir = tempfile::tempdir().unwrap();
4048        let lock = dir.path().join("t.write-lock");
4049        std::fs::write(&lock, "new-token").unwrap();
4050        assert!(!break_stale(&lock, "old-token"));
4051        assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
4052        // Same token but fresh: not stale any more, so also left alone.
4053        assert!(!break_stale(&lock, "new-token"));
4054        assert!(lock.exists());
4055        age_lock(&lock);
4056        assert!(break_stale(&lock, "new-token"));
4057        assert!(!lock.exists());
4058    }
4059
4060    #[test]
4061    fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
4062        let dir = tempfile::tempdir().unwrap();
4063        let lock = dir.path().join("t.write-lock");
4064        std::fs::write(&lock, "dead-1").unwrap();
4065        age_lock(&lock);
4066        let marker = break_marker(&lock, "dead-1");
4067        std::fs::write(&marker, "crashed-remover").unwrap();
4068        // Fresh marker: another remover is working, so nothing is broken.
4069        assert!(!break_stale(&lock, "dead-1"));
4070        assert!(lock.exists());
4071        // Stale marker: recovered, then the lock is broken.
4072        age_lock(&marker);
4073        assert!(break_stale(&lock, "dead-1"));
4074        assert!(!lock.exists());
4075        assert!(!marker.exists());
4076    }
4077}