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
33#[cfg(test)]
34thread_local! {
35    pub(crate) static LIST_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
36}
37
38use std::collections::HashMap;
39use std::num::NonZeroUsize;
40use std::path::{Path, PathBuf};
41
42use anyhow::{Context, Result, bail};
43use jiff::Timestamp;
44use serde::{Deserialize, Serialize};
45
46use crate::ask::Questions;
47use crate::config::BuildCache;
48use crate::id_reserve::{IdSource, path_exists};
49
50/// On-disk format for a queued task. Bumped when a field's meaning changes.
51///
52/// 21: task/chat command effect receipts commit atomically with local transitions.
53///
54/// 18: retained review criteria snapshots survive operator edits.
55///
56/// 17: durable explicit operator resumption, independent of run startup.
57///
58/// 7: added [`Task::attachments`], names of files copied under
59/// `<id>.attachments/` beside the task file (a field only; `#[serde(default)]`,
60/// so an older record reads as empty and [`read_path`] still accepts it).
61///
62/// 6: added [`Task::resume_override`] (a field only; `#[serde(default)]`, so
63/// an older record reads as `None` and [`read_path`] still accepts it).
64///
65/// 5: added [`Task::triage_applied`], the ids of triage questions whose
66/// answer has already been applied to this task. A "resume" answer used to
67/// leave no trace ([`Task::release`] clears [`Task::hold_reason`], which was
68/// the only place the applied marker lived), so when the released task failed
69/// its attempts and went back to `held`, the next idle pass found the same
70/// answered question "not applied" and released it again with `attempts` reset
71/// to 0 - the `max_attempts` bound never held. `#[serde(default)]` so an older
72/// record reads as empty. A task already looping when this build arrives has
73/// no record, so it is released once more, recorded, and then stays held.
74///
75/// 8: added [`Task::followup`], the origin of a task `crate::followup` filed
76/// from a merged run's leftover findings. Field-only bump, `#[serde(default)]`.
77///
78/// 4: added [`Task::blocked_from`], the status a task had the moment it
79/// became [`TaskStatus::Blocked`], so [`Task::unblock`] restores it instead
80/// of always landing on [`TaskStatus::Queued`]. Without it, a task a human
81/// or `crate::triage` had deliberately left [`TaskStatus::Held`] — machine
82/// or manual — would lose that the instant `crate::conduct` blocked it on a
83/// follow-up question, and come back `Queued` the moment the question was
84/// answered, regardless of what the answer said: exactly the loop where a
85/// task the operator told to stay held instead re-enters the competition
86/// queue every time someone answers a question about it. `#[serde(default)]`
87/// so an older record reads as `None`; [`Task::unblock`] then falls back to
88/// inferring `Held` from surviving hold evidence ([`Task::hold_reason`] /
89/// [`Task::hold_source`], never cleared by [`Task::block`]) rather than
90/// guessing `Queued` outright — see [`Task::unblock`]'s own doc.
91///
92/// 9: added [`Task::held_at`], the start of the current hold, so a notice can
93/// tell a question filed for this hold from one about an older cause.
94/// Field-only, `#[serde(default)]`.
95///
96/// 10: added [`Task::overrides`] and [`Task::review_of`], so a run started by
97/// hand (`magi run` / `magi review`) is carried by a task without losing its
98/// command-line choices. Field-only.
99///
100/// 11: added [`TaskStatus::Parked`] and [`Task::park_reason`], so a run that
101/// stopped at a node boundary (an upgrade, an operator's park) is no longer
102/// recorded as a failed task. Variant plus `#[serde(default)]` field; an older
103/// build must not half-read the new status.
104///
105/// 12: added [`Task::origin_chat`], the talk a task descends from, so a
106/// follow-up still knows its chat after an ancestor task is deleted.
107/// Field-only, `#[serde(default)]`.
108///
109/// 13: added [`Task::chat_notice`], the record that a chat-filed task's final
110/// state was reported to its conversation. Field-only, `#[serde(default)]`;
111/// a record below this schema is never notified (an upgrade must not replay
112/// the whole history into chats).
113///
114/// 3: added [`HoldSource`] so conductor recovery cannot release a hold an
115/// operator deliberately placed. Old records default to `None` and are
116/// protected as operator-held until an explicit release; the safe direction
117/// when their author was never recorded.
118///
119/// 2: added [`TaskStatus::Blocked`], [`Task::blocked_by`] and
120/// [`Task::block_reason`] (`crate::conduct`'s decisions) and
121/// [`Task::answers`] (operator answers carried forward to the next
122/// conductor prompt and the next run's instruction). All three are
123/// `#[serde(default)]`, so [`read_path`] accepts anything up to and
124/// including this schema rather than only an exact match — a task written
125/// by a build that only knew about schema 1 has nothing to say about
126/// blocking or answers, and defaulting those fields is exactly as good a
127/// reading as a value that build never had a chance to write.
128///
129/// 15: added [`Task::passes`], what each settled pass over a run did to the
130/// attempt budget and why it stopped. Field-only, `#[serde(default)]`; a task
131/// from before this has no entry for its earlier passes, which stay unknown.
132///
133/// 14: record whether a task count edit's overrides inherit daemon options.
134/// Old overrides default to isolated command-line settings, including empty ones.
135///
136/// 16: added [`Task::attempt_limit`], an optional task-specific retry budget.
137/// Field-only, `#[serde(default)]`; old records inherit the daemon limit.
138///
139/// 19: persist settled pass start times for upgrade-resume scheduling.
140/// Old passes default to unknown and use settlement order as an approximation.
141/// 20: persist the task decision chat destination, defaulting to absent.
142/// 21: repository assignment history and execution boundaries, empty on old tasks.
143/// 22: typed disk resource waits and a retained execution pin for automatic recovery.
144/// 23: new tasks inherit `verify.build_cache` unless explicitly overridden.
145/// Older tasks retain shared builds.
146///
147/// 24: bind automatic recovery-budget holds to their stopped execution.
148///
149/// 25: append-only completion/reopen audit and occurrence-bound completion notices.
150pub const SCHEMA: u32 = 25;
151
152const RECOVERY_HOLD_SCHEMA: u32 = 24;
153
154/// Candidate order only: all claims, lanes and eligibility gates still apply.
155/// Upgrade-parked runs retain their pass-start order ahead of ordinary work,
156/// regardless of ordinary priority. Old records without a start time use
157/// settlement time and task id as an approximation. Other parks are ordinary.
158/// Urgent slots and explicit interrupts are handled separately by the daemon.
159pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
160    match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
161        (Some(a), Some(b)) => a.cmp(&b),
162        (Some(_), None) => std::cmp::Ordering::Less,
163        (None, Some(_)) => std::cmp::Ordering::Greater,
164        (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
165    }
166}
167
168/// Resource waits eligible for automatic admission checks, never owner approval.
169///
170/// Bound to the `hold_reason` it was recorded with: [`Task::has_disk_capacity_cause`]
171/// honours it only while the task still carries that exact reason, so a later
172/// hold that rewrites the reason invalidates it even if a transition forgets to
173/// clear the cause.
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
175#[serde(tag = "kind", rename_all = "snake_case")]
176pub enum MachineHoldCause {
177    /// The disk floor or an output reservation prevented execution.
178    DiskCapacity {
179        /// The exact `hold_reason` the hold was placed with.
180        reason: String,
181        /// Admission stopped before a new execution was established.
182        #[serde(default)]
183        before_start: bool,
184    },
185}
186
187/// Who placed the current hold.
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
189#[serde(rename_all = "lowercase")]
190pub enum HoldSource {
191    /// An operator used the CLI or web UI.
192    Manual,
193    /// The daemon or conductor placed the hold as part of its own recovery.
194    Machine,
195}
196
197impl HoldSource {
198    /// Short human-facing label for reports and the CLI.
199    pub fn label(self) -> &'static str {
200        match self {
201            Self::Manual => "manual",
202            Self::Machine => "machine",
203        }
204    }
205}
206
207/// Where a task came from. Recorded because "who asked for this" is the first
208/// question about an autonomous run, and the answer is not recoverable later.
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(tag = "kind", rename_all = "lowercase")]
211pub enum Source {
212    /// A person, at a terminal or through the web UI.
213    Human,
214    /// An agent inside a run, via `magi task add`. Both ids are recorded so a
215    /// task can be traced back to the exact seat that asked for it.
216    Agent {
217        /// Run the asking agent belonged to.
218        run: String,
219        /// Node it was working in, e.g. `implement` or `review`.
220        node: String,
221    },
222    /// A GitHub issue, imported by number.
223    Issue {
224        /// Issue number.
225        number: u64,
226        /// `owner/repo`, as `gh` reports it.
227        repo: String,
228    },
229}
230
231/// The `node` a [`Source::Agent`] carries when the asker is a chat
232/// conversation (its `run` is then the conversation's id).
233pub const CHAT_NODE: &str = "chat";
234
235impl Source {
236    /// Short human-facing label, for lists and the web UI.
237    pub fn label(&self) -> String {
238        match self {
239            Self::Human => "human".to_owned(),
240            Self::Agent { run, node } => format!("{node}@{}", short(run)),
241            Self::Issue { number, .. } => format!("issue #{number}"),
242        }
243    }
244}
245
246/// Where a task is in its life.
247#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "lowercase")]
249pub enum TaskStatus {
250    /// Waiting to be claimed.
251    Queued,
252    /// Claimed by a daemon; a run is in flight.
253    Running,
254    /// A run finished and its gate passed.
255    Done,
256    /// A run finished without passing, and attempts remain.
257    Failed,
258    /// Out of attempts, or held by hand. The loop will not pick it up.
259    Held,
260    /// Waiting on another task or an unanswered question. See
261    /// [`Task::blocked_by`]. Set and cleared by `crate::conduct` and
262    /// `crate::daemon`'s deterministic resolver, never by hand.
263    Blocked,
264    /// The run stopped at a node boundary because the process was asked to
265    /// give itself back. Nothing failed: the run's work is intact and the next
266    /// loop resumes it. Runnable like [`TaskStatus::Queued`]; the reason is in
267    /// [`Task::park_reason`], never [`Task::last_error`].
268    Parked,
269}
270
271impl TaskStatus {
272    /// Is this task eligible for a daemon to claim?
273    pub fn runnable(self) -> bool {
274        matches!(self, Self::Queued | Self::Failed | Self::Parked)
275    }
276
277    /// Lowercase name, as it appears on disk and in the API.
278    pub fn as_str(self) -> &'static str {
279        match self {
280            Self::Queued => "queued",
281            Self::Running => "running",
282            Self::Done => "done",
283            Self::Failed => "failed",
284            Self::Held => "held",
285            Self::Blocked => "blocked",
286            Self::Parked => "parked",
287        }
288    }
289}
290
291/// How many tasks sit in each [`TaskStatus`], for a dashboard tile — never a
292/// per-task view, so it carries no ids.
293#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
294pub struct TaskCounts {
295    /// Waiting to be claimed.
296    pub queued: usize,
297    /// Claimed; a run is in flight.
298    pub running: usize,
299    /// A run finished and its gate passed.
300    pub done: usize,
301    /// A run finished without passing, and attempts remain.
302    pub failed: usize,
303    /// Out of attempts, or held by hand.
304    pub held: usize,
305    /// Waiting on another task or an unanswered question.
306    pub blocked: usize,
307    /// Run parked at a node boundary; resumable, not a failure.
308    pub parked: usize,
309}
310
311impl TaskCounts {
312    /// Tally `tasks` by status. A pure function over whatever [`Queue::list`]
313    /// already read, so it needs no root of its own and stays trivially
314    /// testable against a hand-built slice.
315    pub fn of(tasks: &[Task]) -> Self {
316        Self::of_statuses(tasks.iter().map(|task| task.status))
317    }
318
319    /// Count current statuses from a reconciled display projection.
320    pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
321        let mut counts = Self::default();
322        for status in statuses {
323            match status {
324                TaskStatus::Queued => counts.queued += 1,
325                TaskStatus::Running => counts.running += 1,
326                TaskStatus::Done => counts.done += 1,
327                TaskStatus::Failed => counts.failed += 1,
328                TaskStatus::Held => counts.held += 1,
329                TaskStatus::Blocked => counts.blocked += 1,
330                TaskStatus::Parked => counts.parked += 1,
331            }
332        }
333        counts
334    }
335}
336
337/// Audit record and execution boundary for a repository reassignment.
338#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
339pub struct Reassignment {
340    /// Original repository.
341    pub from: PathBuf,
342    /// Newly selected repository.
343    pub to: PathBuf,
344    /// Control surface or conversation that requested this change.
345    pub actor: String,
346    /// Time of the operator decision.
347    pub at: Timestamp,
348    /// Runs before this boundary can never execute for this assignment.
349    pub run_boundary: usize,
350}
351
352/// Origin of a completion or reopen decision.
353#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
354#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
355pub enum CompletionActor {
356    /// Terminal operator.
357    Cli,
358    /// Web operator.
359    Web,
360    /// Decision made in the named conversation.
361    Chat(String),
362    /// Conductor decision.
363    Conductor,
364    /// Automatic run settlement.
365    DaemonSettle,
366}
367
368/// A task lifecycle decision, distinct from a run outcome.
369#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
370#[serde(rename_all = "snake_case")]
371pub enum CompletionAction {
372    /// Task was marked done.
373    Complete,
374    /// Task was reopened into an operator hold.
375    Reopen,
376}
377
378/// Run and publication evidence observed when a task decision was made.
379#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
380pub struct CompletionRunSnapshot {
381    /// Retained run identifier.
382    pub id: String,
383    /// Unknown when the retained record could not be read.
384    pub status: Option<crate::run::RunStatus>,
385    /// Recorded public pull request.
386    pub pr_url: Option<String>,
387    /// Recorded or freshly observed public lifecycle.
388    pub pr_state: Option<String>,
389    /// Last published or merged public commit.
390    pub pr_head: Option<String>,
391    /// Retained candidate and public branch names; never deleted by a task decision.
392    #[serde(default)]
393    pub branches: Vec<String>,
394    /// Why a run snapshot was unavailable.
395    pub error: Option<String>,
396}
397
398impl CompletionRunSnapshot {
399    fn from_run(state: &crate::run::RunState) -> Self {
400        let mut branches: Vec<String> = state
401            .candidates
402            .iter()
403            .map(|candidate| candidate.branch.clone())
404            .collect();
405        if let Some(branch) = &state.pr_head
406            && !branches.contains(branch)
407        {
408            branches.push(branch.clone());
409        }
410        Self {
411            id: state.id.clone(),
412            status: Some(state.status),
413            pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
414            pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
415            pr_head: state
416                .pr_merged_head
417                .clone()
418                .or_else(|| state.pr_pushed_head.clone()),
419            branches,
420            error: None,
421        }
422    }
423}
424
425/// Mandatory evidence supplied by every path that marks a task done.
426#[derive(Debug, Clone)]
427pub struct CompletionContext {
428    /// Surface or process responsible for the decision.
429    pub actor: CompletionActor,
430    /// Operator explanation or settlement rationale.
431    pub reason: Option<String>,
432    /// Explicit permission to abandon an unfinished latest run.
433    pub discard: bool,
434    /// Latest retained execution snapshot, including unreadable-record evidence.
435    pub run: Option<CompletionRunSnapshot>,
436    /// Retained runs whose outcomes could not be read during explicit discard.
437    pub unavailable_runs: Vec<String>,
438}
439
440impl CompletionContext {
441    /// Capture the latest retained execution without inventing missing evidence.
442    pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
443        let run = task
444            .runs
445            .last()
446            .map(|id| match crate::run::RunState::load_under(id, home) {
447                Ok(state) => CompletionRunSnapshot::from_run(&state),
448                Err(error) => CompletionRunSnapshot {
449                    id: id.clone(),
450                    status: None,
451                    pr_url: None,
452                    pr_state: None,
453                    pr_head: None,
454                    branches: Vec::new(),
455                    error: Some(format!("{error:#}")),
456                },
457            });
458        Self {
459            actor,
460            reason,
461            discard: false,
462            run,
463            unavailable_runs: Vec::new(),
464        }
465    }
466
467    /// Use the exact state already loaded by a run settlement.
468    pub fn from_run(
469        actor: CompletionActor,
470        reason: Option<String>,
471        _task: &Task,
472        state: &crate::run::RunState,
473    ) -> Self {
474        Self {
475            actor,
476            reason,
477            discard: false,
478            run: Some(CompletionRunSnapshot::from_run(state)),
479            unavailable_runs: Vec::new(),
480        }
481    }
482}
483
484/// Immutable, occurrence-addressed task completion/reopen audit.
485#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
486pub struct CompletionEvent {
487    /// Unique decision occurrence, also used to identify its completion notice.
488    pub occurrence: String,
489    /// Kind of transition.
490    pub action: CompletionAction,
491    /// Decision origin.
492    pub actor: CompletionActor,
493    /// Explanation retained verbatim.
494    pub reason: Option<String>,
495    /// Whether unfinished work was explicitly discarded.
496    pub discard: bool,
497    /// Task status before the decision.
498    pub prior_status: TaskStatus,
499    /// Hold explanation before completion cleared active controls.
500    #[serde(default)]
501    pub prior_hold_reason: Option<String>,
502    /// Dependency explanation before completion cleared active controls.
503    #[serde(default)]
504    pub prior_block_reason: Option<String>,
505    /// Last run/task failure evidence before the lifecycle decision.
506    #[serde(default)]
507    pub prior_error: Option<String>,
508    /// Decision time.
509    pub at: Timestamp,
510    /// Run/PR evidence at that time.
511    pub run: Option<CompletionRunSnapshot>,
512    /// Unknown historical outcomes retained when the owner explicitly discarded.
513    #[serde(default, skip_serializing_if = "Vec::is_empty")]
514    pub unavailable_runs: Vec<String>,
515}
516
517/// One unit of work.
518#[derive(Debug, Clone, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct Task {
521    /// On-disk format version.
522    pub schema: u32,
523    /// Task id, e.g. `20260902-140501-a1b2`.
524    pub id: String,
525    /// One line, for lists and notifications.
526    pub title: String,
527    /// The task itself, handed to the graph verbatim.
528    pub instruction: String,
529    /// Explicit, SHA-pinned implementation imports; separate from instruction text.
530    #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
531    pub sources: crate::refs::Sources,
532    /// Repository to work in.
533    pub repo: PathBuf,
534    /// Repository assignment boundaries; historical runs remain in `runs`.
535    #[serde(default)]
536    pub reassignments: Vec<Reassignment>,
537    /// Who asked.
538    pub source: Source,
539    /// Durable destination for task decision messages (including tasks filed outside chat).
540    #[serde(default)]
541    pub chat: Option<String>,
542    /// Higher runs first; ties break oldest-first so nothing starves.
543    #[serde(default)]
544    pub priority: i32,
545    /// Run this task alone: one implementer, no panel of judges to convince.
546    ///
547    /// `#[serde(default)]` so a queue file written before this field existed
548    /// still reads, as `false` - the ordinary multi-candidate competition,
549    /// unchanged. A task set to `solo` still runs the whole graph; only the
550    /// candidate count the daemon builds it with changes, and
551    /// [`crate::graph::Runner`] already collapses a single-candidate run to
552    /// implement → review → gate → merge on its own (see
553    /// [`crate::graph::Runner::review`]'s doc), so nothing about judging,
554    /// deliberation or voting had to change to support this.
555    #[serde(default)]
556    pub solo: bool,
557    /// Current state.
558    pub status: TaskStatus,
559    /// Append-only operator and automatic completion/reopen decisions.
560    #[serde(default)]
561    pub completion_history: Vec<CompletionEvent>,
562    /// How many times this task has been claimed.
563    #[serde(default)]
564    pub attempts: usize,
565    /// Total attempt budget; `None` inherits the daemon limit.
566    #[serde(default)]
567    pub attempt_limit: Option<NonZeroUsize>,
568    /// Distinct runs, ordered by their most recent claim. Older records may
569    /// contain repeated ids; execution history lives in the run pass records.
570    #[serde(default)]
571    pub runs: Vec<String>,
572    /// Reserved startups that failed before execution; never a resume source or execution attempt.
573    #[serde(default)]
574    pub startup_failures: Vec<crate::run::StartupFailure>,
575    /// Why the last attempt did not land.
576    #[serde(default)]
577    pub last_error: Option<String>,
578    /// What a human hold is waiting on.
579    ///
580    /// `None` covers both the ordinary cases: a hold the loop makes itself
581    /// (out of attempts, or the disk gate closed) explains itself through
582    /// [`Task::last_error`] instead, and a human hold nobody bothered to
583    /// explain is still a valid hold. The queue has no way to express a
584    /// dependency between two tasks, so on the occasions a hold really is
585    /// "wait for that other task first", this is the only place that reason
586    /// survives - see [`Task::hold_manual`] and [`Task::release`].
587    ///
588    /// `#[serde(default)]` so a queue file written before this field existed
589    /// still reads, with no reason recorded rather than a parse error.
590    #[serde(default)]
591    pub hold_reason: Option<String>,
592    /// Who placed [`Task::hold_reason`].  `None` is a compatible old record;
593    /// see [`Task::operator_held`] for its deliberately conservative meaning.
594    #[serde(default)]
595    pub hold_source: Option<HoldSource>,
596    #[serde(default, skip_serializing_if = "Option::is_none")]
597    recovery_budget_hold: Option<RecoveryBudgetHold>,
598    /// Disk resource wait recorded by the admission gate; never owner consent.
599    #[serde(default)]
600    pub machine_hold_cause: Option<MachineHoldCause>,
601    /// Automatic resource recovery must resume this execution, never compete again.
602    #[serde(default)]
603    pub disk_resume_run: Option<String>,
604    /// Last bounded disk-monitor pass; persisted across scheduler replacement.
605    #[serde(default)]
606    pub disk_checked_at: Option<Timestamp>,
607    /// Diagnostic detail excerpted from the run that led to a hold - what a
608    /// human would have found opening `artifacts/` by hand, not the one-line
609    /// reason in [`Task::last_error`]. Set only when a run's own attempts are
610    /// exhausted and the task becomes [`TaskStatus::Held`]; `daemon` computes
611    /// it from the run's own record, since this module has no notion of a
612    /// run's internals. Bounded in length by the writer - see
613    /// `daemon::diagnostic` - so a verbose run cannot make this file grow
614    /// without limit.
615    ///
616    /// `#[serde(default)]` so a queue file written before this field existed
617    /// still reads, with no diagnostic recorded rather than a parse error.
618    #[serde(default)]
619    pub diagnostic: Option<String>,
620    /// What this task is waiting on: other task ids, unanswered
621    /// `crate::ask::Question` ids, or both. Non-empty exactly when
622    /// [`TaskStatus::Blocked`]; emptying it — see [`Task::unblock`] — is what
623    /// puts the task back at [`TaskStatus::Queued`].
624    ///
625    /// Set by `crate::conduct`'s decisions and cleared deterministically by
626    /// `crate::daemon` as each dependency resolves, never by a person. Never
627    /// `#[serde(default)]` is skipped: a queue file from before this field
628    /// existed has nothing to report here, and an empty list is exactly that.
629    #[serde(default)]
630    pub blocked_by: Vec<String>,
631    /// One line explaining the current [`Task::blocked_by`], written by
632    /// `crate::conduct`. Cleared whenever `blocked_by` empties.
633    #[serde(default)]
634    pub block_reason: Option<String>,
635    /// The status this task had the moment [`Task::block`] most recently
636    /// moved it to [`TaskStatus::Blocked`] — what [`Task::unblock`] restores
637    /// once nothing is left in `blocked_by`, instead of always landing on
638    /// [`TaskStatus::Queued`]. See [`SCHEMA`]'s doc for schema 4 on why this
639    /// exists: an answer to a question `crate::conduct` filed about a
640    /// [`TaskStatus::Held`] task must not itself be what puts the task back
641    /// in the competition queue.
642    ///
643    /// `#[serde(default)]` so a queue file written before this field existed
644    /// reads as `None`; [`Task::unblock`] treats that the same as a task
645    /// blocked straight from `Queued`, unless surviving hold evidence says
646    /// otherwise.
647    #[serde(default)]
648    pub blocked_from: Option<TaskStatus>,
649    /// Last change of blocking targets, independent of explanation or delivery writes.
650    #[serde(default)]
651    pub blocked_at: Option<Timestamp>,
652    /// Questions `crate::conduct` asked about this task that the operator has
653    /// since answered, oldest first — what was asked, and what they said.
654    ///
655    /// A blocking question's id leaves [`Task::blocked_by`] the moment
656    /// [`crate::ask::QuestionStatus::Answered`] is observed, but the id alone
657    /// tells nobody what was decided. This is what carries the answer's
658    /// *content* forward: into the next conductor prompt for this task, and
659    /// into the instruction handed to the next run — see `crate::daemon`'s
660    /// deterministic blocker resolution. Kept for the task's whole life, the
661    /// same as [`Task::runs`]: a release resets attempts, not evidence.
662    #[serde(default)]
663    pub answers: Vec<AnsweredQuestion>,
664    /// Ids of the `crate::triage` questions whose answer has been applied to
665    /// this task. Unlike [`Task::hold_reason`], [`Task::release`] and every
666    /// hold transition leave it alone, so an answer is applied at most once
667    /// however many times the task is held again. See [`SCHEMA`]'s doc for
668    /// schema 5. `#[serde(default)]` so an older record reads as empty.
669    #[serde(default)]
670    pub triage_applied: Vec<String>,
671    /// Ids of the `magi ask` questions whose [`crate::ask::ChoiceAction`] has
672    /// been applied to this task. Separate from [`Task::triage_applied`]
673    /// (a different producer) and, like it, untouched by [`Task::release`],
674    /// so one answer acts at most once however often the task is held again.
675    /// `#[serde(default)]` so an older record reads as empty.
676    #[serde(default)]
677    pub actions_applied: Vec<String>,
678    /// Exact task/chat commands committed in the same write as their effects.
679    /// These receipts survive subsequent transitions and execution starts.
680    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
681    pub decision_effects: std::collections::BTreeMap<String, String>,
682    /// Exact resume pins explicitly replaced or removed before dispatch.
683    /// Retained independently of later task transitions and stale writers.
684    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
685    pub superseded_resumes: std::collections::BTreeMap<String, String>,
686    /// Resume inquiry ownership committed atomically with task dispatch.
687    /// This is not effect evidence: only the run's committed pass proves execution.
688    /// Retained across recovery and stale writers until that pass can consume it.
689    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
690    pub dispatched_resumes: std::collections::BTreeMap<String, String>,
691    /// Durable base-recovery request keys saved atomically with the exact-run pin.
692    #[serde(default)]
693    pub base_recovery_requests: Vec<String>,
694    /// The operator's "resume" answer to a triage question, kept until the
695    /// task actually runs (or is done) so `crate::conduct` cannot silently
696    /// undo it and `crate::triage` can tell that a hold it sees now came
697    /// *after* the answer. See [`OperatorResume`]. `#[serde(default)]`.
698    #[serde(default)]
699    pub resume_override: Option<OperatorResume>,
700    /// The sync-only fence survives consumption of the ordinary dispatch pin.
701    #[serde(default, skip_serializing_if = "Option::is_none")]
702    pub sync_only: Option<crate::base_sync_only::Request>,
703    /// Immutable repair receipts, saved atomically with the exact-run queue pin.
704    #[serde(default)]
705    pub repair_grants: Vec<crate::repair_budget::Receipt>,
706    /// Append-only owner-authorized reconciliation of an unspent receipt.
707    #[serde(default)]
708    pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
709    /// Latest explicit operator release. Historical answers remain audit evidence;
710    /// this approval takes precedence over their earlier waiting premises.
711    #[serde(default)]
712    pub resumption: Option<Resumption>,
713    /// Earlier explicit approvals retained for audit and instruction suffix matching.
714    #[serde(default)]
715    pub resumption_history: Vec<Resumption>,
716    /// Latest explicit release or manual hold, used to reject delayed answers.
717    #[serde(default)]
718    pub operator_decided_at: Option<Timestamp>,
719    /// Set by `crate::conduct` when it chooses `Review` recovery for a task
720    /// whose branch survived a blocked run: the branch to reopen with
721    /// `crate::graph::Runner::review` instead of competing from scratch.
722    ///
723    /// Requeues the task the same way [`Task::release`] does, so it is
724    /// picked up by the ordinary loop; `crate::daemon` reads this field once,
725    /// when it actually starts the run, and clears it either way — consumed
726    /// on success, dropped if the branch no longer exists by then. Never set
727    /// from the conductor's own words: `crate::daemon` derives the branch
728    /// name itself from the task's last run, so a hallucinated branch can
729    /// never reach here.
730    #[serde(default)]
731    pub review_branch: Option<String>,
732    /// Authored criteria when the retained recovery review was selected.
733    #[serde(default)]
734    pub review_instruction: Option<String>,
735    /// Explicit public implementation selected by the operator; never inferred from prose.
736    #[serde(default)]
737    pub pr_recovery: Option<crate::pr_recovery::Selection>,
738    /// A release deliberately starts a new competition instead of resuming
739    /// the prior run. History remains as evidence in `runs`.
740    #[serde(default)]
741    pub fresh_start: bool,
742    /// Explicit replacement selection; persists through dispatch and resume.
743    #[serde(default)]
744    pub replacement: Option<crate::merge_decision::Replacement>,
745    /// Marked by an operator (`magi task interrupt`) to ask `magi serve` to
746    /// run this one ahead of whatever it already has in flight, once
747    /// `[daemon] pause_for_interrupts` is on - see
748    /// `crate::daemon::advance_interrupt`. Never set by the loop itself, and
749    /// deliberately a different operation from [`Task::set_priority`]: a
750    /// priority only reorders the queue a claim has not reached yet, while
751    /// this asks a run already in flight to park at its next safe boundary
752    /// and step aside. `#[serde(default)]` so a queue file written before
753    /// this field existed still reads, as `false` - no task interrupts
754    /// anything unless asked to, exactly as before.
755    #[serde(default)]
756    pub interrupt: bool,
757    /// Marked by `magi task add --urgent` or `magi task urgent`.
758    /// `crate::daemon::poll` dispatches this task through its own one-slot `urgent_sem` the moment it is
759    /// runnable, in addition to whatever is already running under the
760    /// ordinary `[daemon] max_concurrent_runs` pool - never instead of it,
761    /// and never by pausing or otherwise touching that run. This is the
762    /// opposite direction from [`Task::interrupt`]: that one asks a run
763    /// already in flight to step aside; this one never asks anything to
764    /// step aside, it only spends one additional, temporary concurrency
765    /// slot. The two are independent and may both be set on the same task,
766    /// but this exemption stops at `[daemon] pause_for_interrupts`'s own
767    /// park/resume handoff (75dd): while an interrupt sequence is actively
768    /// parking, running, or resuming - its own, or an unrelated task's -
769    /// `crate::daemon::interrupt_gate` withholds an urgent candidate exactly
770    /// like an ordinary one, never exempted. 75dd's "at most one run, ever,
771    /// at once" guarantee takes precedence, because the alternative is a run
772    /// still genuinely in flight (only *asked* to park, not yet gone) ending
773    /// up alongside a second one this feature let through - the very thing
774    /// that guarantee exists to rule out.
775    ///
776    /// `#[serde(default)]` so a queue file written before this field existed
777    /// still reads, as `false` - no task claims the urgent slot unless asked
778    /// to, exactly as before.
779    #[serde(default)]
780    pub urgent: bool,
781    /// Set by [`Task::new`], cleared once a queue has stored the task. Never
782    /// persisted: a task read from disk is always an existing one. While set,
783    /// [`Queue::put`] reserves the id (see [`Queue::file_with`]) instead of
784    /// merging into whatever record already carries it.
785    #[serde(skip)]
786    pub(crate) unfiled: bool,
787    /// Files (typically screenshots) copied into `<id>.attachments/` beside
788    /// this task's file by [`Queue::attach`], as bare validated names. The
789    /// copy is what makes them reach the implementer: the original may be
790    /// cleaned up long before the task runs. Untouched by [`Task::edit`].
791    /// `#[serde(default)]` so an older record reads as empty.
792    #[serde(default)]
793    pub attachments: Vec<String>,
794    /// Set on a task `crate::followup` filed from the findings a merged run
795    /// left open: which run and findings it carries, and how many follow-ups
796    /// deep it is. `None` for every ordinary task. `#[serde(default)]`.
797    #[serde(default)]
798    pub followup: Option<FollowUp>,
799    /// Id of the chat this task descends from: set by [`Task::new`] when a
800    /// chat files it, inherited by the follow-ups `crate::followup` files, so
801    /// the provenance survives deleting an ancestor. `None` for a task written
802    /// before the field existed (`crate::consult` then walks the ancestry).
803    /// `#[serde(default)]`.
804    #[serde(default)]
805    pub origin_chat: Option<String>,
806    /// The command-line choices (`--merge`, `-c`, `--seed`, ...) of the
807    /// `magi run` / `magi review` that filed this task, applied on top of the
808    /// repository's config by whoever executes it - a daemon included - so
809    /// handing the task over does not change what it does. A count edit on an
810    /// ordinary queue task explicitly inherits daemon options instead.
811    /// `#[serde(default)]`.
812    #[serde(default)]
813    pub overrides: Option<RunOverrides>,
814    /// The branch an explicit `magi review <branch>` asked to review. Unlike
815    /// [`Task::review_branch`] (a recovery choice the daemon consumes and
816    /// drops back to a competition when the branch is gone), this is the whole
817    /// request: it is never consumed, and a missing branch fails the attempt
818    /// rather than paying for an implementation nobody asked for.
819    /// `#[serde(default)]`.
820    #[serde(default)]
821    pub review_of: Option<String>,
822    /// When the current hold began. Set by the transitions into
823    /// [`TaskStatus::Held`] (a re-hold keeps it), cleared by
824    /// [`Task::release`]. `crate::notices` uses it as the identity of the
825    /// cause: a question filed before it is about something older.
826    #[serde(default)]
827    pub held_at: Option<Timestamp>,
828    /// Why the run parked, while the task is [`TaskStatus::Parked`]. Kept apart
829    /// from [`Task::last_error`] because nothing failed. Cleared by every
830    /// transition out of the parked state. `#[serde(default)]`.
831    #[serde(default)]
832    pub park_reason: Option<String>,
833    /// The last final state reported to the originating chat. See
834    /// [`Task::chat_notice_due`]. Never cleared by a release or requeue.
835    #[serde(default)]
836    pub chat_notice: Option<ChatNotice>,
837    /// Delivery ledger, unioned under the task lock even on stale writes.
838    #[serde(default)]
839    pub chat_notices: Vec<String>,
840    /// Structured producer identity of the unresolved hold. Requeues and prose
841    /// updates retain it; a settled run or a distinct startup stage replaces it.
842    #[serde(default)]
843    pub hold_notice_cause: Option<NoticeCause>,
844    /// Append-only: one entry per pass over a run that the loop settled. A
845    /// resumed run is one run with several passes, and `attempts` counts
846    /// claims net of refunds, so the two are not the same number; this says
847    /// which pass cost what. Kept across a release.
848    #[serde(default)]
849    pub passes: Vec<TaskPass>,
850    /// When the loop claimed this task for its latest dispatch. Stamped under
851    /// the claim, before any slow start-up work, so it is the real dispatch
852    /// order; `record_pass_at` prefers it over the graph's own pass start.
853    #[serde(default)]
854    pub dispatched_at: Option<Timestamp>,
855    /// Durable failed-input budget, unaffected by automatic release/requeue.
856    #[serde(default)]
857    pub recovery_budget: Option<RecoveryBudget>,
858    /// Inputs resolved before starting the current automatic attempt. The
859    /// settlement uses this same identity even for review-only runs.
860    #[serde(default)]
861    pub recovery_admission: Option<RecoveryAdmission>,
862    /// Previously seen input generations. Switching inputs away and back does
863    /// not refund an exhausted generation without explicit operator authority.
864    #[serde(default)]
865    pub recovery_generations: Vec<RecoveryBudget>,
866    /// When the task was filed.
867    pub created_at: Timestamp,
868    /// Last change to this file.
869    pub updated_at: Timestamp,
870}
871
872/// Admission identity shared by start and settlement.
873#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
874pub struct RecoveryAdmission {
875    /// Fetched upstream commit before any run-local rebase.
876    pub base: String,
877    /// Resolved instruction references and explicit review source.
878    pub inputs: String,
879}
880
881#[derive(Debug, Clone, Serialize, Deserialize)]
882struct RecoveryBudgetHold {
883    admission: RecoveryAdmission,
884    run: String,
885    pass: usize,
886    held_at: Timestamp,
887    decision: Option<Timestamp>,
888    #[serde(default)]
889    legacy: bool,
890}
891
892/// Failures against one recovery input generation. An owner release explicitly
893/// starts a new generation; a machine requeue never replenishes it.
894#[derive(Debug, Clone, Serialize, Deserialize)]
895pub struct RecoveryBudget {
896    /// Authored instructions, not generated review scaffolding.
897    pub instruction: String,
898    /// Upstream commit used to prepare this generation.
899    pub base: String,
900    /// Referenced input commits, including their resolved identities.
901    pub inputs: String,
902    /// Stable processing stage of the last failure.
903    pub stage: String,
904    /// Failed passes, independent of the resettable claim counter.
905    pub failures: usize,
906    /// Fingerprint of actual candidate patches; equivalent rebased commits do
907    /// not count as progress. Unknown inputs never replenish the budget.
908    #[serde(default)]
909    pub progress: Option<String>,
910}
911
912impl RecoveryBudget {
913    fn budget_reason(&self) -> String {
914        format!(
915            "[recovery-budget] {} failed passes against unchanged inputs ({}). Inspect the retained recovery sources and correct the cause, change the inputs, or explicitly release the task to approve another generation. Automatic requeue does not reset this budget.",
916            self.failures, self.stage
917        )
918    }
919}
920
921fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
922    use crate::proc::Quiet as _;
923    use std::hash::{Hash, Hasher};
924    let mut patches = Vec::new();
925    for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
926        let output = std::process::Command::new("git")
927            .current_dir(&state.repo)
928            .args(["diff", "--binary", &state.base_commit, &candidate.branch])
929            .quiet()
930            .output()
931            .ok()?;
932        if !output.status.success() {
933            return None;
934        }
935        patches.push(output.stdout);
936    }
937    patches.sort();
938    patches.dedup();
939    let mut hash = std::collections::hash_map::DefaultHasher::new();
940    patches.hash(&mut hash);
941    Some(format!("{:x}", hash.finish()))
942}
943
944/// The implementation inputs a recovery budget is keyed on: the explicit,
945/// SHA-pinned sources only, never references parsed from instruction prose.
946/// No sources is `[]`, the key an input-free task always had.
947pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
948    serde_json::to_string(
949        &sources
950            .start_from
951            .iter()
952            .map(|i| ("start", &i.token, &i.sha))
953            .chain(
954                sources
955                    .pick_commits
956                    .iter()
957                    .map(|i| ("pick", &i.token, &i.sha)),
958            )
959            .collect::<Vec<_>>(),
960    )
961    .unwrap_or_default()
962}
963
964/// Facts a producer can independently attest about a held outcome.
965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
966pub struct NoticeCause {
967    /// Processing stage or verified external evidence.
968    pub stage: String,
969    /// Producer-verified blocker object, independent of the displayed error.
970    /// Omitted when absent to preserve existing persisted notice keys.
971    #[serde(default, skip_serializing_if = "Option::is_none")]
972    pub target: Option<String>,
973    /// An actual run that reached settlement; absent for preflight failures.
974    pub run: Option<String>,
975    /// The settled pass, so a resumed run can report a new failure.
976    pub pass: Option<usize>,
977}
978
979/// Current and legacy completion keys; legacy run counts contain only digits.
980pub(crate) fn is_done_notice_key(key: &str) -> bool {
981    key == "done"
982        || key
983            .strip_prefix("done#")
984            .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
985}
986
987/// What a settled pass did to the attempt budget.
988#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
989#[serde(rename_all = "snake_case")]
990pub enum PassCost {
991    /// The attempt stays counted.
992    Spent,
993    /// The attempt was handed back.
994    Refunded,
995}
996
997/// One settled pass over a run. See [`Task::passes`].
998#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
999pub struct TaskPass {
1000    /// The run the pass belongs to.
1001    pub run: String,
1002    /// [`crate::run::RunPass::index`] in that run.
1003    pub pass_index: usize,
1004    /// What it did to the budget.
1005    pub cost: PassCost,
1006    /// `attempts` once this pass was settled.
1007    pub attempts_after: usize,
1008    /// When this pass began, retained across daemon upgrades.
1009    #[serde(default)]
1010    pub started_at: Option<Timestamp>,
1011    /// When the loop settled it.
1012    pub settled_at: Timestamp,
1013    /// Why the pass parked, when it did.
1014    #[serde(default)]
1015    pub parked: Option<crate::run::ParkCause>,
1016}
1017
1018/// What became of a completion notice. See [`Task::chat_notice`].
1019#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1020#[serde(rename_all = "lowercase")]
1021pub enum ChatNoticeOutcome {
1022    /// Queued as a draft of the originating talk.
1023    Posted,
1024    /// The talk is gone or closed; nothing was queued, and nothing will be.
1025    Skipped,
1026}
1027
1028/// The final state of a chat-filed task that was already reported (or skipped).
1029#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1030pub struct ChatNotice {
1031    /// Identity of the cause, see [`Task::chat_notice_key`].
1032    pub key: String,
1033    /// When it was recorded.
1034    pub at: Timestamp,
1035    /// Posted or skipped.
1036    pub outcome: ChatNoticeOutcome,
1037}
1038
1039/// Command-line choices carried by a task. See [`Task::overrides`].
1040#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1041pub struct RunOverrides {
1042    /// Count edits on ordinary queued tasks inherit the loop's config and merge.
1043    /// False for direct-run overrides and old records, even when otherwise empty.
1044    #[serde(default)]
1045    pub inherit_daemon_options: bool,
1046    /// `--merge`: `none`, `local` or `pr`.
1047    #[serde(default)]
1048    pub merge: Option<String>,
1049    /// `-c` / `--implementers`: parallel implementations (persisted as `candidates`).
1050    #[serde(default)]
1051    pub candidates: Option<usize>,
1052    /// `-j`: independent judges.
1053    #[serde(default)]
1054    pub judges: Option<usize>,
1055    /// `--reviewers`: reviewers per round.
1056    #[serde(default)]
1057    pub reviewers: Option<usize>,
1058    /// `--review-rounds`.
1059    #[serde(default)]
1060    pub review_rounds: Option<usize>,
1061    /// `--seed`.
1062    #[serde(default)]
1063    pub seed: Option<u64>,
1064    /// `--config`, absolute: the daemon's own working directory differs.
1065    #[serde(default)]
1066    pub config: Option<PathBuf>,
1067    /// `--build-cache`; unset inherits the repository's policy on new tasks.
1068    #[serde(default, skip_serializing_if = "Option::is_none")]
1069    pub build_cache: Option<BuildCache>,
1070}
1071
1072impl RunOverrides {
1073    /// Lay `other` over these: every choice `other` made wins, the rest stay.
1074    pub fn merge_over(&mut self, other: &RunOverrides) {
1075        macro_rules! take {
1076            ($($f:ident),*) => {$(
1077                if other.$f.is_some() {
1078                    self.$f.clone_from(&other.$f);
1079                }
1080            )*};
1081        }
1082        take!(
1083            merge,
1084            candidates,
1085            judges,
1086            reviewers,
1087            review_rounds,
1088            seed,
1089            config,
1090            build_cache
1091        );
1092    }
1093
1094    /// Apply these on top of `config`.
1095    pub fn apply(&self, config: &mut crate::config::Config) {
1096        if let Some(n) = self.candidates {
1097            config.graph.implementers = n;
1098        }
1099        if let Some(n) = self.judges {
1100            config.graph.judges = n;
1101        }
1102        if let Some(n) = self.reviewers {
1103            config.graph.reviewers = n;
1104        }
1105        if let Some(n) = self.review_rounds {
1106            config.graph.review_rounds = n;
1107        }
1108        if let Some(m) = &self.merge
1109            && let Ok(mode) = crate::daemon::merge_mode(m)
1110        {
1111            config.merge.mode = mode;
1112        }
1113        if let Some(s) = self.seed {
1114            config.blind.seed = Some(s);
1115        }
1116        if let Some(mode) = self.build_cache {
1117            config.verify.build_cache = mode;
1118        }
1119    }
1120}
1121
1122/// What a follow-up task came from. See [`Task::followup`].
1123#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1124pub struct FollowUp {
1125    /// The merged run whose open findings this task carries.
1126    pub run: String,
1127    /// The queue task that run served, when it had one.
1128    #[serde(default)]
1129    pub origin_task: Option<String>,
1130    /// The merged pull request.
1131    pub pr: String,
1132    /// Ids of the findings (e.g. `R3-1-1`) this task covers.
1133    pub findings: Vec<String>,
1134    /// Follow-up depth: 1 for a follow-up of an ordinary task's run, 2 for a
1135    /// follow-up of that, and so on. An ordinary task is generation 0.
1136    pub generation: u32,
1137}
1138
1139/// Durable scope of an explicit operator resumption, surviving run startup.
1140#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1141pub struct Resumption {
1142    /// Monotonic count of explicit resumptions.
1143    pub generation: u64,
1144    /// Mutation path that applied the approval.
1145    pub source: String,
1146    /// Answered question, if the approval came from one.
1147    pub question_id: Option<String>,
1148    /// When this approval was applied.
1149    pub at: Timestamp,
1150    /// Authored instruction approved at release.
1151    pub instruction: String,
1152    /// Number of historical answers superseded as waiting premises.
1153    pub answers_through: usize,
1154    /// Legacy run-list boundary retained for record compatibility. Evidence
1155    /// uses approval time and run passes because resumes retain the same id.
1156    pub runs_through: usize,
1157    /// Previous hold or dependency reason cleared by this release.
1158    pub cleared_reason: Option<String>,
1159    /// Verified evidence versions already used to block after this approval.
1160    #[serde(default)]
1161    pub blocking_evidence: Vec<String>,
1162}
1163
1164/// A triage "resume" answer and what became of it. See
1165/// [`Task::resume_override`].
1166#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1167pub struct OperatorResume {
1168    /// 回答された Question の ID。Question を伴わない再開では空文字列。
1169    pub question_id: String,
1170    /// When the answer was applied.
1171    pub at: Timestamp,
1172    /// The reason `crate::conduct` gave for holding the task again after the
1173    /// answer, if it did. The conductor may do this once.
1174    #[serde(default)]
1175    pub conductor_rehold: Option<String>,
1176    /// The operator answered "resume" a second time, to the question about
1177    /// that contradiction: the conductor may no longer hold this task.
1178    #[serde(default)]
1179    pub forced: bool,
1180    /// Set when the answer was a structured `resume` action on a `magi ask`
1181    /// choice ([`crate::ask::ChoiceAction::Resume`]): the run the operator
1182    /// chose to continue. Its presence also stops `crate::conduct` from
1183    /// requeuing the task into a fresh competition, which would discard
1184    /// exactly the run that was named. Cleared with the rest of the record
1185    /// once the task runs. `#[serde(default)]` so older records read as `None`.
1186    #[serde(default)]
1187    pub pinned_run: Option<String>,
1188}
1189
1190/// One question `crate::conduct` asked about a task, and what the operator
1191/// said back. See [`Task::answers`].
1192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1193pub struct AnsweredQuestion {
1194    /// The question as asked, e.g. [`crate::ask::Question::summary`].
1195    pub question: String,
1196    /// What the operator answered.
1197    pub answer: String,
1198}
1199
1200fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1201    for entry in entries {
1202        if !ledger.contains(&entry) {
1203            ledger.push(entry);
1204        }
1205    }
1206}
1207
1208fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1209    older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1210    if !older.is_empty() {
1211        older.append(ledger);
1212        *ledger = older;
1213    }
1214}
1215
1216impl Task {
1217    /// File a new task. Persist it with [`Queue::put`].
1218    pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1219        let now = Timestamp::now();
1220        let origin_chat = match &source {
1221            Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1222            _ => None,
1223        };
1224        Self {
1225            schema: SCHEMA,
1226            id: new_id(),
1227            title,
1228            instruction,
1229            sources: crate::refs::Sources::default(),
1230            repo,
1231            reassignments: Vec::new(),
1232            source,
1233            chat: None,
1234            priority: 0,
1235            solo: false,
1236            status: TaskStatus::Queued,
1237            completion_history: Vec::new(),
1238            attempts: 0,
1239            attempt_limit: None,
1240            runs: Vec::new(),
1241            startup_failures: Vec::new(),
1242            last_error: None,
1243            hold_reason: None,
1244            hold_source: None,
1245            recovery_budget_hold: None,
1246            machine_hold_cause: None,
1247            disk_resume_run: None,
1248            disk_checked_at: None,
1249            diagnostic: None,
1250            blocked_by: Vec::new(),
1251            block_reason: None,
1252            blocked_from: None,
1253            blocked_at: None,
1254            answers: Vec::new(),
1255            triage_applied: Vec::new(),
1256            actions_applied: Vec::new(),
1257            decision_effects: Default::default(),
1258            superseded_resumes: Default::default(),
1259            dispatched_resumes: Default::default(),
1260            base_recovery_requests: Vec::new(),
1261            resume_override: None,
1262            sync_only: None,
1263            repair_grants: Vec::new(),
1264            repair_reconciliations: Vec::new(),
1265            resumption: None,
1266            resumption_history: Vec::new(),
1267            operator_decided_at: None,
1268            review_branch: None,
1269            review_instruction: None,
1270            pr_recovery: None,
1271            fresh_start: false,
1272            replacement: None,
1273            interrupt: false,
1274            urgent: false,
1275            unfiled: true,
1276            attachments: Vec::new(),
1277            followup: None,
1278            origin_chat,
1279            overrides: None,
1280            review_of: None,
1281            held_at: None,
1282            park_reason: None,
1283            chat_notice: None,
1284            chat_notices: Vec::new(),
1285            hold_notice_cause: None,
1286            passes: Vec::new(),
1287            dispatched_at: None,
1288            recovery_budget: None,
1289            recovery_admission: None,
1290            recovery_generations: Vec::new(),
1291            created_at: now,
1292            updated_at: now,
1293        }
1294    }
1295
1296    /// Apply a validated idle-task assignment, preserving evidence and history.
1297    pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1298        self.stamp_schema();
1299        if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1300            self.hold_manual(Some(
1301                "Repository reassigned; inspect history and release to start fresh.".into(),
1302            ));
1303        }
1304        let at = Timestamp::now();
1305        self.reassignments.push(Reassignment {
1306            from: self.repo.clone(),
1307            to: repo.clone(),
1308            actor: actor.to_owned(),
1309            at,
1310            run_boundary: self.runs.len(),
1311        });
1312        self.repo = repo;
1313        self.review_branch = None;
1314        self.review_instruction = None;
1315        self.pr_recovery = None;
1316        self.replacement = None;
1317        self.interrupt = false;
1318        self.resume_override = None;
1319        self.fresh_start = true;
1320        self.operator_decided_at = Some(at);
1321    }
1322
1323    /// Public branch for the task's current repository assignment.
1324    pub fn publication_branch(&self) -> String {
1325        crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1326    }
1327
1328    /// Runs eligible for execution in the current assignment only.
1329    pub fn execution_runs(&self) -> &[String] {
1330        let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1331        self.runs.get(boundary..).unwrap_or_default()
1332    }
1333
1334    /// Whether a historical run still belongs to this execution assignment.
1335    pub fn execution_run(&self, run: &str) -> bool {
1336        self.execution_runs().iter().any(|id| id == run)
1337    }
1338
1339    /// Check both the assignment boundary and the saved repository before execution.
1340    pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1341        self.reassignments.last().is_none_or(|boundary| {
1342            self.execution_run(&run.id)
1343                && run.task_assignment == self.reassignments.len()
1344                && run.created_at > boundary.at
1345                && run
1346                    .repo
1347                    .canonicalize()
1348                    .ok()
1349                    .zip(self.repo.canonicalize().ok())
1350                    .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1351        })
1352    }
1353
1354    /// Questions issued before reassignment cannot control the new assignment.
1355    pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1356        self.reassignments
1357            .last()
1358            .is_some_and(|r| q.asked_at <= r.at)
1359            || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1360    }
1361
1362    /// The chat this task itself says it came from, including its original source.
1363    pub fn chat_talk(&self) -> Option<&str> {
1364        if let Some(id) = &self.origin_chat {
1365            return Some(id);
1366        }
1367        match &self.source {
1368            Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1369            _ => None,
1370        }
1371    }
1372
1373    /// The talk that filed this task *itself* (`Source::Agent` with
1374    /// [`CHAT_NODE`]); unlike [`Task::chat_talk`] a follow-up's inherited
1375    /// `origin_chat` does not count.
1376    pub fn filed_by_chat(&self) -> Option<&str> {
1377        match &self.source {
1378            Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1379            _ => None,
1380        }
1381    }
1382
1383    /// Identity of a material outcome. Prose and wall-clock times are never
1384    /// evidence. Dependencies are a set; held causes survive intermediate states.
1385    pub fn chat_notice_key(&self) -> Option<String> {
1386        match self.status {
1387            TaskStatus::Done => Some(
1388                self.completion_history
1389                    .iter()
1390                    .rev()
1391                    .find(|event| event.action == CompletionAction::Complete)
1392                    .map_or_else(
1393                        || "done".to_owned(),
1394                        |event| format!("done:{}", event.occurrence),
1395                    ),
1396            ),
1397            TaskStatus::Held => {
1398                let cause = self
1399                    .hold_notice_cause
1400                    .clone()
1401                    .unwrap_or_else(|| self.unresolved_hold_cause());
1402                Some(format!(
1403                    "cause:{}",
1404                    serde_json::to_string(&cause).expect("cause")
1405                ))
1406            }
1407            TaskStatus::Blocked => {
1408                let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1409                // Only new verified blocking evidence versions the dependency
1410                // set. Freezing an unrelated hold on release must not do so.
1411                let evidence = self
1412                    .hold_notice_cause
1413                    .as_ref()
1414                    .filter(|c| c.stage.starts_with("conductor-evidence:"));
1415                Some(format!(
1416                    "dependencies:{}",
1417                    serde_json::to_string(&(ids, evidence)).expect("ids")
1418                ))
1419            }
1420            _ => None,
1421        }
1422    }
1423
1424    fn unresolved_hold_cause(&self) -> NoticeCause {
1425        NoticeCause {
1426            stage: "hold".into(),
1427            target: None,
1428            run: self.runs.last().cloned(),
1429            pass: None,
1430        }
1431    }
1432
1433    /// Exact old delivery identity, only for reconciling an existing record.
1434    pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1435        let key = match self.status {
1436            TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1437                "held#{}",
1438                self.held_at.map(|t| t.to_string()).unwrap_or_default()
1439            )),
1440            TaskStatus::Blocked => Some(format!(
1441                "blocked#{}#{}",
1442                self.blocked_by.join(","),
1443                self.block_reason.as_deref().unwrap_or_default()
1444            )),
1445            _ => None,
1446        };
1447        key.filter(|key| self.legacy_notice_matches(key))
1448    }
1449
1450    pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1451        match self.status {
1452            TaskStatus::Held if self.hold_notice_cause.is_none() => key
1453                .strip_prefix("held#")
1454                .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1455            TaskStatus::Blocked
1456                if self
1457                    .hold_notice_cause
1458                    .as_ref()
1459                    .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1460            {
1461                key.strip_prefix("blocked#").is_some_and(|tail| {
1462                    let Some((ids, _)) = tail.split_once('#') else {
1463                        return false;
1464                    };
1465                    let old: std::collections::BTreeSet<_> =
1466                        ids.split(',').filter(|id| !id.is_empty()).collect();
1467                    let current: std::collections::BTreeSet<_> =
1468                        self.blocked_by.iter().map(String::as_str).collect();
1469                    old == current
1470                })
1471            }
1472            _ => false,
1473        }
1474    }
1475
1476    fn import_chat_notice(&mut self) {
1477        if let Some(n) = &self.chat_notice {
1478            let key = if is_done_notice_key(&n.key) {
1479                "done".to_owned()
1480            } else if self.legacy_notice_matches(&n.key) {
1481                self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1482            } else {
1483                n.key.clone()
1484            };
1485            if !self.chat_notices.contains(&key) {
1486                self.chat_notices.push(key);
1487            }
1488        }
1489    }
1490
1491    /// A producer records the processing stage and actual run/pass, never the
1492    /// error's rendered prose. No run means startup made no implementation progress.
1493    pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1494        self.import_chat_notice();
1495        self.hold_notice_cause = Some(NoticeCause {
1496            stage: stage.to_owned(),
1497            target: None,
1498            run: run.map(str::to_owned),
1499            pass,
1500        });
1501    }
1502
1503    /// Startup retries cannot replace an unresolved run outcome without doing
1504    /// work. Distinct startup stages can still explain a newly encountered blocker.
1505    pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1506        let recovery_only = matches!(
1507            stage,
1508            "startup-source" | "startup-candidates" | "startup-public-head"
1509        );
1510        match self.hold_notice_cause.as_ref() {
1511            Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1512            None if recovery_only
1513                && self
1514                    .chat_notice
1515                    .as_ref()
1516                    .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1517            {
1518                return;
1519            }
1520            _ => {}
1521        }
1522        self.notice_cause(stage, None, None);
1523    }
1524
1525    /// Apply a preflight failure without allowing Running's generic failure
1526    /// identity to overwrite the producer's stage or its unresolved recovery anchor.
1527    pub(crate) fn fail_startup(
1528        &mut self,
1529        stage: &str,
1530        why: impl Into<String>,
1531        max_attempts: usize,
1532    ) {
1533        let unresolved = self.hold_notice_cause.clone();
1534        self.fail(why, max_attempts);
1535        self.hold_notice_cause = unresolved;
1536        self.startup_notice_cause(stage);
1537    }
1538
1539    /// A startup failure tied to a concrete object, such as a missing attachment.
1540    pub(crate) fn fail_startup_target(
1541        &mut self,
1542        stage: &str,
1543        target: String,
1544        why: impl Into<String>,
1545        max_attempts: usize,
1546    ) {
1547        self.fail_startup(stage, why, max_attempts);
1548        if let Some(cause) = self.hold_notice_cause.as_mut() {
1549            cause.target = Some(target);
1550        }
1551    }
1552
1553    /// A chat-filed task owes each material final outcome at most one notice.
1554    pub fn chat_notice_due(&self) -> Option<String> {
1555        self.filed_by_chat()?;
1556        if self.schema < 13 {
1557            return None;
1558        }
1559        let key = self.chat_notice_key()?;
1560        if self.chat_notices.contains(&key) {
1561            return None;
1562        }
1563        match &self.chat_notice {
1564            Some(n)
1565                if n.key == key
1566                    || (key == "done" && is_done_notice_key(&n.key))
1567                    || self.legacy_notice_matches(&n.key) =>
1568            {
1569                None
1570            }
1571            _ => Some(key),
1572        }
1573    }
1574
1575    /// Short form used in reports, matching a run's short id.
1576    pub fn short(&self) -> &str {
1577        short(&self.id)
1578    }
1579
1580    /// Record that triage question `question_id`'s answer has been applied.
1581    pub fn mark_triage_applied(&mut self, question_id: &str) {
1582        if !self.triage_applied(question_id) {
1583            self.triage_applied.push(question_id.to_owned());
1584        }
1585    }
1586
1587    /// Has the action of `magi ask` question `question_id` already been
1588    /// applied, or is it being applied now? See [`Task::actions_applied`].
1589    pub fn action_applied(&self, question_id: &str) -> bool {
1590        self.actions_applied.iter().any(|id| id == question_id)
1591    }
1592
1593    /// Record that `magi ask` question `question_id`'s action was applied.
1594    pub fn mark_action_applied(&mut self, question_id: &str) {
1595        if !self.action_applied(question_id) {
1596            self.actions_applied.push(question_id.to_owned());
1597        }
1598    }
1599
1600    /// Has triage question `question_id`'s answer already been applied?
1601    pub fn triage_applied(&self, question_id: &str) -> bool {
1602        self.triage_applied.iter().any(|id| id == question_id)
1603    }
1604
1605    /// Record that a run has started for this task.
1606    /// Move an already linked run to the end so it remains the current attempt,
1607    /// with one history entry per run and separate pass records for each resume.
1608    ///
1609    /// Clears [`Task::interrupt`]: a mark to run ahead of whatever else is
1610    /// in flight is fulfilled the moment this task actually gets its turn,
1611    /// dispatched same as any other. Without this, a task whose run fails
1612    /// and requeues - still `runnable`, still carrying the mark from its
1613    /// first attempt - would keep re-triggering `crate::daemon`'s interrupt
1614    /// scheduler and re-parking whatever it interrupted on every later
1615    /// boundary, for as long as its attempts hold out, instead of the
1616    /// one-shot "let this go next" the mark is meant to be.
1617    pub fn start(&mut self, run: String) {
1618        self.stamp_schema();
1619        self.status = TaskStatus::Running;
1620        self.attempts += 1;
1621        self.runs.retain(|id| id != &run);
1622        if let Some(pin) = &self.resume_override
1623            && pin.pinned_run.as_ref() == Some(&run)
1624            && !pin.question_id.is_empty()
1625        {
1626            self.dispatched_resumes
1627                .insert(pin.question_id.clone(), run.clone());
1628        }
1629        self.runs.push(run);
1630        self.last_error = None;
1631        self.park_reason = None;
1632        self.fresh_start = false;
1633        self.interrupt = false;
1634        // The answer has been honoured: the task got its turn.
1635        self.resume_override = None;
1636        // The automatic disk recovery pin is consumed by this start; a later
1637        // failure and requeue must retry normally.
1638        self.disk_resume_run = None;
1639    }
1640
1641    /// Attribute a failed reservation once without spending an execution attempt.
1642    pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1643        if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1644            self.startup_failures.push(failure);
1645        }
1646    }
1647
1648    /// Note that `run` serves this task without otherwise changing its life:
1649    /// no status, attempt or interrupt change, unlike [`Task::start`]. For a
1650    /// run somebody else started on the task's behalf (`magi run --task`);
1651    /// idempotent. Returns whether anything was added.
1652    pub fn link_run(&mut self, run: &str) -> bool {
1653        if self.runs.iter().any(|r| r == run) {
1654            return false;
1655        }
1656        self.runs.push(run.to_owned());
1657        true
1658    }
1659
1660    /// Record a successful run.
1661    ///
1662    /// Both `magi task done` and `POST /api/queue/{id}/done` can close a held
1663    /// *or blocked* task directly, with no release in between, so this clears
1664    /// `hold_reason` and `blocked_by`/`block_reason` the same way
1665    /// [`Task::release`] does. Otherwise a task held for "waiting on 3ed9", or
1666    /// blocked on a dependency that never actually finished, and then closed
1667    /// as done without ever being released would still read as waiting on
1668    /// something in `magi task show` and on its card, after it no longer is.
1669    pub fn succeed(&mut self, context: CompletionContext) {
1670        if self.status == TaskStatus::Done {
1671            return;
1672        }
1673        self.record_completion(CompletionAction::Complete, context);
1674        self.stamp_schema();
1675        self.status = TaskStatus::Done;
1676        if let Some(pin) = self.resume_override.take()
1677            && !pin.question_id.is_empty()
1678            && let Some(run) = pin.pinned_run
1679        {
1680            // Completion cancels a queued request; normal dispatch records its
1681            // start separately and must not be mistaken for supersession.
1682            self.superseded_resumes.insert(pin.question_id, run);
1683        }
1684        self.sync_only = None;
1685        self.last_error = None;
1686        self.park_reason = None;
1687        self.hold_reason = None;
1688        self.hold_source = None;
1689        self.machine_hold_cause = None;
1690        self.disk_resume_run = None;
1691        self.disk_checked_at = None;
1692        self.diagnostic = None;
1693        self.blocked_by.clear();
1694        self.block_reason = None;
1695        self.blocked_from = None;
1696    }
1697
1698    /// Finish the task because the run's whole change turned out to be on the
1699    /// base already ([`crate::run::RunStatus::AlreadyInBase`]): `Done`, with
1700    /// `note` kept in [`Task::last_error`] so `magi task show` says why, and
1701    /// the attempt refunded. Nothing went wrong and nothing was spent
1702    /// misbehaving, so this is neither [`Task::fail`] nor
1703    /// [`Task::handed_off`]; and unlike [`Task::succeed`] it does not pretend
1704    /// the run landed anything.
1705    pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1706        let note = note.into();
1707        if context.reason.is_none() {
1708            context.reason = Some(note.clone());
1709        }
1710        self.succeed(context);
1711        self.attempts = self.attempts.saturating_sub(1);
1712        self.last_error = Some(note);
1713    }
1714
1715    fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1716        self.completion_history.push(CompletionEvent {
1717            occurrence: format!(
1718                "{}-{:016x}{:016x}",
1719                Timestamp::now(),
1720                crate::rng::entropy(),
1721                crate::rng::entropy()
1722            ),
1723            action,
1724            actor: context.actor,
1725            reason: context.reason,
1726            discard: context.discard,
1727            prior_status: self.status,
1728            at: Timestamp::now(),
1729            prior_hold_reason: self.hold_reason.clone(),
1730            prior_block_reason: self.block_reason.clone(),
1731            prior_error: self.last_error.clone(),
1732            run: context.run,
1733            unavailable_runs: context.unavailable_runs,
1734        });
1735        self.stamp_schema();
1736    }
1737
1738    /// Reopen a completed task into a hold after transactional admission.
1739    /// Release remains a separate operator decision.
1740    pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1741        anyhow::ensure!(
1742            self.status == TaskStatus::Done,
1743            "only a done task can be reopened"
1744        );
1745        anyhow::ensure!(
1746            context
1747                .reason
1748                .as_deref()
1749                .is_some_and(|reason| !reason.trim().is_empty()),
1750            "reopen requires a non-empty reason"
1751        );
1752        let reason = context.reason.clone();
1753        self.record_completion(CompletionAction::Reopen, context);
1754        self.hold_manual(reason);
1755        self.resume_override = None;
1756        self.fresh_start = false;
1757        self.last_error = None;
1758        self.diagnostic = None;
1759        Ok(())
1760    }
1761
1762    /// Earlier attempts at this task that a later one has since made moot —
1763    /// empty unless the task is [`TaskStatus::Done`] *and* `last_run_succeeded`
1764    /// says `runs.last()` is actually why.
1765    ///
1766    /// `runs` is oldest first, and [`Task::start`] is the only thing that
1767    /// pushes to it, always right before the attempt it names either succeeds
1768    /// or fails; `succeed` itself never touches `runs`. So whenever `status`
1769    /// is `Done` *because* the loop itself saw that last attempt land
1770    /// (`Merged`/`Ready`), everything before it in the same list is a retry
1771    /// this task no longer needs. But `succeed` is also reachable directly —
1772    /// `magi task done`, the web UI's equivalent, and the conductor's
1773    /// `Recovery::Done` all call it on a task in *any* status, including one
1774    /// whose last recorded attempt never landed at all (closed by hand after
1775    /// a merge magi's own loop never saw). `runs.last()` alone cannot tell
1776    /// those two cases apart — that requires the caller to have actually
1777    /// looked at that run's own `status`, which this module has no way to
1778    /// do — so `last_run_succeeded` is the caller's answer to exactly that
1779    /// question, not something this function can derive from `Task` alone.
1780    ///
1781    /// Deliberately narrower than [`Queue::superseded`]'s "every earlier
1782    /// attempt has a later one" walk, which fires the moment a retry starts
1783    /// even though the retry itself might still fail: that reading is right
1784    /// for the web UI's "a newer attempt exists, go look at that one
1785    /// instead" note, but wrong for deciding a run no longer needs a human's
1786    /// attention, which is only true once the task's story has actually
1787    /// ended well. Two Blocked runs sitting side by side while a third
1788    /// attempt is still in flight must not be touched by this — see
1789    /// `daemon::supersede_prior_runs`, the caller that turns this list into
1790    /// rewritten `run.json` files.
1791    pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1792        if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1793        {
1794            return &[];
1795        }
1796        &self.execution_runs()[..self.execution_runs().len() - 1]
1797    }
1798
1799    /// The attempt right after the last occurrence of `run`, if there is one.
1800    /// Resuming records the same run again; it cannot supersede itself.
1801    ///
1802    /// The one place "a later attempt replaced this run" is decided:
1803    /// [`Queue::superseded`] and [`Queue::superseded_by`] (the web UI's
1804    /// note) read it, and so does [`Task::earlier_attempts`], so what is shown
1805    /// and what `crate::handover` acts on cannot disagree.
1806    pub fn successor_of(&self, run: &str) -> Option<&String> {
1807        let runs = self.execution_runs();
1808        let pos = runs.iter().rposition(|r| r == run)?;
1809        runs.get(pos + 1)
1810    }
1811
1812    /// Every run in this assignment, i.e. every run that an
1813    /// attempt being minted *right now* supersedes.
1814    ///
1815    /// The new run is not in [`Task::runs`] yet when it decides what to take
1816    /// over (`Task::start` pushes it afterwards), so "has a later attempt" is
1817    /// true of everything listed here by the time the new run exists.
1818    pub fn earlier_attempts(&self) -> &[String] {
1819        self.execution_runs()
1820    }
1821
1822    fn preserve_legacy_build_cache(&mut self) {
1823        if self.schema < 23 {
1824            let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1825                inherit_daemon_options: true,
1826                ..RunOverrides::default()
1827            });
1828            overrides.build_cache.get_or_insert(BuildCache::Shared);
1829        }
1830    }
1831
1832    /// A transition this build makes (start, hold, block, done) makes the task
1833    /// eligible for a chat notice even when it was filed under an older
1834    /// schema; only records no build has touched since stay silent
1835    /// ([`Task::chat_notice_due`]).
1836    fn stamp_schema(&mut self) {
1837        self.preserve_legacy_build_cache();
1838        if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1839            self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1840        }
1841        self.schema = self.schema.max(SCHEMA);
1842    }
1843
1844    /// Stamp [`Task::held_at`] on the way into [`TaskStatus::Held`]; a task
1845    /// that is already held keeps the time its hold began.
1846    fn note_held(&mut self) {
1847        self.stamp_schema();
1848        self.recovery_budget_hold = None;
1849        let continuing = self.status == TaskStatus::Held
1850            || (self.status == TaskStatus::Blocked
1851                && (self.blocked_from == Some(TaskStatus::Held)
1852                    || (self.blocked_from.is_none()
1853                        && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1854        if !continuing || self.held_at.is_none() {
1855            self.held_at = Some(Timestamp::now());
1856        }
1857    }
1858
1859    /// Record a failed attempt. Out of attempts means held for a human, rather
1860    /// than retried until the money runs out.
1861    ///
1862    /// Clears [`Task::diagnostic`] unconditionally: it belongs to whatever run
1863    /// produced it, and a caller that has one for *this* attempt sets it
1864    /// itself right after calling this, once it knows the task actually ended
1865    /// up [`TaskStatus::Held`] - see `daemon::diagnostic`. Without the clear, a
1866    /// task released after a diagnosed hold and then failed again for an
1867    /// unrelated, undiagnosed reason (a config error, say) would go on
1868    /// showing the previous run's diagnostic as if it explained the new one.
1869    ///
1870    /// Also records `why` into [`Task::hold_reason`] when this ends up
1871    /// [`TaskStatus::Held`], so the notification and `magi task show` say the
1872    /// same thing as [`Task::last_error`] instead of leaving the hold's own
1873    /// reason blank.
1874    pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1875        let why = why.into();
1876        if self.status == TaskStatus::Running {
1877            let run = self.runs.last().cloned();
1878            self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1879        }
1880        self.diagnostic = None;
1881        self.park_reason = None;
1882        self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1883            self.note_held();
1884            self.hold_source = Some(HoldSource::Machine);
1885            self.machine_hold_cause = None;
1886            self.disk_resume_run = None;
1887            self.disk_checked_at = None;
1888            self.hold_reason = Some(why.clone());
1889            TaskStatus::Held
1890        } else {
1891            TaskStatus::Failed
1892        };
1893        self.last_error = Some(why);
1894    }
1895
1896    /// Record an attempt that failed for a reason the task is not responsible
1897    /// for - the agent CLIs ran out of quota and the judging panel collapsed.
1898    ///
1899    /// This refunds the attempt on purpose. A quota window closing at 4am must
1900    /// not spend the backlog's retry budget: the operator would come back to a
1901    /// queue of held tasks that were never actually judged, and would have to
1902    /// release every one by hand to find out which had a real problem. The task
1903    /// goes back to `Failed`, which the loop retries, so a reset quota picks the
1904    /// work up where it stopped.
1905    pub fn stall(&mut self, why: impl Into<String>) {
1906        self.last_error = Some(why.into());
1907        self.diagnostic = None;
1908        self.attempts = self.attempts.saturating_sub(1);
1909        self.status = TaskStatus::Failed;
1910    }
1911
1912    /// Record a run that parked at a node boundary. Nothing failed: the attempt
1913    /// is refunded, [`Task::last_error`] is left as it was, the run history and
1914    /// `fresh_start` are kept so the next loop resumes the same run, and the
1915    /// reason goes to [`Task::park_reason`]. Runnable like a requeued task and
1916    /// never counted against `max_attempts`.
1917    pub fn park(&mut self, why: impl Into<String>) {
1918        self.diagnostic = None;
1919        self.attempts = self.attempts.saturating_sub(1);
1920        self.status = TaskStatus::Parked;
1921        self.park_reason = Some(why.into());
1922        // The variant and field are schema 11; stamp it so an older build
1923        // refuses the record instead of half-reading it.
1924        self.stamp_schema();
1925    }
1926
1927    /// Record a settled pass whose start time is unknown (see [`Self::record_pass_at`]).
1928    pub fn record_pass(
1929        &mut self,
1930        run: &str,
1931        pass_index: usize,
1932        attempts_before: usize,
1933        parked: Option<crate::run::ParkCause>,
1934    ) {
1935        self.record_pass_at(run, pass_index, None, attempts_before, parked);
1936    }
1937
1938    /// Record a settled pass. `attempts_before` is the count just before the
1939    /// settle, so a refund is read off what actually changed, not inferred.
1940    pub fn record_pass_at(
1941        &mut self,
1942        run: &str,
1943        pass_index: usize,
1944        started_at: Option<Timestamp>,
1945        attempts_before: usize,
1946        parked: Option<crate::run::ParkCause>,
1947    ) {
1948        if self
1949            .passes
1950            .iter()
1951            .any(|p| p.run == run && p.pass_index == pass_index)
1952        {
1953            return;
1954        }
1955        let cost = if self.attempts < attempts_before {
1956            PassCost::Refunded
1957        } else {
1958            PassCost::Spent
1959        };
1960        self.passes.push(TaskPass {
1961            run: run.to_owned(),
1962            pass_index,
1963            started_at: self.dispatched_at.or(started_at),
1964            cost,
1965            attempts_after: self.attempts,
1966            settled_at: Timestamp::now(),
1967            parked,
1968        });
1969        self.stamp_schema();
1970    }
1971
1972    /// Only the latest pass of the current, resumable upgrade-parked run
1973    /// retains its place. Explicit fresh starts and other park causes do not.
1974    pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
1975        if self.status != TaskStatus::Parked || self.fresh_start {
1976            return None;
1977        }
1978        let pass = self.passes.last()?;
1979        if self.execution_runs().last() != Some(&pass.run)
1980            || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
1981        {
1982            return None;
1983        }
1984        // Before schema 19 the dispatch start was not copied to the task.
1985        // Settlement time is only an approximation for those old records.
1986        Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
1987    }
1988
1989    /// Whether this held task may only be released by an operator.
1990    ///
1991    /// Old files did not record a source. Preserve every such hold rather
1992    /// than guessing that it was automatic and risking duplicate work. New
1993    /// automatic holds record [`HoldSource::Machine`] and remain recoverable.
1994    pub fn operator_held(&self) -> bool {
1995        self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
1996    }
1997
1998    /// Take this task out of the loop's reach by an operator action.
1999    ///
2000    /// Clears `blocked_by`/`block_reason` unconditionally, the same as
2001    /// [`Task::release`] and for the same reason its own comment already
2002    /// gives: a human choosing to hold a *blocked* task overrides its wait
2003    /// outright, the same as it overrides an ordinary hold. Without this, a
2004    /// task held straight out of [`TaskStatus::Blocked`] - the web UI's "Hold"
2005    /// button is reachable on a blocked task, same as "Mark done" - kept
2006    /// reading as still waiting on a dependency it no longer had any claim on.
2007    pub fn hold_manual(&mut self, reason: Option<String>) {
2008        // A later explicit hold supersedes outstanding triage answers.
2009        self.operator_decided_at = Some(Timestamp::now());
2010        if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2011            self.resume_override = None;
2012        }
2013        self.hold_unrequested_retry(reason);
2014    }
2015
2016    /// Keep a hand-started run from retrying automatically, without recording
2017    /// an operator decision that could invalidate its outstanding questions.
2018    pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2019        self.park_reason = None;
2020        self.note_held();
2021        self.status = TaskStatus::Held;
2022        if reason.is_some() {
2023            self.hold_reason = reason;
2024        }
2025        self.hold_source = Some(HoldSource::Manual);
2026        self.machine_hold_cause = None;
2027        self.disk_resume_run = None;
2028        self.disk_checked_at = None;
2029        self.blocked_by.clear();
2030        self.block_reason = None;
2031        self.blocked_from = None;
2032    }
2033
2034    pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2035        let recovery_hold = self.recovery_budget_hold.take();
2036        self.hold_unrequested_retry(Some(reason));
2037        self.recovery_budget_hold = recovery_hold;
2038    }
2039
2040    /// Take this task out of the loop's reach during automatic recovery.
2041    ///
2042    /// Clears `blocked_by`/`block_reason` for the same reason
2043    /// [`Task::hold_manual`] does.
2044    pub fn hold_machine(&mut self, reason: Option<String>) {
2045        self.park_reason = None;
2046        self.note_held();
2047        self.status = TaskStatus::Held;
2048        if reason.is_some() {
2049            self.hold_reason = reason;
2050        }
2051        self.hold_source = Some(HoldSource::Machine);
2052        self.machine_hold_cause = None;
2053        self.disk_resume_run = None;
2054        self.disk_checked_at = None;
2055        self.blocked_by.clear();
2056        self.block_reason = None;
2057        self.blocked_from = None;
2058    }
2059
2060    /// Record the disk-capacity cause bound to the current `hold_reason`.
2061    pub(crate) fn mark_disk_capacity(&mut self) {
2062        self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2063            reason: self.hold_reason.clone().unwrap_or_default(),
2064            before_start: false,
2065        });
2066    }
2067
2068    pub(crate) fn mark_startup_disk_capacity(&mut self) {
2069        self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2070            reason: self.hold_reason.clone().unwrap_or_default(),
2071            before_start: true,
2072        });
2073    }
2074
2075    pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2076        if self.has_disk_capacity_cause()
2077            && matches!(
2078                self.machine_hold_cause,
2079                Some(MachineHoldCause::DiskCapacity {
2080                    before_start: true,
2081                    ..
2082                })
2083            )
2084        {
2085            None
2086        } else {
2087            self.execution_runs().last()
2088        }
2089    }
2090
2091    /// Does the structured disk-capacity cause still match the current hold?
2092    pub fn has_disk_capacity_cause(&self) -> bool {
2093        matches!(
2094            (&self.machine_hold_cause, self.hold_reason.as_deref()),
2095            (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2096        )
2097    }
2098
2099    /// Admission waits preserve all execution and approval evidence on recovery.
2100    pub(crate) fn resume_disk_wait(&mut self) {
2101        let retained = self.disk_wait_run().cloned();
2102        self.status = TaskStatus::Queued;
2103        self.held_at = None;
2104        self.hold_source = None;
2105        self.hold_reason = None;
2106        self.machine_hold_cause = None;
2107        self.last_error = None;
2108        self.disk_resume_run = retained;
2109    }
2110
2111    /// Block this task on other task ids and/or open question ids, chosen by
2112    /// `crate::conduct`. Pure: the caller still owns writing it back with
2113    /// [`Queue::put`].
2114    ///
2115    /// Records [`Task::blocked_from`] the first time this moves the task into
2116    /// [`TaskStatus::Blocked`], and leaves it alone on a later call that adds
2117    /// or replaces `blocked_by` while the task is already `Blocked` - a
2118    /// second question about an already-blocked task must not overwrite the
2119    /// status it should eventually return to with `Blocked` itself.
2120    pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2121        self.stamp_schema();
2122        let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2123        let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2124        if self.status != TaskStatus::Blocked || before != after {
2125            self.blocked_at = Some(Timestamp::now());
2126        }
2127        if self.status != TaskStatus::Blocked {
2128            self.blocked_from = Some(self.status);
2129        }
2130        self.status = TaskStatus::Blocked;
2131        self.blocked_by = blocked_by;
2132        self.block_reason = reason;
2133    }
2134
2135    /// Remove one resolved dependency (a task id that became [`TaskStatus::Done`],
2136    /// or a question id that became [`crate::ask::QuestionStatus::Answered`]).
2137    /// Once nothing is left in [`Task::blocked_by`], the task returns to
2138    /// whatever [`Task::blocked_from`] recorded - deciding *why* a task was
2139    /// blocked was `crate::conduct`'s job, but noticing a dependency resolved
2140    /// needs no model at all, and restoring the status it interrupted needs
2141    /// nothing more than what `block` already wrote down.
2142    ///
2143    /// A task blocked while `Running` restores to [`TaskStatus::Queued`]
2144    /// instead: whatever process was running it is gone by the time this
2145    /// runs, so there is nothing left to resume. A task with no recorded
2146    /// `blocked_from` - a pre-schema-4 record, or one blocked before this
2147    /// field existed - falls back to [`TaskStatus::Held`] when it still
2148    /// carries hold evidence ([`Task::hold_reason`] or [`Task::hold_source`],
2149    /// neither ever cleared by `block`), and to `Queued` otherwise: the same
2150    /// choice `block` itself would have recorded, reconstructed from what
2151    /// survived.
2152    ///
2153    /// A no-op, on purpose, for a task that is not [`TaskStatus::Blocked`]:
2154    /// `crate::daemon`'s deterministic resolver runs over every task on every
2155    /// poll, and a task that moved on for some other reason must not be
2156    /// dragged back by a stale id it still happens to carry.
2157    pub fn unblock(&mut self, resolved_id: &str) {
2158        if self.status != TaskStatus::Blocked {
2159            return;
2160        }
2161        self.blocked_by.retain(|id| id != resolved_id);
2162        self.restore_if_unblocked();
2163    }
2164
2165    /// A dependency this task waited on was deleted on purpose
2166    /// ([`Queue::remove`]): drop just that id from [`Task::blocked_by`] and,
2167    /// once nothing is left, return to the status the block interrupted, the
2168    /// same way [`Task::unblock`] does. Returns whether anything changed.
2169    ///
2170    /// Never a hold: the operator chose the deletion, so the dependent is not
2171    /// in trouble. Touches nothing but a `Blocked` task that actually names
2172    /// `deleted_id`, so a `Held` task (or a manual hold) is left exactly as it
2173    /// was. A dependency that vanished *without* going through a deletion is
2174    /// not this method's case - that stays a machine hold.
2175    pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2176        if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2177            return false;
2178        }
2179        self.blocked_by.retain(|id| id != deleted_id);
2180        self.restore_if_unblocked();
2181        true
2182    }
2183
2184    /// The shared tail of [`Task::unblock`] and [`Task::dependency_deleted`]:
2185    /// with nothing left in `blocked_by`, restore the interrupted status and
2186    /// clear the now-stale block bookkeeping.
2187    fn restore_if_unblocked(&mut self) {
2188        if self.blocked_by.is_empty() {
2189            self.status = match self.blocked_from {
2190                Some(TaskStatus::Running) => TaskStatus::Queued,
2191                Some(other) => other,
2192                None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2193                    TaskStatus::Held
2194                }
2195                None => TaskStatus::Queued,
2196            };
2197            self.block_reason = None;
2198            self.blocked_from = None;
2199        }
2200    }
2201
2202    /// Record that a question `crate::conduct` asked about this task has been
2203    /// answered, so the answer's content — not just the fact that the
2204    /// question is gone — reaches the next conductor prompt and the next
2205    /// run's instruction. See [`Task::answers`].
2206    pub fn record_answer(&mut self, question: String, answer: String) {
2207        self.answers.push(AnsweredQuestion { question, answer });
2208    }
2209
2210    /// Requeue this task to reopen its last run as a review-only pass against
2211    /// `branch` (`crate::graph::Runner::review`) rather than competing from
2212    /// scratch. See [`Task::review_branch`].
2213    pub fn request_review(&mut self, branch: String) {
2214        self.release();
2215        self.review_branch = Some(branch);
2216        self.review_instruction = Some(self.instruction.clone());
2217    }
2218
2219    /// Requeue after a conductor chose a new competition. Unlike an ordinary
2220    /// operator release, this deliberately does not resume the old run.
2221    pub fn requeue(&mut self) {
2222        self.release();
2223        // A fresh competition is the opposite of a review of the old branch.
2224        self.review_branch = None;
2225        self.review_instruction = None;
2226        self.fresh_start = true;
2227    }
2228
2229    /// Hold this task because a takeover of `branch` was refused, keeping
2230    /// [`Task::review_branch`] so that once the operator has cleaned up and
2231    /// released it, the retry is a review of the same branch rather than a
2232    /// resume or a fresh competition. Spends no attempt.
2233    ///
2234    /// This is the only way a machine hold keeps a `review_branch`: the
2235    /// daemon takes it at the start of every attempt, so [`Task::release`]
2236    /// relies on that to tell this hold from every other.
2237    pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2238        if branch.is_some() {
2239            self.review_branch = branch;
2240            self.review_instruction = Some(self.instruction.clone());
2241        }
2242        self.hold_machine(Some(reason));
2243    }
2244
2245    /// Change the urgent lane setting without releasing a held task.
2246    pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2247        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2248            bail!(
2249                "task {} is {}; urgent can only change while queued or held; \
2250                 wait for the active attempt to finish and requeue or hold the task first",
2251                self.short(),
2252                self.status.as_str()
2253            );
2254        }
2255        self.urgent = urgent;
2256        Ok(())
2257    }
2258
2259    /// Change how urgently this task should run next.
2260    ///
2261    /// Refused once the task is `running`: priority only feeds the sort
2262    /// [`Queue::next_runnable`] does over tasks waiting to be claimed, and a
2263    /// running task has already left that pool. Accepting the write anyway
2264    /// would look like it worked while changing nothing until - and unless -
2265    /// this attempt fails and the task becomes runnable again, which is a
2266    /// surprise the phone should not hand back as a success.
2267    pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2268        if self.status == TaskStatus::Running {
2269            bail!(
2270                "task {} is running; its priority cannot be changed until \
2271                 this attempt finishes",
2272                self.short()
2273            );
2274        }
2275        self.priority = priority;
2276        Ok(())
2277    }
2278
2279    /// Mark (or unmark) this task to interrupt whatever `magi serve` already
2280    /// has in flight, once `[daemon] pause_for_interrupts` is on. See
2281    /// [`Task::interrupt`].
2282    ///
2283    /// Setting it is restricted to a task the loop could pick up on its own
2284    /// right now - [`TaskStatus::runnable`] - for the same reason as
2285    /// [`Task::set_priority`]: a task already `running` has been claimed, and
2286    /// a task that is `done`, `held`, or `blocked` is not going to compete
2287    /// for the daemon's attention regardless of this flag. Unlike priority,
2288    /// this is never silently inert while `running` - it is refused outright,
2289    /// because the entire feature this flag drives (`crate::daemon`'s
2290    /// interrupt scheduler) is scoped to tasks still waiting to be claimed.
2291    /// Clearing it back to `false` carries no such risk and is always
2292    /// allowed, including on a task that moved on since it was set.
2293    pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2294        if interrupt && !self.status.runnable() {
2295            bail!(
2296                "task {} is {}; only a queued or failed task can be marked \
2297                 to interrupt",
2298                self.short(),
2299                self.status.as_str()
2300            );
2301        }
2302        self.interrupt = interrupt;
2303        Ok(())
2304    }
2305
2306    /// Resolve the task override against the running daemon's limit.
2307    pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2308        self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2309    }
2310
2311    /// Change the budget without resetting attempts or releasing a hold.
2312    /// Callers must hold the queue claim and reload the task before calling.
2313    pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2314        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2315            bail!("only queued or held tasks can change the attempt limit");
2316        }
2317        self.stamp_schema();
2318        self.attempt_limit = limit;
2319        Ok(())
2320    }
2321
2322    /// Explicit implementer choice, with Solo taking precedence for old records.
2323    pub fn implementers(&self) -> Option<usize> {
2324        if self.solo {
2325            Some(1)
2326        } else {
2327            self.overrides.as_ref().and_then(|o| o.candidates)
2328        }
2329    }
2330
2331    /// Task-level policy for a new run in `config`, before falling back to its
2332    /// layered value: the explicit per-task choice, else isolated for an urgent
2333    /// task where that helps and works (`build_target::urgent_isolation`).
2334    pub fn build_cache_override(
2335        &self,
2336        config: &crate::config::Config,
2337    ) -> Option<(BuildCache, &'static str)> {
2338        self.overrides
2339            .as_ref()
2340            .and_then(|o| o.build_cache)
2341            .map(|mode| (mode, "task-override"))
2342            .or_else(|| {
2343                (self.urgent && crate::build_target::urgent_isolation(config))
2344                    .then_some((BuildCache::Isolated, "urgent"))
2345            })
2346    }
2347
2348    /// Set or clear the policy for new runs without changing any saved run.
2349    /// Callers must hold the queue claim and reload the task before calling.
2350    pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2351        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2352            bail!(
2353                "task {} is {}; only queued or held tasks can change build cache",
2354                self.short(),
2355                self.status.as_str()
2356            );
2357        }
2358        self.stamp_schema();
2359        if self.overrides.is_some() || mode.is_some() {
2360            let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2361                inherit_daemon_options: true,
2362                ..RunOverrides::default()
2363            });
2364            overrides.build_cache = mode;
2365        }
2366        Ok(())
2367    }
2368
2369    /// Validate against this task's configuration and change only its seat count.
2370    /// Callers must hold the queue claim and reload the task before calling.
2371    pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2372        self.check_implementers_editable()?;
2373        let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2374        let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2375        if let Some(o) = &self.overrides {
2376            o.apply(&mut config);
2377        }
2378        self.set_implementers(count, &config)
2379    }
2380
2381    fn check_implementers_editable(&self) -> Result<()> {
2382        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2383            bail!(
2384                "task {} is {}; only queued or held tasks can change implementers",
2385                self.short(),
2386                self.status.as_str()
2387            );
2388        }
2389        Ok(())
2390    }
2391
2392    /// Normalize Solo and candidate overrides without altering task history.
2393    pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2394        self.check_implementers_editable()?;
2395        crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2396        self.stamp_schema();
2397        self.solo = count == 1;
2398        let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2399            inherit_daemon_options: true,
2400            ..Default::default()
2401        });
2402        overrides.candidates = (count > 1).then_some(usize::from(count));
2403        let mut settings = overrides.clone();
2404        settings.inherit_daemon_options = false;
2405        // Some(empty) is a direct-run setting too: retain its isolation on Solo.
2406        self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2407        {
2408            None
2409        } else {
2410            Some(overrides)
2411        };
2412        Ok(())
2413    }
2414
2415    /// Replace this task's title and instruction wholesale.
2416    ///
2417    /// Restricted to `queued` and `held`. A `running` task's instruction has
2418    /// already been handed to the graph, so a run in flight and the file on
2419    /// disk must not be allowed to disagree about what was asked; a `done` or
2420    /// `failed` task is a record of what actually happened and editing it
2421    /// after the fact would falsify that record. `id`, `created_at`,
2422    /// `source`, and `runs` are left untouched on purpose - an edit stands in
2423    /// for "delete and refile", and keeping the id, the timestamp, the
2424    /// attribution, and the run history is the entire reason it exists
2425    /// instead.
2426    pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2427        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2428            bail!(
2429                "task {} is {}; only a queued or held task's instruction can \
2430                 be edited",
2431                self.short(),
2432                self.status.as_str()
2433            );
2434        }
2435        // Older retained reviews have no criteria snapshot yet. Capture the
2436        // old instruction before this supported edit can change the target.
2437        if self.review_branch.is_some() && self.review_instruction.is_none() {
2438            self.review_instruction = Some(self.instruction.clone());
2439        }
2440        if self.instruction != instruction {
2441            // A run selected for earlier criteria is no longer authorized by
2442            // this revised instruction. Title-only edits preserve the pin.
2443            self.resume_override = None;
2444        }
2445        if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2446            self.hold_manual(self.hold_reason.clone());
2447        }
2448        self.machine_hold_cause = None;
2449        self.disk_resume_run = None;
2450        self.disk_checked_at = None;
2451        self.title = title;
2452        self.instruction = instruction;
2453        Ok(())
2454    }
2455
2456    /// Record a run that produced a pull request without merging it.
2457    ///
2458    /// The task is held rather than retried, and it costs no further attempt
2459    /// either way. The work the task asked for exists: it is sitting on a
2460    /// branch, in a pull request, waiting for CI or for a person. Retrying
2461    /// would spend the whole competition budget a second time and then race a
2462    /// second branch against the pull request the first one opened - which is
2463    /// exactly what happened to run 01c2, whose finished and green pull request
2464    /// was re-competed from scratch four seconds after it opened.
2465    ///
2466    /// A pull request nobody merged is a request for a person, not a failure.
2467    ///
2468    /// Records `why` into [`Task::hold_reason`] as well as
2469    /// [`Task::last_error`], so the notification centre and `magi task show`
2470    /// say why the task is held rather than "no reason recorded". This is
2471    /// also the path a verified no-op with an outstanding `magi ask` question
2472    /// settles through - see `daemon::settle` and `daemon::settle_and_diagnose`,
2473    /// which append the question id to `hold_reason` when one is still open
2474    /// for the run.
2475    pub fn handed_off(&mut self, why: impl Into<String>) {
2476        let why = why.into();
2477        self.diagnostic = None;
2478        self.note_held();
2479        self.status = TaskStatus::Held;
2480        self.hold_source = Some(HoldSource::Machine);
2481        self.machine_hold_cause = None;
2482        self.disk_resume_run = None;
2483        self.disk_checked_at = None;
2484        self.hold_reason = Some(why.clone());
2485        self.last_error = Some(why);
2486    }
2487
2488    /// Release on explicit operator authority, rather than automatic recovery.
2489    pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2490        self.recovery_budget = None;
2491        self.recovery_generations.clear();
2492        self.recovery_admission = None;
2493        if self
2494            .resumption
2495            .as_ref()
2496            .is_some_and(|r| r.instruction != self.instruction)
2497        {
2498            // Also cover persisted revisions whose earlier approval still
2499            // carries a transient pin when this release is applied.
2500            self.resume_override = None;
2501        }
2502        let approval = Resumption {
2503            generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2504            source: source.to_owned(),
2505            question_id: question_id.map(str::to_owned),
2506            at: Timestamp::now(),
2507            instruction: self.instruction.clone(),
2508            answers_through: self.answers.len(),
2509            runs_through: self.runs.len(),
2510            blocking_evidence: Vec::new(),
2511            cleared_reason: self
2512                .hold_reason
2513                .clone()
2514                .or_else(|| self.block_reason.clone()),
2515        };
2516        self.release();
2517        self.operator_decided_at = Some(approval.at);
2518        if let Some(previous) = self.resumption.replace(approval) {
2519            self.resumption_history.push(previous);
2520        }
2521    }
2522
2523    /// Record a failed graph pass without allowing automatic requeues to refund it.
2524    pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2525        let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2526            || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2527            |a| (a.base.clone(), a.inputs.clone()),
2528        );
2529        let progress = recovery_progress(state);
2530        let stage = if state.prep_failure.is_some() {
2531            "preparation"
2532        } else {
2533            "execution"
2534        };
2535        let matches = |b: &RecoveryBudget| {
2536            b.instruction == self.instruction
2537                && b.base == base
2538                && b.inputs == inputs
2539                && (progress.is_none() || b.progress == progress)
2540        };
2541        if !self.recovery_budget.as_ref().is_some_and(matches) {
2542            let previous = self
2543                .recovery_generations
2544                .iter()
2545                .position(matches)
2546                .map(|index| self.recovery_generations.remove(index));
2547            if let Some(old) = self.recovery_budget.take() {
2548                self.recovery_generations.push(old);
2549            }
2550            self.recovery_budget = previous;
2551        }
2552        if let Some(budget) = &mut self.recovery_budget {
2553            budget.failures = budget.failures.saturating_add(1);
2554            budget.stage = stage.to_owned();
2555        } else {
2556            self.recovery_budget = Some(RecoveryBudget {
2557                instruction: self.instruction.clone(),
2558                base,
2559                inputs,
2560                stage: stage.to_owned(),
2561                failures: 1,
2562                progress,
2563            });
2564        }
2565    }
2566
2567    pub(crate) fn recovery_exhausted(
2568        &self,
2569        base: &str,
2570        inputs: &str,
2571        limit: usize,
2572    ) -> Option<String> {
2573        let same_input = |b: &&RecoveryBudget| {
2574            b.instruction == self.instruction && b.base == base && b.inputs == inputs
2575        };
2576        let budget = self
2577            .recovery_budget
2578            .as_ref()
2579            .filter(same_input)
2580            .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2581        (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2582    }
2583
2584    pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2585        self.hold_unrequested_retry(Some(reason));
2586        if let Some(pass) = self.passes.last()
2587            && self.execution_runs().last() == Some(&pass.run)
2588        {
2589            self.recovery_budget_hold = Some(RecoveryBudgetHold {
2590                admission,
2591                run: pass.run.clone(),
2592                pass: pass.pass_index,
2593                held_at: self.held_at.expect("hold timestamp just recorded"),
2594                decision: self.operator_decided_at,
2595                legacy: false,
2596            });
2597        }
2598    }
2599
2600    fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2601        self.status == TaskStatus::Held
2602            && self.hold_source == Some(HoldSource::Manual)
2603            && self.machine_hold_cause.is_none()
2604            && self.recovery_budget.as_ref().is_some_and(|budget| {
2605                budget.instruction == self.instruction
2606                    && budget.base == admission.base
2607                    && budget.inputs == admission.inputs
2608                    && budget.stage == "execution"
2609                    && budget.failures > 0
2610                    && self
2611                        .hold_reason
2612                        .as_ref()
2613                        .is_some_and(|reason| *reason == budget.budget_reason())
2614            })
2615    }
2616
2617    fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2618        let held_at = self.held_at?;
2619        let settled = self.passes.last()?;
2620        let admission = self.recovery_admission.as_ref()?;
2621        if !self.matches_budget_hold(admission)
2622            || self.execution_runs().last() != Some(&settled.run)
2623            || settled.cost != PassCost::Spent
2624            || settled.parked.is_some()
2625            || settled.settled_at > held_at
2626            || self.operator_decided_at.is_some_and(|at| at >= held_at)
2627        {
2628            return None;
2629        }
2630        Some(RecoveryBudgetHold {
2631            admission: admission.clone(),
2632            run: settled.run.clone(),
2633            pass: settled.pass_index,
2634            held_at,
2635            decision: self.operator_decided_at,
2636            legacy: true,
2637        })
2638    }
2639
2640    pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2641        let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2642            self.held_at,
2643            self.passes.last(),
2644            run.passes.last(),
2645            self.recovery_admission.as_ref(),
2646        ) else {
2647            return false;
2648        };
2649        if !self.matches_budget_hold(admission)
2650            || self.execution_runs().last() != Some(&run.id)
2651            || settled.run != run.id
2652            || settled.pass_index != pass.index
2653            || settled.cost != PassCost::Spent
2654            || settled.parked.is_some()
2655            || settled.settled_at < pass.started_at
2656            || settled.settled_at > held_at
2657            || self.operator_decided_at.is_some_and(|at| at >= held_at)
2658            || !crate::daemon::compatible_run_instruction(run, self)
2659        {
2660            return false;
2661        }
2662        match &self.recovery_budget_hold {
2663            Some(hold) => {
2664                hold.run == run.id
2665                    && hold.pass == pass.index
2666                    && hold.held_at == held_at
2667                    && hold.decision == self.operator_decided_at
2668                    && &hold.admission == admission
2669                    && (!hold.legacy
2670                        || self
2671                            .operator_decided_at
2672                            .is_none_or(|at| at < pass.started_at))
2673            }
2674            None => {
2675                self.schema < RECOVERY_HOLD_SCHEMA
2676                    && self
2677                        .operator_decided_at
2678                        .is_none_or(|at| at < pass.started_at)
2679            }
2680        }
2681    }
2682
2683    pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2684        self.stamp_schema();
2685        self.repair_grants.push(receipt.clone());
2686        self.status = TaskStatus::Queued;
2687        self.hold_source = None;
2688        self.hold_reason = None;
2689        self.held_at = None;
2690        self.recovery_budget_hold = None;
2691        self.resume_override = Some(OperatorResume {
2692            question_id: String::new(),
2693            at: receipt.at,
2694            conductor_rehold: None,
2695            forced: true,
2696            pinned_run: Some(receipt.request.run.clone()),
2697        });
2698    }
2699
2700    /// Put a held or finished task back in line, with its attempt count reset
2701    /// so a release is a real second chance rather than an instant re-hold.
2702    /// The run history is kept: attempts reset, evidence does not.
2703    pub fn release(&mut self) {
2704        // Freeze the unresolved cause before a recovery can mint a run without
2705        // doing work. Approval and timestamps alone are not new outcomes.
2706        self.import_chat_notice();
2707        if self.hold_notice_cause.is_none()
2708            && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2709        {
2710            self.hold_notice_cause = Some(self.unresolved_hold_cause());
2711        }
2712        let refused_handover = self.status == TaskStatus::Held
2713            && self.hold_source == Some(HoldSource::Machine)
2714            && self.review_branch.is_some()
2715            && self
2716                .review_instruction
2717                .as_ref()
2718                .is_none_or(|i| *i == self.instruction);
2719        self.status = TaskStatus::Queued;
2720        self.held_at = None;
2721        self.attempts = 0;
2722        self.last_error = None;
2723        self.park_reason = None;
2724        // Otherwise the next person who holds this task reads a reason that
2725        // belonged to whatever it was waiting on last time.
2726        self.hold_reason = None;
2727        self.hold_source = None;
2728        self.machine_hold_cause = None;
2729        self.disk_resume_run = None;
2730        self.disk_checked_at = None;
2731        self.diagnostic = None;
2732        // A release also un-blocks: the dependency or question `blocked_by`
2733        // named may still be unresolved, but a human (or `crate::conduct`)
2734        // choosing to release the task overrides that wait outright, the same
2735        // as it overrides an ordinary hold.
2736        self.blocked_by.clear();
2737        self.block_reason = None;
2738        self.blocked_from = None;
2739        // A machine hold that still names a review branch is a refused
2740        // handover (see [`Task::hold_for_handover`]): the retry must review
2741        // that same branch. Any other release drops it.
2742        if !refused_handover {
2743            self.review_branch = None;
2744            self.review_instruction = None;
2745        }
2746        self.fresh_start = false;
2747    }
2748}
2749
2750/// Copy `src` into `dir` as `name`, or `stem-2.ext`, `stem-3.ext`, ... when
2751/// that is taken. `create_new` makes the collision check atomic and also
2752/// catches a case-insensitive filesystem. Returns the stored name and path.
2753fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
2754    use std::io::ErrorKind;
2755    let (stem, ext) = match name.rfind('.') {
2756        Some(i) if i > 0 => (&name[..i], &name[i..]),
2757        _ => (name, ""),
2758    };
2759    for n in 1u32.. {
2760        let candidate = if n == 1 {
2761            name.to_owned()
2762        } else {
2763            let suffix = format!("-{n}");
2764            let room = 64usize.saturating_sub(suffix.len() + ext.len());
2765            let stem: String = stem.chars().take(room).collect();
2766            format!("{stem}{suffix}{ext}")
2767        };
2768        if !crate::ask::valid_asset_name(&candidate) {
2769            bail!("no valid attachment name is left for `{name}`");
2770        }
2771        let path = dir.join(&candidate);
2772        match std::fs::OpenOptions::new()
2773            .write(true)
2774            .create_new(true)
2775            .open(&path)
2776        {
2777            Ok(mut out) => {
2778                let copied = std::fs::File::open(src)
2779                    .and_then(|mut input| std::io::copy(&mut input, &mut out));
2780                if let Err(e) = copied {
2781                    drop(out);
2782                    let _ = std::fs::remove_file(&path);
2783                    return Err(e).with_context(|| format!("copy {}", src.display()));
2784                }
2785                return Ok((candidate, path));
2786            }
2787            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
2788            Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
2789        }
2790    }
2791    unreachable!("the counter never runs out")
2792}
2793
2794/// Minimum age before a dead writer's lock may be recovered, and maximum wait
2795/// for a contending writer. Age alone never revokes a live writer's ownership.
2796const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
2797
2798/// Guard for [`Queue::lock_task`]; removes the lock file on drop, but only
2799/// while the file still carries this guard's owner token.
2800pub(crate) struct TaskLock {
2801    path: PathBuf,
2802    token: String,
2803}
2804
2805/// A token no other holder shares: pid, then a mix of entropy and a process
2806/// counter so threads born in the same nanosecond still differ.
2807fn owner_token() -> String {
2808    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
2809    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
2810    let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
2811    format!("{}-{:016x}", std::process::id(), r.next_u64())
2812}
2813
2814/// The marker that serializes everyone removing the lock that carries `token`.
2815/// Hashed (FNV-1a) so an empty or foreign token is still a valid file name.
2816fn break_marker(path: &Path, token: &str) -> PathBuf {
2817    let mut h: u64 = 0xcbf29ce484222325;
2818    for b in token.bytes() {
2819        h ^= u64::from(b);
2820        h = h.wrapping_mul(0x100000001b3);
2821    }
2822    let mut name = path.as_os_str().to_owned();
2823    name.push(format!(".break-{h:016x}"));
2824    PathBuf::from(name)
2825}
2826
2827fn older_than_stale(path: &Path) -> bool {
2828    std::fs::metadata(path)
2829        .and_then(|m| m.modified())
2830        .ok()
2831        .and_then(|t| t.elapsed().ok())
2832        .is_some_and(|age| age > TASK_LOCK_STALE)
2833}
2834
2835fn writer_may_be_gone(token: &str) -> bool {
2836    let Some(pid) = token
2837        .split_once('-')
2838        .and_then(|(pid, _)| pid.parse::<u32>().ok())
2839    else {
2840        // Legacy/incomplete tokens have no valid writer identity. They remain
2841        // subject to the age and compare/remove checks.
2842        return true;
2843    };
2844    if pid == std::process::id() {
2845        return false;
2846    }
2847    // Unknown process-table access must not steal a long-running retirement.
2848    crate::proc::pid_status(pid) == Some(false)
2849}
2850
2851/// How many levels of "a stale marker guarding a stale marker" are recovered
2852/// before giving up. Each level needs its own crashed remover, so the cap is
2853/// never reached without several independent crashes.
2854const MAX_MARKER_DEPTH: u8 = 3;
2855
2856/// Take the break marker for `token`, or `None` if another remover holds it.
2857/// The marker carries its own owner token. One older than [`TASK_LOCK_STALE`]
2858/// was left by a remover that died; it is cleared by the same compare-and-
2859/// remove discipline as a lock, guarded by a marker of its own, so a recoverer
2860/// that judged it stale cannot delete a fresh marker that replaced it.
2861fn take_marker(
2862    path: &Path,
2863    token: &str,
2864    depth: u8,
2865    retry: crate::lock_file::Retry,
2866) -> Option<(PathBuf, String)> {
2867    use std::io::Write;
2868    let marker = break_marker(path, token);
2869    for _ in 0..2 {
2870        match retry.create(&marker) {
2871            Ok(mut f) => {
2872                let mine = owner_token();
2873                if f.write_all(mine.as_bytes()).is_err() {
2874                    drop(f);
2875                    let _ = std::fs::remove_file(&marker);
2876                    return None;
2877                }
2878                return Some((marker, mine));
2879            }
2880            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
2881                let judged = std::fs::read_to_string(&marker).ok();
2882                match judged.filter(|_| older_than_stale(&marker)) {
2883                    Some(judged) if depth < MAX_MARKER_DEPTH => {
2884                        remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
2885                    }
2886                    _ => return None,
2887                }
2888            }
2889            Err(_) => return None,
2890        }
2891    }
2892    None
2893}
2894
2895/// Remove the lock at `path` if it still carries `token` (and, when
2896/// `require_stale`, is still stale). Removal is serialized per token by the
2897/// break marker, so a remover that judged an old lock cannot delete the fresh
2898/// one that replaced it. `None` means the marker was busy: try again.
2899fn remove_lock_if(
2900    path: &Path,
2901    token: &str,
2902    require_stale: bool,
2903    depth: u8,
2904    retry: crate::lock_file::Retry,
2905) -> Option<bool> {
2906    let (marker, mine) = take_marker(path, token, depth, retry)?;
2907    let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
2908        && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
2909    if still {
2910        let _ = std::fs::remove_file(path);
2911    }
2912    // Release the marker only if it is still ours.
2913    if depth >= MAX_MARKER_DEPTH {
2914        if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
2915            let _ = std::fs::remove_file(&marker);
2916        }
2917    } else {
2918        let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
2919    }
2920    Some(still)
2921}
2922
2923/// Break the lock judged stale while it held `judged`. Returns whether it was
2924/// removed; a lock that has since been replaced is left alone.
2925#[cfg(test)]
2926fn break_stale(path: &Path, judged: &str) -> bool {
2927    break_stale_with(path, judged, crate::lock_file::Retry::new(None))
2928}
2929
2930fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
2931    remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
2932}
2933
2934impl Drop for TaskLock {
2935    fn drop(&mut self) {
2936        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
2937        let retry = crate::lock_file::Retry::new(Some(deadline));
2938        loop {
2939            match remove_lock_if(&self.path, &self.token, false, 0, retry) {
2940                Some(_) => return,
2941                None if std::time::Instant::now() > deadline => return,
2942                None => std::thread::sleep(std::time::Duration::from_millis(5)),
2943            }
2944        }
2945    }
2946}
2947
2948#[derive(Debug, thiserror::Error)]
2949#[error("task changed during completion decision; reload and inspect it")]
2950pub(crate) struct CompletionSnapshotChanged;
2951
2952/// A queue on disk.
2953#[derive(Debug, Clone)]
2954pub struct Queue {
2955    root: PathBuf,
2956    ids: IdSource,
2957}
2958
2959fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
2960    let mut wanted = Vec::new();
2961    for src in sources {
2962        let name = src
2963            .file_name()
2964            .and_then(|n| n.to_str())
2965            .with_context(|| format!("`{}` has no usable file name", src.display()))?;
2966        if !crate::ask::valid_asset_name(name) {
2967            bail!(
2968                "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
2969                 with no `..`; rename the file and try again"
2970            );
2971        }
2972        if !src.is_file() {
2973            bail!("attachment `{}` is not a file", src.display());
2974        }
2975        wanted.push((src, name));
2976    }
2977    Ok(wanted)
2978}
2979
2980impl Queue {
2981    /// The operator's queue, `<home>/queue`.
2982    pub fn open() -> Self {
2983        Self::at(crate::run::home().join("queue"))
2984    }
2985
2986    /// A queue at an explicit root. Tests use this; so could an operator who
2987    /// wants a queue per project.
2988    pub fn at(root: PathBuf) -> Self {
2989        Self {
2990            root,
2991            ids: IdSource::new(new_id),
2992        }
2993    }
2994
2995    /// Replace the source of candidate ids for new tasks. For tests that need
2996    /// a deterministic collision.
2997    #[doc(hidden)]
2998    pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
2999        self.ids = IdSource::custom(f);
3000        self
3001    }
3002
3003    /// File a new task: reserve its id atomically and write it without ever
3004    /// reading, merging into or replacing an existing record.
3005    ///
3006    /// The candidate is `task.id`. Under that id's write lock, a record that
3007    /// already exists makes the candidate taken and another id is minted; a
3008    /// failure to find out is an error, never "free". `hook` runs under the
3009    /// lock once the id looks free and may veto it with `Ok(false)` (an
3010    /// orphaned claim or attachment directory also marks an id as used). The
3011    /// first `Err` ends the attempt. `undo` runs if the record then fails to
3012    /// write. `task.id` is the reserved id on success.
3013    fn file_with(
3014        &self,
3015        task: &mut Task,
3016        hook: impl FnMut(&mut Task) -> Result<bool>,
3017        undo: impl FnMut(&mut Task),
3018    ) -> Result<()> {
3019        self.reserve_id(task, hook, undo, true)
3020    }
3021
3022    /// The reservation loop behind [`Queue::file_with`]. With `store` false
3023    /// the id is only reserved through whatever `hook` leaves on disk (an
3024    /// attachment directory) and no record is written; the task stays unfiled.
3025    ///
3026    /// An injected id source supplies the first candidate too, unless the
3027    /// task already holds an id through an earlier reservation (attachments);
3028    /// production keeps the id [`Task::new`] minted.
3029    fn reserve_id(
3030        &self,
3031        task: &mut Task,
3032        mut hook: impl FnMut(&mut Task) -> Result<bool>,
3033        mut undo: impl FnMut(&mut Task),
3034        store: bool,
3035    ) -> Result<()> {
3036        let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3037        let initial = task.id.clone();
3038        self.ids
3039            .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3040                task.id = id.to_owned();
3041                let _lock = self.lock_task(&task.id)?;
3042                if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3043                    return Ok(false);
3044                }
3045                if store {
3046                    if let Err(e) = self.write_record(task) {
3047                        undo(task);
3048                        return Err(e);
3049                    }
3050                    task.unfiled = false;
3051                }
3052                Ok(true)
3053            })?;
3054        Ok(())
3055    }
3056
3057    /// Is `id` used by anything but a stored record: a claim file, or an
3058    /// attachment directory (`check_attachments`) left by an earlier
3059    /// reservation or an interrupted filing? Only a definite "not found" is
3060    /// free; any other answer is an error, never "free".
3061    fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3062        if path_exists(&self.lock_path(id))? {
3063            return Ok(true);
3064        }
3065        Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3066    }
3067
3068    /// The `hook` of a plain [`Queue::put`] of a new task. Attachments
3069    /// already copied by [`Queue::attach`] sit in this id's own directory,
3070    /// which is then not a sign of someone else's use.
3071    fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3072        Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3073    }
3074
3075    /// File a new task and take its claim in one step, on the id that ends up
3076    /// reserved. An id whose claim file already exists is taken.
3077    pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3078        let mut claim = None;
3079        self.file_with(
3080            task,
3081            |t| {
3082                if self.id_in_use(&t.id, true)? {
3083                    return Ok(false);
3084                }
3085                claim = Some(self.claim(&t.id)?);
3086                Ok(true)
3087            },
3088            |_| {},
3089        )?;
3090        claim.context("claim missing after filing")
3091    }
3092
3093    /// Directory holding the task files.
3094    pub fn root(&self) -> &Path {
3095        &self.root
3096    }
3097
3098    /// Path for one task id.
3099    pub fn path_of(&self, id: &str) -> PathBuf {
3100        self.root.join(format!("{id}.json"))
3101    }
3102
3103    /// Directory holding a task's attachments. A sibling of the task file,
3104    /// not a `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
3105    pub fn attachments_dir(&self, id: &str) -> PathBuf {
3106        self.root.join(format!("{id}.attachments"))
3107    }
3108
3109    /// Copy each of `sources` into `task`'s attachment directory and record
3110    /// the stored names on `task` (persist with [`Queue::put`]). Returns the
3111    /// names, in order.
3112    ///
3113    /// Every source is checked (a readable file, a name passing
3114    /// [`crate::ask::valid_asset_name`]) before anything is copied, and a
3115    /// copy that fails part-way removes only what this call created. A name
3116    /// already taken is never overwritten: it becomes `stem-2.ext`,
3117    /// `stem-3.ext`, ... A name that does not validate is refused rather than
3118    /// sanitised - the operator renames the file.
3119    pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3120        let wanted = validate_attachments(sources)?;
3121        if task.unfiled && task.attachments.is_empty() {
3122            // Not stored yet: the directory is created under the id's
3123            // reservation and keeps the id taken until the record lands.
3124            let names = std::cell::RefCell::new(Vec::new());
3125            self.reserve_id(
3126                task,
3127                |t| {
3128                    if self.id_in_use(&t.id, true)? {
3129                        return Ok(false);
3130                    }
3131                    *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3132                    Ok(true)
3133                },
3134                |_| {},
3135                false,
3136            )?;
3137            return Ok(names.into_inner());
3138        }
3139        self.copy_attachments(task, &wanted)
3140    }
3141
3142    /// Copy `wanted` into `task`'s attachment directory (see [`Queue::attach`]).
3143    fn copy_attachments(
3144        &self,
3145        task: &mut Task,
3146        wanted: &[(&PathBuf, &str)],
3147    ) -> Result<Vec<String>> {
3148        let dir = self.attachments_dir(&task.id);
3149        let existed = dir.is_dir();
3150        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3151        let mut created: Vec<PathBuf> = Vec::new();
3152        let mut names = Vec::new();
3153        let mut copy_all = || -> Result<()> {
3154            for (src, name) in wanted {
3155                let (stored, path) = copy_new(&dir, src, name)?;
3156                created.push(path);
3157                names.push(stored);
3158            }
3159            Ok(())
3160        };
3161        if let Err(e) = copy_all() {
3162            for path in &created {
3163                let _ = std::fs::remove_file(path);
3164            }
3165            if !existed {
3166                let _ = std::fs::remove_dir(&dir);
3167            }
3168            return Err(e);
3169        }
3170        task.attachments.extend(names.iter().cloned());
3171        Ok(names)
3172    }
3173
3174    /// [`Queue::attach`] then [`Queue::put`], undoing the copies when the
3175    /// record cannot be written. Without the undo the files sit in
3176    /// `<id>.attachments/` with no task pointing at them.
3177    ///
3178    /// Only what this call copied is removed (the names `attach` returned,
3179    /// and the directory itself only when it did not exist before and is
3180    /// empty), never an attachment an earlier save recorded. `task` is rolled
3181    /// back too, and the error the caller sees is `put`'s own. This relies on
3182    /// a failed `put` leaving the stored record untouched, which its
3183    /// write-then-rename guarantees.
3184    pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3185        if task.unfiled && task.attachments.is_empty() {
3186            return self.attach_and_file(task, sources);
3187        }
3188        let dir = self.attachments_dir(&task.id);
3189        let existed = dir.is_dir();
3190        let before = task.attachments.len();
3191        let names = self.attach(task, sources)?;
3192        if let Err(e) = self.put(task) {
3193            for name in &names {
3194                let _ = std::fs::remove_file(dir.join(name));
3195            }
3196            if !existed {
3197                let _ = std::fs::remove_dir(&dir);
3198            }
3199            task.attachments.truncate(before);
3200            return Err(e);
3201        }
3202        Ok(names)
3203    }
3204
3205    /// [`Queue::attach_and_put`] for a task not yet stored: the attachment
3206    /// directory is created under the id's reservation, and a candidate whose
3207    /// directory already exists is taken.
3208    fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3209        let wanted = validate_attachments(sources)?;
3210        let before = task.attachments.len();
3211        let names = std::cell::RefCell::new(Vec::new());
3212        let result = self.file_with(
3213            task,
3214            |t| {
3215                if self.id_in_use(&t.id, true)? {
3216                    return Ok(false);
3217                }
3218                *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3219                Ok(true)
3220            },
3221            |t| {
3222                let dir = self.attachments_dir(&t.id);
3223                for name in names.borrow().iter() {
3224                    let _ = std::fs::remove_file(dir.join(name));
3225                }
3226                // The directory did not exist when the id was reserved.
3227                let _ = std::fs::remove_dir(&dir);
3228                t.attachments.truncate(before);
3229            },
3230        );
3231        result.map(|()| names.into_inner())
3232    }
3233
3234    /// Absolute paths of `task`'s attachments, whatever shape this queue's
3235    /// root has. Absolute because the prompt hands them to an agent whose
3236    /// working directory is somewhere else entirely.
3237    pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3238        let dir = self.attachments_dir(&task.id);
3239        task.attachments
3240            .iter()
3241            .map(|n| {
3242                let p = dir.join(n);
3243                std::path::absolute(&p).unwrap_or(p)
3244            })
3245            .collect()
3246    }
3247
3248    /// Write a task, atomically, so a daemon killed mid-write leaves the
3249    /// previous state readable rather than a truncated file.
3250    ///
3251    /// Runs already recorded on disk that `task` does not carry are kept, not
3252    /// dropped: `magi run --task` links a run into a task from another
3253    /// process ([`Queue::link_run`]) while a daemon may hold a snapshot taken
3254    /// before it, and writing that snapshot back whole would erase the link.
3255    /// Nothing ever removes a run from a task, so the union loses nothing.
3256    pub fn put(&self, task: &mut Task) -> Result<()> {
3257        if task.unfiled {
3258            // A new task never merges into a record that has its id.
3259            return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3260        }
3261        let _lock = self.lock_task(&task.id)?;
3262        self.put_unlocked(task)
3263    }
3264
3265    /// Write `task` only if no task with its id exists yet; `Ok(false)` when
3266    /// one does. Unlike [`Queue::put`] it never replaces a record, so a
3267    /// producer with a deterministic id cannot rewind a task that has since
3268    /// started running or finished.
3269    pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3270        let _lock = self.lock_task(&task.id)?;
3271        if path_exists(&self.path_of(&task.id))? {
3272            return Ok(false);
3273        }
3274        self.write_record(task)?;
3275        task.unfiled = false;
3276        Ok(true)
3277    }
3278
3279    /// [`Queue::put`] for a caller already holding [`Queue::lock_task`].
3280    fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3281        self.merge_stored(task);
3282        if let Some(boundary) = task.reassignments.last() {
3283            let stored = self.get(&task.id)?;
3284            anyhow::ensure!(
3285                task.reassignments == stored.reassignments
3286                    && task.repo == stored.repo
3287                    && task.runs.get(..boundary.run_boundary)
3288                        == stored.runs.get(..boundary.run_boundary),
3289                "historical repository execution cannot be restarted; reload the task"
3290            );
3291        }
3292        self.write_record(task)
3293    }
3294
3295    /// Save an exact-run recovery pin only if its admitted owner snapshot is current.
3296    pub(crate) fn commit_base_recovery(
3297        &self,
3298        task: &mut Task,
3299        expected: &serde_json::Value,
3300    ) -> Result<()> {
3301        let _lock = self.lock_task(&task.id)?;
3302        anyhow::ensure!(
3303            serde_json::to_value(self.get(&task.id)?)? == *expected,
3304            "task changed during base recovery; inspect the pending authorization"
3305        );
3306        // Retain the ordinary merge evidence when replacing an earlier decision pin.
3307        self.put_unlocked(task)
3308    }
3309
3310    pub(crate) fn commit_repair_grant(
3311        &self,
3312        task: &mut Task,
3313        expected: &serde_json::Value,
3314    ) -> Result<()> {
3315        let _lock = self.lock_task(&task.id)?;
3316        anyhow::ensure!(
3317            serde_json::to_value(self.get(&task.id)?)? == *expected,
3318            "repair grant refused: task changed during admission"
3319        );
3320        self.write_record(task)
3321            .context(crate::repair_budget::PublicationUnknown)
3322    }
3323
3324    /// Save a disk monitor transition only while its complete task snapshot matches.
3325    pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3326        let _lock = self.lock_task(&task.id)?;
3327        anyhow::ensure!(
3328            serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3329            "task changed during disk monitoring"
3330        );
3331        task.stamp_schema();
3332        self.write_record_inner(task, false)
3333    }
3334
3335    /// Commit one validated reassignment under the task write lock.
3336    pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3337        let _lock = self.lock_task(&task.id)?;
3338        let stored = self.get(&task.id)?;
3339        anyhow::ensure!(
3340            serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3341                && stored.reassignments.len() + 1 == task.reassignments.len()
3342                && stored.repo == task.reassignments.last().expect("new boundary").from
3343                && stored.runs == task.runs,
3344            "task changed during reassignment; retry after inspecting it"
3345        );
3346        self.write_record(task)
3347    }
3348
3349    /// Commit a validated lifecycle transition only against its admitted snapshot.
3350    pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3351        let _lock = self.lock_task(&task.id)?;
3352        anyhow::ensure!(
3353            serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3354            CompletionSnapshotChanged
3355        );
3356        self.write_record(task)
3357    }
3358
3359    /// Fold the stored record of `task`'s id into `task` (updates only).
3360    fn merge_stored(&self, task: &mut Task) {
3361        if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3362            stored.import_chat_notice();
3363            // A stale writer may add evidence, but never erase/rewrite an
3364            // immutable event or undo the lifecycle decision it did not see.
3365            let local_decision = task.completion_history.iter().any(|event| {
3366                !stored
3367                    .completion_history
3368                    .iter()
3369                    .any(|saved| saved.occurrence == event.occurrence)
3370                    && event.at > stored.updated_at
3371            });
3372            let unseen_decision = stored.completion_history.iter().any(|event| {
3373                !task
3374                    .completion_history
3375                    .iter()
3376                    .any(|mine| mine.occurrence == event.occurrence)
3377            });
3378            let mut history = std::mem::take(&mut stored.completion_history);
3379            for event in std::mem::take(&mut task.completion_history) {
3380                if !history
3381                    .iter()
3382                    .any(|stored| stored.occurrence == event.occurrence)
3383                {
3384                    history.push(event);
3385                }
3386            }
3387            if unseen_decision {
3388                // Keep the persisted decision and every live control that followed
3389                // it. Only import evidence from the writer that missed it.
3390                task.import_chat_notice();
3391                let mut stale = std::mem::replace(task, stored);
3392                append_missing(&mut task.answers, stale.answers);
3393                if task.reassignments == stale.reassignments {
3394                    append_missing(&mut task.runs, stale.runs);
3395                }
3396                for (ledger, entries) in [
3397                    (&mut task.decision_effects, stale.decision_effects),
3398                    (&mut task.superseded_resumes, stale.superseded_resumes),
3399                    (&mut task.dispatched_resumes, stale.dispatched_resumes),
3400                ] {
3401                    for (key, value) in entries {
3402                        ledger.entry(key).or_insert(value);
3403                    }
3404                }
3405                append_missing(&mut task.actions_applied, stale.actions_applied);
3406                append_missing(&mut task.triage_applied, stale.triage_applied);
3407                append_missing(&mut task.chat_notices, stale.chat_notices);
3408                append_missing(
3409                    &mut task.base_recovery_requests,
3410                    stale.base_recovery_requests,
3411                );
3412                // The tail is the current grant. Older receipts must not replace
3413                // it or bring back their queued status or exact-run pins.
3414                prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3415                    a.request.request == b.request.request
3416                });
3417                prepend_missing_by(
3418                    &mut task.repair_reconciliations,
3419                    stale.repair_reconciliations,
3420                    |a, b| a.request.request == b.request.request,
3421                );
3422                // A triage effect can refer to an approval from the stale writer.
3423                // Retain it for proof, never as the active release.
3424                stale.resumption_history.extend(stale.resumption);
3425                stale.resumption_history.retain(|approval| {
3426                    task.resumption
3427                        .as_ref()
3428                        .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3429                });
3430                prepend_missing_by(
3431                    &mut task.resumption_history,
3432                    stale.resumption_history,
3433                    |a, b| a.at == b.at && a.generation == b.generation,
3434                );
3435                for failure in stale.startup_failures {
3436                    task.record_startup_failure(failure);
3437                }
3438                for pass in stale.passes {
3439                    if !task.passes.iter().any(|stored| {
3440                        stored.run == pass.run && stored.pass_index == pass.pass_index
3441                    }) {
3442                        task.passes.push(pass);
3443                    }
3444                }
3445                task.completion_history = history;
3446                if !task.decision_effects.is_empty() {
3447                    task.stamp_schema();
3448                }
3449                return;
3450            }
3451            if stored.reassignments.len() > task.reassignments.len() {
3452                // An older writer may contribute evidence, but cannot restore
3453                // old execution selections, status, or runs across the boundary.
3454                let stale = std::mem::replace(task, stored.clone());
3455                for answer in stale.answers {
3456                    if !task.answers.contains(&answer) {
3457                        task.answers.push(answer);
3458                    }
3459                }
3460            }
3461            // Receipt history is append-only; control state comes from the
3462            // newer snapshot, not from whichever writer happens to keep a receipt.
3463            if task.updated_at < stored.updated_at
3464                && (task.sync_only != stored.sync_only
3465                    || stored.sync_only.is_some()
3466                    || stored
3467                        .recovery_budget_hold
3468                        .as_ref()
3469                        .is_some_and(|hold| hold.held_at > task.updated_at)
3470                    || stored.repair_grants.last().is_some_and(|grant| {
3471                        task.repair_grants.last() != Some(grant)
3472                            || stored.operator_decided_at > task.operator_decided_at
3473                            || stored
3474                                .resume_override
3475                                .as_ref()
3476                                .is_some_and(|pin| pin.at > task.updated_at)
3477                            || (task.resume_override != stored.resume_override
3478                                && task
3479                                    .resume_override
3480                                    .as_ref()
3481                                    .is_some_and(|pin| pin.at == grant.at))
3482                    }))
3483                && task
3484                    .operator_decided_at
3485                    .is_none_or(|at| at <= stored.updated_at)
3486                && task
3487                    .resume_override
3488                    .as_ref()
3489                    .is_none_or(|pin| pin.at <= stored.updated_at)
3490                && !local_decision
3491            {
3492                *task = stored.clone();
3493            }
3494            task.completion_history = history;
3495            append_missing(
3496                &mut task.base_recovery_requests,
3497                stored.base_recovery_requests,
3498            );
3499            append_missing(&mut task.actions_applied, stored.actions_applied);
3500            append_missing(&mut task.triage_applied, stored.triage_applied);
3501            for receipt in &stored.repair_grants {
3502                if !task
3503                    .repair_grants
3504                    .iter()
3505                    .any(|r| r.request.request == receipt.request.request)
3506                {
3507                    // History can be recovered independently of the live pin.
3508                    task.repair_grants.push(receipt.clone());
3509                }
3510            }
3511            for receipt in &stored.repair_reconciliations {
3512                if !task.repair_reconciliations.contains(receipt) {
3513                    // A pre-reconciliation snapshot must preserve the recovery's
3514                    // exact-run queue pin and release state with its receipt.
3515                    task.repair_reconciliations.push(receipt.clone());
3516                    task.resume_override = stored.resume_override.clone();
3517                    task.status = stored.status;
3518                    task.hold_source = stored.hold_source;
3519                    task.machine_hold_cause = stored.machine_hold_cause.clone();
3520                    task.disk_resume_run = stored.disk_resume_run.clone();
3521                    task.disk_checked_at = stored.disk_checked_at;
3522                    task.hold_reason = stored.hold_reason.clone();
3523                    task.held_at = stored.held_at;
3524                }
3525            }
3526            task.superseded_resumes.extend(stored.superseded_resumes);
3527            task.dispatched_resumes.extend(stored.dispatched_resumes);
3528            if task.status != TaskStatus::Running
3529                && let Some(pin) = &stored.resume_override
3530                && !pin.question_id.is_empty()
3531                && let Some(run) = &pin.pinned_run
3532                && task.resume_override.as_ref().is_none_or(|next| {
3533                    next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3534                })
3535            {
3536                task.superseded_resumes
3537                    .insert(pin.question_id.clone(), run.clone());
3538            }
3539            // A writer holding an older task snapshot must never erase or
3540            // rewrite proof that a chat command already committed its effect.
3541            for (id, receipt) in stored.decision_effects {
3542                task.decision_effects.insert(id, receipt);
3543            }
3544            if !task.decision_effects.is_empty() {
3545                task.stamp_schema();
3546            }
3547            // The task's message chat is recorded once and never rewound or
3548            // dropped by a writer holding an older snapshot.
3549            if task.chat.is_none() {
3550                task.chat = stored.chat.clone();
3551            }
3552            append_missing(&mut task.chat_notices, stored.chat_notices);
3553            for failure in stored.startup_failures {
3554                task.record_startup_failure(failure);
3555            }
3556            append_missing(&mut task.runs, stored.runs);
3557            for p in stored.passes {
3558                if !task
3559                    .passes
3560                    .iter()
3561                    .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3562                {
3563                    task.passes.push(p);
3564                }
3565            }
3566            // A completion notice already recorded is never rewound by an
3567            // older snapshot: that would report the same state twice.
3568            if let Some(n) = stored.chat_notice
3569                && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3570            {
3571                task.chat_notice = Some(n);
3572            }
3573        }
3574    }
3575
3576    /// Audit-only update; caller holds the task write lock and claim. Preserve
3577    /// timestamps, controls and notification state while appending startup evidence.
3578    pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3579        let path = self.path_of(&task.id);
3580        let tmp = path.with_extension("json.tmp");
3581        std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3582        std::fs::rename(tmp, path)?;
3583        Ok(())
3584    }
3585
3586    /// Stamp and write `task` atomically; the caller holds the id's lock.
3587    fn write_record(&self, task: &mut Task) -> Result<()> {
3588        self.write_record_inner(task, true)
3589    }
3590
3591    fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3592        task.import_chat_notice();
3593        if task.status != TaskStatus::Held && task.sync_only.is_none() {
3594            task.recovery_budget_hold = None;
3595        }
3596        task.updated_at = Timestamp::now();
3597        std::fs::create_dir_all(&self.root)
3598            .with_context(|| format!("create {}", self.root.display()))?;
3599        let body = serde_json::to_string_pretty(task).context("serialize task")?;
3600        let path = self.path_of(&task.id);
3601        let tmp = path.with_extension("json.tmp");
3602        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3603        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3604        // A machine hold is news for the notification centre, filed beside
3605        // this queue (`<home>/queue` -> `<home>/notifications`) rather than
3606        // through a process-global, so a queue in a temp directory notifies
3607        // into that directory.
3608        if let (Some(notice), Some(home)) = (
3609            notify.then(|| crate::notices::task_held(task)).flatten(),
3610            self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3611        ) {
3612            crate::notices::raise_in(home, notice);
3613        }
3614        Ok(())
3615    }
3616
3617    /// Change the task `id` in place: read it inside its write lock, let `f`
3618    /// edit it, and write it back only when `f` returns `true`. The check a
3619    /// caller makes in `f` therefore sees the record as stored now, not a
3620    /// snapshot taken before another writer got in. Returns whether it wrote.
3621    pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3622        let id = self.resolve_id(id)?;
3623        let _lock = self.lock_task(&id)?;
3624        let mut task = self.get(&id)?;
3625        if !f(&mut task) {
3626            return Ok(false);
3627        }
3628        self.put_unlocked(&mut task)?;
3629        Ok(true)
3630    }
3631
3632    /// Append `run` to the runs of the task `id` (or an unambiguous prefix),
3633    /// leaving everything else about it alone — see [`Task::link_run`]. Read
3634    /// and written back in one breath, because [`Queue::put`] replaces the
3635    /// whole record. Returns the task as stored.
3636    pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
3637        let id = self.resolve_id(id)?;
3638        // Read inside the lock, so the record written back is the current one
3639        // and a daemon's write cannot slip between the read and the write.
3640        let _lock = self.lock_task(&id)?;
3641        let mut task = self.get(&id)?;
3642        if task.link_run(run) {
3643            self.put_unlocked(&mut task)?;
3644        }
3645        Ok(task)
3646    }
3647
3648    /// Exclusive right to rewrite task `id`'s record, held until the guard
3649    /// drops. Every writer ([`Queue::put`], [`Queue::link_run`]) takes it, so
3650    /// a process linking a run and the daemon saving a transition are
3651    /// serialized instead of last-writer-wins. An old lock may be broken only
3652    /// after its writer is confirmed dead (legacy tokens without a PID retain
3653    /// age-based recovery). Not the claim lock (`<id>.lock`), held for a
3654    /// whole run.
3655    pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
3656        std::fs::create_dir_all(&self.root)
3657            .with_context(|| format!("create {}", self.root.display()))?;
3658        let path = self.root.join(format!("{id}.write-lock"));
3659        let started = std::time::Instant::now();
3660        let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
3661        let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
3662        loop {
3663            match retry.create(&path) {
3664                Ok(mut file) => {
3665                    use std::io::Write;
3666                    let token = owner_token();
3667                    if let Err(e) = file.write_all(token.as_bytes()) {
3668                        drop(file);
3669                        let _ = std::fs::remove_file(&path);
3670                        return Err(e).with_context(|| format!("lock {}", path.display()));
3671                    }
3672                    return Ok(TaskLock { path, token });
3673                }
3674                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3675                    // Content first, then age: a lock replaced in between
3676                    // reads fresh, never stale.
3677                    let judged = std::fs::read_to_string(&path).ok();
3678                    let broken = judged
3679                        .filter(|_| older_than_stale(&path))
3680                        .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
3681                    // A break that does not happen (marker busy, recovery
3682                    // exhausted) is a wait like any other, so it meets the
3683                    // same deadline instead of spinning forever.
3684                    if !broken {
3685                        if started.elapsed() > TASK_LOCK_STALE {
3686                            bail!("could not lock task {id}");
3687                        }
3688                        std::thread::sleep(std::time::Duration::from_millis(15));
3689                    }
3690                }
3691                Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
3692            }
3693        }
3694    }
3695
3696    /// Load a task by id or unambiguous id prefix.
3697    pub fn get(&self, id: &str) -> Result<Task> {
3698        let resolved = self.resolve_id(id)?;
3699        read_path(&self.path_of(&resolved))
3700    }
3701
3702    /// Remove a task, and the claim lock that belongs to it.
3703    ///
3704    /// `in_flight` comes from the caller — a live daemon's heartbeat naming
3705    /// this task — because the task's own `running` status cannot answer the
3706    /// question. A daemon killed mid-competition leaves the status at
3707    /// `running` and an orphaned `.lock` behind, and a guard that trusted
3708    /// either would make the task undeletable for good: the phone showed
3709    /// exactly that, refusing a task whose daemon had been gone for an hour.
3710    ///
3711    /// So the lock is removed with the task rather than respected. Any lock
3712    /// still there once no live daemon claims the task is by definition stale,
3713    /// and leaving it would make a deleted task look claimed to
3714    /// [`Queue::claim`] and to whoever reads the directory.
3715    ///
3716    /// A deletion is deliberate, so whatever was `blocked` on the id is
3717    /// resolved, not held: a `<id>.removed` tombstone is written first (it
3718    /// is what tells [`missing_blockers`] and the daemon's resolver that this
3719    /// id was deleted on purpose, so a pass that races this call cannot
3720    /// mistake it for a vanished dependency), the record is deleted (the
3721    /// tombstone is taken back if that fails), and then each dependent is
3722    /// rewritten under its claim - see [`Queue::release_dependents_of`].
3723    /// Best-effort for the dependents: one claimed by something else right
3724    /// now, or whose write fails, is released silently by
3725    /// `crate::daemon::resolve_blockers` (or `crate::triage::run_once`) on
3726    /// its next pass, because the tombstone is still there. It does not fail
3727    /// this removal.
3728    ///
3729    /// `questions` is the store [`missing_blockers`] checks a `blocked_by` id
3730    /// against - the same store the caller already resolves `id`'s own home
3731    /// from, passed in rather than reopened here so a test queue at an
3732    /// explicit root never reads the operator's real questions directory.
3733    pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
3734        self.remove_with_receipt(id, in_flight, questions, None)
3735    }
3736
3737    /// Atomically retain the deleted task as the receipt for this triage inquiry.
3738    pub(crate) fn discard_triage(
3739        &self,
3740        id: &str,
3741        questions: &Questions,
3742        inquiry: &str,
3743    ) -> Result<Removal> {
3744        self.remove_with_receipt(id, false, questions, Some(inquiry))
3745    }
3746
3747    pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
3748        let path = self
3749            .root
3750            .join("triage-discard")
3751            .join(format!("{inquiry}.json"));
3752        let bytes = match std::fs::read(path) {
3753            Ok(bytes) => bytes,
3754            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
3755            Err(e) => return Err(e.into()),
3756        };
3757        let receipt: Task = serde_json::from_slice(&bytes)?;
3758        Ok(receipt.id == id && !self.path_of(id).exists())
3759    }
3760
3761    fn remove_with_receipt(
3762        &self,
3763        id: &str,
3764        in_flight: bool,
3765        questions: &Questions,
3766        inquiry: Option<&str>,
3767    ) -> Result<Removal> {
3768        let resolved = self.resolve_id(id)?;
3769        if in_flight {
3770            bail!("task {resolved} is being run by a live daemon right now");
3771        }
3772        let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
3773        if let Some(path) = &receipt {
3774            std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
3775        }
3776        self.write_tombstone(&resolved)?;
3777        if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
3778            Some(path) => std::fs::rename(p, path),
3779            None => std::fs::remove_file(p),
3780        }) {
3781            // A record that is still there was not deleted: take the marker
3782            // back. One already gone keeps it, so the deletion still reads
3783            // as deliberate.
3784            if self.path_of(&resolved).exists() {
3785                let _ = std::fs::remove_file(self.tombstone_path(&resolved));
3786            }
3787            return Err(e);
3788        }
3789        let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
3790        Ok(Removal {
3791            id: resolved,
3792            released,
3793            still_blocked,
3794        })
3795    }
3796
3797    /// Path of the marker saying task `id` was deleted on purpose. Not a
3798    /// `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
3799    fn tombstone_path(&self, id: &str) -> PathBuf {
3800        self.root.join(format!("{id}.removed"))
3801    }
3802
3803    fn write_tombstone(&self, id: &str) -> Result<()> {
3804        let path = self.tombstone_path(id);
3805        let tmp = self.root.join(format!("{id}.removed.tmp"));
3806        std::fs::write(&tmp, b"")
3807            .and_then(|()| std::fs::rename(&tmp, &path))
3808            .with_context(|| format!("write {}", path.display()))
3809    }
3810
3811    /// Was `id` deleted through [`Queue::remove`] (and is its record gone)?
3812    /// A live record always wins: a tombstone never makes an existing task
3813    /// look deleted.
3814    fn was_deleted(&self, id: &str) -> bool {
3815        self.tombstone_path(id).is_file() && !self.path_of(id).exists()
3816    }
3817
3818    /// Apply [`Task::dependency_deleted`] to `task` for every `blocked_by` id
3819    /// that [`Queue::remove`] deleted. Returns those ids. The caller holds
3820    /// the task's claim and saves it.
3821    pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
3822        let deleted = deleted_blockers(self, questions, &task.blocked_by);
3823        deleted
3824            .into_iter()
3825            .filter(|id| task.dependency_deleted(id))
3826            .collect()
3827    }
3828
3829    /// Record, as a fixed-wording info notice, that `dependent` stopped
3830    /// waiting on the deleted task `deleted`. Best-effort and beside the
3831    /// queue, like the hold notice [`Queue::put`] files.
3832    pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
3833        let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
3834            return;
3835        };
3836        let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
3837        let waiting = dependent.status == TaskStatus::Blocked;
3838        let message = match (ja, waiting) {
3839            (true, false) => format!(
3840                "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
3841                dependent.short(),
3842                short(deleted)
3843            ),
3844            (true, true) => format!(
3845                "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
3846                dependent.short(),
3847                short(deleted)
3848            ),
3849            (false, false) => format!(
3850                "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
3851                dependent.short(),
3852                short(deleted)
3853            ),
3854            (false, true) => format!(
3855                "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
3856                dependent.short(),
3857                short(deleted)
3858            ),
3859        };
3860        crate::notices::raise_in(
3861            home,
3862            crate::notices::Notice::info(
3863                &format!("unblocked:{}:{}", dependent.id, deleted),
3864                message,
3865            )
3866            .link(crate::notices::Link::Task {
3867                id: dependent.id.clone(),
3868            }),
3869        );
3870    }
3871
3872    /// Resolve every `blocked` task naming `dependency` (just deleted) with
3873    /// [`Task::dependency_deleted`]. Returns the ids released to another
3874    /// status and those that remain `blocked` on something else. Each
3875    /// dependent is re-read inside its claim, never written from a stale copy.
3876    fn release_dependents_of(
3877        &self,
3878        dependency: &str,
3879        questions: &Questions,
3880    ) -> (Vec<String>, Vec<String>) {
3881        let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
3882        for listed in self.list() {
3883            if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
3884                matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
3885            }) {
3886                continue;
3887            }
3888            let Ok(_claim) = self.claim(&listed.id) else {
3889                continue;
3890            };
3891            let Ok(mut task) = self.get(&listed.id) else {
3892                continue;
3893            };
3894            let references: Vec<String> = task.blocked_by.iter().filter(|id| {
3895                matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
3896            }).cloned().collect();
3897            if references.is_empty() {
3898                continue;
3899            }
3900            for reference in references {
3901                task.dependency_deleted(&reference);
3902            }
3903            if self.put(&mut task).is_err() {
3904                continue;
3905            }
3906            self.note_dependency_deleted(&task, dependency);
3907            if task.status == TaskStatus::Blocked {
3908                still_blocked.push(task.id.clone());
3909            } else {
3910                released.push(task.id.clone());
3911            }
3912        }
3913        (released, still_blocked)
3914    }
3915
3916    /// The attachment-and-record half of [`Queue::remove`]. `remove_record` is
3917    /// how the record file is deleted; production passes `remove_file`, and a
3918    /// test passes a failing one to prove the attachments come back.
3919    fn remove_record_with_attachments(
3920        &self,
3921        resolved: &str,
3922        remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
3923    ) -> Result<()> {
3924        // Neither step may strand the other. The attachments are set aside by a
3925        // rename (cheap, and undone if the record cannot be removed), then the
3926        // record goes, and only then is the set-aside directory deleted for
3927        // real. A failure before the record is gone loses nothing; a failure
3928        // after it leaves at most an orphan `.removing` directory, which the
3929        // next removal sweeps.
3930        self.sweep_removed_attachments();
3931        let attachments = self.attachments_dir(resolved);
3932        let aside = self.root.join(format!("{resolved}.attachments.removing"));
3933        let moved = match std::fs::rename(&attachments, &aside) {
3934            Ok(()) => true,
3935            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
3936            Err(e) => {
3937                return Err(e).with_context(|| format!("remove {}", attachments.display()));
3938            }
3939        };
3940        let path = self.path_of(resolved);
3941        if let Err(e) = remove_record(&path) {
3942            if moved {
3943                let _ = std::fs::rename(&aside, &attachments);
3944            }
3945            return Err(e).with_context(|| format!("remove {}", path.display()));
3946        }
3947        if moved {
3948            if let Err(e) = std::fs::remove_dir_all(&aside) {
3949                tracing::warn!("leftover attachments {}: {e}", aside.display());
3950            }
3951        }
3952        let lock = self.lock_path(resolved);
3953        if let Err(e) = std::fs::remove_file(&lock) {
3954            if e.kind() != std::io::ErrorKind::NotFound {
3955                return Err(e).with_context(|| format!("remove {}", lock.display()));
3956            }
3957        }
3958        Ok(())
3959    }
3960
3961    /// Delete `*.attachments.removing` directories a previous [`Queue::remove`]
3962    /// could not finish deleting. The task record is already gone by then, so
3963    /// the id no longer resolves and the removal cannot be retried by name;
3964    /// every later removal sweeps them instead. A directory whose record still
3965    /// exists belongs to a removal in progress and is left alone. Best-effort.
3966    fn sweep_removed_attachments(&self) {
3967        let Ok(entries) = std::fs::read_dir(&self.root) else {
3968            return;
3969        };
3970        for entry in entries.flatten() {
3971            let name = entry.file_name();
3972            let name = name.to_string_lossy();
3973            let Some(id) = name.strip_suffix(".attachments.removing") else {
3974                continue;
3975            };
3976            // A record still on disk means a removal is mid-flight (or about
3977            // to roll back): the directory is its to delete or restore.
3978            if !self.path_of(id).exists() {
3979                if let Err(e) = std::fs::remove_dir_all(entry.path()) {
3980                    tracing::warn!("leftover attachments {}: {e}", entry.path().display());
3981                }
3982            }
3983        }
3984        self.sweep_tombstones();
3985    }
3986
3987    /// Delete `*.removed` markers that are no longer needed: the record is
3988    /// gone, no task's `blocked_by` names the id, and the marker is older than
3989    /// [`TOMBSTONE_GRACE`]. The age is what makes this safe against a
3990    /// concurrent writer: the task list read here can be stale, so a dependent
3991    /// that was just blocked on an id (a conductor applying a decision while a
3992    /// removal is under way) would otherwise lose the marker and be held as a
3993    /// vanished dependency. A marker whose record still exists belongs to a
3994    /// removal in progress and is never touched.
3995    fn sweep_tombstones(&self) {
3996        let Ok(entries) = std::fs::read_dir(&self.root) else {
3997            return;
3998        };
3999        let tasks = self.list();
4000        for entry in entries.flatten() {
4001            let name = entry.file_name();
4002            let name = name.to_string_lossy();
4003            let Some(id) = name.strip_suffix(".removed") else {
4004                continue;
4005            };
4006            if self.path_of(id).exists()
4007                || tasks.iter().any(|t| {
4008                    t.blocked_by
4009                        .iter()
4010                        .any(|b| id.starts_with(b) || id.ends_with(b))
4011                })
4012            {
4013                continue;
4014            }
4015            let old = entry
4016                .metadata()
4017                .and_then(|m| m.modified())
4018                .ok()
4019                .and_then(|m| m.elapsed().ok())
4020                .is_some_and(|age| age >= TOMBSTONE_GRACE);
4021            if old {
4022                let _ = std::fs::remove_file(entry.path());
4023            }
4024        }
4025    }
4026
4027    /// Path of the claim lock for a task. One definition, so `claim` and
4028    /// `remove` cannot end up naming different files.
4029    fn lock_path(&self, id: &str) -> PathBuf {
4030        self.root.join(format!("{id}.lock"))
4031    }
4032
4033    /// Every task on disk, highest priority first and newest first within a
4034    /// priority. This is what `magi task list` and `GET /api/queue` print, so
4035    /// a raised priority has to move a task here the moment it is saved, not
4036    /// only in [`Queue::next_runnable`]'s own ordering - the operator reading
4037    /// the backlog and the loop about to drain it must agree on what "first"
4038    /// means. Every existing task defaults to priority 0, so this is a no-op
4039    /// change from the old newest-first order for a queue nobody has
4040    /// reprioritised.
4041    ///
4042    /// Unreadable files are skipped rather than fatal: one corrupt task must
4043    /// not take the queue - or the web UI, or an unattended daemon - down
4044    /// with it.
4045    pub fn list(&self) -> Vec<Task> {
4046        #[cfg(test)]
4047        LIST_READS.with(|count| count.set(count.get() + 1));
4048        let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4049            .into_iter()
4050            .flatten()
4051            .flatten()
4052            .map(|e| e.path())
4053            .filter(|p| p.extension().is_some_and(|x| x == "json"))
4054            .filter_map(|p| read_path(&p).ok())
4055            .collect();
4056        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4057        tasks
4058    }
4059
4060    /// Task files [`Queue::list`] skips because they cannot be parsed (a
4061    /// newer schema, a torn write). A guard that looks a task up by scanning
4062    /// the list must treat any of these as "the task might be there".
4063    pub fn unreadable(&self) -> Vec<PathBuf> {
4064        std::fs::read_dir(&self.root)
4065            .into_iter()
4066            .flatten()
4067            .flatten()
4068            .map(|e| e.path())
4069            .filter(|p| p.extension().is_some_and(|x| x == "json"))
4070            .filter(|p| read_path(p).is_err())
4071            .collect()
4072    }
4073
4074    /// Runs that a later attempt at the same task replaced, mapped to the id
4075    /// of the attempt that replaced them.
4076    ///
4077    /// A task keeps its attempts in order, and the deck showed them as two
4078    /// cards with the same title and no hint which was which: yukimemi asked
4079    /// why `stalled` and `blocked` appeared twice for one task, and the
4080    /// answer - "those are two tries, and the second one exists because of a
4081    /// bug since fixed" - was not on the screen anywhere.
4082    ///
4083    /// Read from the queue rather than stored on the run, because the
4084    /// ordering is the queue's fact: a `RunState` has no idea another attempt
4085    /// happened after it.
4086    pub fn superseded(&self) -> HashMap<String, String> {
4087        let mut by = HashMap::new();
4088        for task in self.list() {
4089            for earlier in &task.runs {
4090                if let Some(later) = task.successor_of(earlier) {
4091                    by.insert(earlier.clone(), later.clone());
4092                }
4093            }
4094        }
4095        by
4096    }
4097
4098    /// Whether `run` is an earlier attempt a later one replaced, and if so
4099    /// the id of that later attempt.
4100    ///
4101    /// Same walk as [`Queue::superseded`], narrowed to one run: a run detail
4102    /// page asks about exactly one run at a time, and this keeps that call
4103    /// site from building (and discarding) the whole map's `HashMap` just to
4104    /// read one entry out of it.
4105    pub fn superseded_by(&self, run: &str) -> Option<String> {
4106        for task in self.list() {
4107            if task.runs.iter().any(|r| r == run) {
4108                return task.successor_of(run).cloned();
4109            }
4110        }
4111        None
4112    }
4113
4114    /// The task's own most recent attempt, when `run` belongs to that task
4115    /// but is not already that attempt.
4116    ///
4117    /// Distinct from [`Queue::superseded_by`], which names only the very
4118    /// next attempt: a chain of retries (A superseded by B superseded by C)
4119    /// leaves an older run pointing at an intermediate one that may itself
4120    /// be unresolved, and a run's own detail page needs to know where the
4121    /// task's story currently stands - the chain's current head, C - not an
4122    /// attempt in the middle of it that a client would otherwise have to
4123    /// walk to by hand.
4124    pub fn latest_attempt(&self, run: &str) -> Option<String> {
4125        for task in self.list() {
4126            if task.runs.iter().any(|r| r == run) {
4127                return task.runs.last().filter(|last| **last != run).cloned();
4128            }
4129        }
4130        None
4131    }
4132
4133    /// The task a daemon should run next, or `None` when the queue is idle.
4134    ///
4135    /// Upgrade resumes first, then highest priority and oldest id first.
4136    /// See [`dispatch_order`] for the durable ordering rule.
4137    pub fn next_runnable(&self) -> Option<Task> {
4138        let mut runnable: Vec<Task> = self
4139            .list()
4140            .into_iter()
4141            .filter(|t| t.status.runnable())
4142            .collect();
4143        runnable.sort_unstable_by(dispatch_order);
4144        runnable.into_iter().next()
4145    }
4146
4147    /// Take exclusive ownership of a task.
4148    ///
4149    /// The lock is a `create_new` file next to the task, which is atomic on
4150    /// every platform magi targets. It exists so two daemons - or a daemon and
4151    /// a human running `magi run` - cannot drive one task into two competing
4152    /// runs. The returned guard releases on drop, including on panic.
4153    pub fn claim(&self, id: &str) -> Result<Claim> {
4154        std::fs::create_dir_all(&self.root)
4155            .with_context(|| format!("create {}", self.root.display()))?;
4156        let path = self.lock_path(id);
4157        let retry = crate::lock_file::Retry::new(None);
4158        match retry.create(&path) {
4159            Ok(mut f) => {
4160                use std::io::Write as _;
4161                // Best effort: the pid is for the human looking at a stale lock.
4162                let _ = writeln!(f, "{}", std::process::id());
4163                Ok(Claim { path })
4164            }
4165            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4166                bail!("task {id} is already claimed ({} exists)", path.display())
4167            }
4168            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4169        }
4170    }
4171
4172    /// Expand an id prefix to exactly one task id.
4173    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4174        if !prefix.is_empty()
4175            && prefix != "."
4176            && prefix != ".."
4177            && !prefix.contains(['/', '\\'])
4178            && self.path_of(prefix).is_file()
4179        {
4180            return Ok(prefix.to_owned());
4181        }
4182        let ids = record_ids(&self.root, "json")?;
4183        match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4184            Reference::Found(id) => Ok(id),
4185            Reference::Missing => bail!("no task matches `{prefix}`"),
4186            Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4187        }
4188    }
4189
4190    /// Change detection token for the queue.
4191    ///
4192    /// Combines file names and modification times of all task files in the
4193    /// queue, so adding, modifying, or deleting any task — even an older one —
4194    /// moves the revision and notifies connected clients via the change stream.
4195    /// Returns 0 when the queue is completely empty.
4196    pub fn revision(&self) -> u64 {
4197        self.revision_excluding(&std::collections::BTreeSet::new())
4198    }
4199
4200    /// [`Queue::revision`] ignoring the files of the named task ids, for a
4201    /// caller that tracks those tasks' content some other way.
4202    pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4203        use std::hash::{Hash as _, Hasher as _};
4204
4205        let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4206            .into_iter()
4207            .flatten()
4208            .flatten()
4209            .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4210            .filter(|e| {
4211                let path = e.path();
4212                !path
4213                    .file_stem()
4214                    .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4215            })
4216            .filter_map(|e| {
4217                let name = e.file_name().to_string_lossy().into_owned();
4218                let mtime = e
4219                    .metadata()
4220                    .ok()?
4221                    .modified()
4222                    .ok()?
4223                    .duration_since(std::time::UNIX_EPOCH)
4224                    .ok()?
4225                    .as_millis() as u64;
4226                Some((name, mtime))
4227            })
4228            .collect();
4229
4230        if entries.is_empty() {
4231            return 0;
4232        }
4233
4234        entries.sort_unstable();
4235        let mut hasher = std::hash::DefaultHasher::new();
4236        for (name, mtime) in &entries {
4237            name.hash(&mut hasher);
4238            mtime.hash(&mut hasher);
4239        }
4240        let h = hasher.finish();
4241        if h == 0 { 1 } else { h }
4242    }
4243}
4244
4245/// How long a deletion marker is kept after its record is gone, even with
4246/// nothing referencing it. See [`Queue::sweep_tombstones`].
4247const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4248
4249/// What [`Queue::remove`] did, beyond deleting the named task's own file.
4250#[derive(Debug, Clone)]
4251pub struct Removal {
4252    /// The id actually removed - `id` expanded from a prefix, if it was one.
4253    pub id: String,
4254    /// Every task that was `blocked` on [`Removal::id`] and left the block
4255    /// (back to the status it interrupted) because that was its only
4256    /// remaining dependency.
4257    pub released: Vec<String>,
4258    /// Every task that named [`Removal::id`] and is still `blocked` on
4259    /// another dependency.
4260    pub still_blocked: Vec<String>,
4261}
4262
4263/// Exclusive ownership of a task, released on drop.
4264#[derive(Debug)]
4265pub struct Claim {
4266    path: PathBuf,
4267}
4268
4269impl Drop for Claim {
4270    fn drop(&mut self) {
4271        let _ = std::fs::remove_file(&self.path);
4272    }
4273}
4274
4275/// The first line of a task, trimmed to a title. Used when the caller gives a
4276/// body but no title, which is the normal case for an agent piping a file in.
4277pub fn title_from(instruction: &str, max: usize) -> String {
4278    let Some(line) = first_line(instruction) else {
4279        return "(empty task)".to_owned();
4280    };
4281    if line.chars().count() <= max {
4282        return line.to_owned();
4283    }
4284    let head: String = line.chars().take(max.saturating_sub(1)).collect();
4285    format!("{head}…")
4286}
4287
4288/// The first non-blank line, whatever it is. A markdown heading is the
4289/// task's own summary - agents pipe in `# Rework the config loader` and mean
4290/// exactly that - so it is preferred over the prose beneath it rather than
4291/// skipped as decoration. Leading list and heading markers are stripped
4292/// because they are syntax, not words. `None` when nothing is left.
4293pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4294    let line = instruction
4295        .lines()
4296        .map(str::trim)
4297        .find(|l| !l.is_empty())?
4298        .trim_start_matches(['#', '-', '*', '>', ' '])
4299        .trim();
4300    (!line.is_empty()).then_some(line)
4301}
4302
4303#[cfg(test)]
4304thread_local! {
4305    pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4306}
4307
4308fn read_path(path: &Path) -> Result<Task> {
4309    #[cfg(test)]
4310    TASK_READS.with(|count| count.set(count.get() + 1));
4311    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4312    let mut task: Task =
4313        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4314    // Greater-than, not not-equal: every field added since schema 1 carries
4315    // `#[serde(default)]`, so an older task has nothing to say about it and
4316    // defaulting is exactly as good a reading as a value that build never had
4317    // a chance to write. Only a schema *ahead* of this build - a meaning it
4318    // cannot possibly know - is refused rather than guessed at.
4319    if task.schema > SCHEMA {
4320        bail!(
4321            "task {} was written by a different magi (schema {}, this build \
4322             speaks {SCHEMA})",
4323            task.id,
4324            task.schema
4325        );
4326    }
4327    task.preserve_legacy_build_cache();
4328    if task.schema < 22
4329        && task.status == TaskStatus::Held
4330        && task.hold_source == Some(HoldSource::Machine)
4331        && task.resume_override.is_none()
4332        && task
4333            .hold_reason
4334            .as_deref()
4335            .is_some_and(crate::disk::is_gate_reason)
4336    {
4337        task.mark_disk_capacity();
4338    }
4339    Ok(task)
4340}
4341
4342/// Resolution shared by queue lookups and dependency inventories. Exact ids
4343/// win; otherwise both the CLI prefix and displayed suffix are supported.
4344#[derive(Debug, PartialEq, Eq)]
4345pub(crate) enum Reference {
4346    Found(String),
4347    Missing,
4348    Ambiguous,
4349}
4350
4351pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4352    let mut hits = Vec::new();
4353    for candidate in ids {
4354        if candidate == id {
4355            return Reference::Found(candidate.to_owned());
4356        }
4357        if candidate.starts_with(id) || candidate.ends_with(id) {
4358            hits.push(candidate);
4359        }
4360    }
4361    match hits.as_slice() {
4362        [] => Reference::Missing,
4363        [one] => Reference::Found((*one).to_owned()),
4364        _ => Reference::Ambiguous,
4365    }
4366}
4367
4368/// Read names, not deserialized records: list() intentionally skips corrupt
4369/// and future-schema records, which still exist and must keep their waiters.
4370pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4371    let entries = match std::fs::read_dir(root) {
4372        Ok(entries) => entries,
4373        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4374        Err(e) => return Err(e.into()),
4375    };
4376    let mut ids = Vec::new();
4377    for entry in entries {
4378        let path = entry?.path();
4379        if path.extension().is_some_and(|e| e == extension)
4380            && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4381        {
4382            ids.push(id.to_owned());
4383        }
4384    }
4385    Ok(ids)
4386}
4387
4388/// Unknown and ambiguous dependencies stay waiting; neither is evidence that
4389/// the operator deleted a prerequisite or needs to supply its replacement.
4390#[derive(Debug, PartialEq, Eq)]
4391pub enum Dependency {
4392    /// Existing task record, with its canonical id; its contents may be unreadable.
4393    Task(String),
4394    /// Existing question record, with its canonical id.
4395    Question(String),
4396    /// Explicitly removed task, identified by its tombstone.
4397    Deleted(String),
4398    /// No matching record or tombstone after a successful inventory read.
4399    Missing,
4400    /// More than one record matches the reference.
4401    Ambiguous,
4402    /// The inventory cannot currently be read, so existence is unknown.
4403    Unknown,
4404}
4405
4406/// Resolve against authoritative task, question and deletion record names.
4407pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4408    let (Ok(tasks), Ok(qs), Ok(removed)) = (
4409        record_ids(queue.root(), "json"),
4410        record_ids(questions.root(), "json"),
4411        record_ids(queue.root(), "removed"),
4412    ) else {
4413        return Dependency::Unknown;
4414    };
4415    // Include tombstones in ambiguity checks: a reused suffix must never
4416    // release a waiter on a different, still-live task.
4417    let mut ids = tasks
4418        .iter()
4419        .chain(qs.iter())
4420        .chain(removed.iter())
4421        .cloned()
4422        .collect::<Vec<_>>();
4423    ids.sort();
4424    ids.dedup();
4425    match resolve_reference(id, ids.iter().map(String::as_str)) {
4426        Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4427        Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4428        Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4429        Reference::Found(_) => Dependency::Unknown,
4430        Reference::Missing => Dependency::Missing,
4431        Reference::Ambiguous => Dependency::Ambiguous,
4432    }
4433}
4434
4435/// Canonicalize only proven dependencies, preserving unknown legacy references.
4436pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4437    for id in ids {
4438        if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4439            dependency(queue, questions, id)
4440        {
4441            *id = full;
4442        }
4443    }
4444}
4445
4446/// Live queue facts for decision and deputy prompts. Historical hold reasons
4447/// and question text are claims, never an inventory of existing prerequisites.
4448pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4449    let inventory = crate::blockers::Inventory::load(queue, questions);
4450    let mut text = String::from(
4451        "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4452    );
4453    match record_ids(queue.root(), "json") {
4454        Ok(ids) => {
4455            for id in ids {
4456                match queue.get(&id) {
4457                    Ok(task) => text.push_str(&format!(
4458                        "{}: {}; blocked_by={:?}; chain={:?}\n",
4459                        task.id,
4460                        task.status.as_str(),
4461                        task.blocked_by,
4462                        inventory.waits_on(&task)
4463                    )),
4464                    Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4465                }
4466            }
4467        }
4468        Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4469    }
4470    text
4471}
4472
4473/// Only a successful directory scan with no matching record proves absence.
4474pub fn missing_blockers(
4475    queue: &Queue,
4476    questions: &Questions,
4477    blocked_by: &[String],
4478) -> Vec<String> {
4479    blocked_by
4480        .iter()
4481        .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4482        .cloned()
4483        .collect()
4484}
4485
4486/// Return the original references, so legacy short ids are removed by the
4487/// same Task transition as full ids.
4488pub fn deleted_blockers(
4489    queue: &Queue,
4490    questions: &Questions,
4491    blocked_by: &[String],
4492) -> Vec<String> {
4493    blocked_by
4494        .iter()
4495        .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4496        .cloned()
4497        .collect()
4498}
4499
4500/// The `hold_reason` text for a task quarantined because one or more of its
4501/// `blocked_by` ids no longer exist. Shared by `crate::daemon::resolve_blockers`,
4502/// `crate::triage::run_once`, and [`Queue::remove`]'s own dependent
4503/// quarantine, so the three call sites read as the same event to an operator
4504/// looking at `magi task show` rather than three different wordings for it.
4505///
4506/// Names the full original `blocked_by` list, not just `missing` - a task
4507/// quarantined here can also have named a dependency that was still
4508/// perfectly valid, and [`Task::hold_machine`] clears `blocked_by` on the way
4509/// in, so this text is the only place that information survives for an
4510/// operator deciding whether to release the task outright.
4511pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4512    missing_blocker_hold_reason_in(blocked_by, missing, "en")
4513}
4514
4515/// [`missing_blocker_hold_reason`] in `language` (Japanese, else English).
4516pub fn missing_blocker_hold_reason_in(
4517    blocked_by: &[String],
4518    missing: &[String],
4519    language: &str,
4520) -> String {
4521    if crate::lang::is_japanese(language) {
4522        format!(
4523            "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4524            blocked_by.join(", "),
4525            missing.join(", "),
4526        )
4527    } else {
4528        format!(
4529            "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4530            blocked_by.join(", "),
4531            missing.join(", "),
4532        )
4533    }
4534}
4535
4536/// The last dash-separated part of an id, the form people say aloud.
4537pub fn short(id: &str) -> &str {
4538    id.split('-').next_back().unwrap_or(id)
4539}
4540
4541fn new_id() -> String {
4542    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4543    let seed = crate::rng::entropy();
4544    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4545}
4546
4547#[cfg(test)]
4548mod tests {
4549    #[test]
4550    fn reassignment_clears_repository_bound_execution_selections() {
4551        let mut task = Task::new(
4552            "move".into(),
4553            "evidence".into(),
4554            "old".into(),
4555            Source::Human,
4556        );
4557        task.review_branch = Some("old-review".into());
4558        task.review_instruction = Some("old criteria".into());
4559        task.pr_recovery = Some(crate::pr_recovery::Selection {
4560            url: "https://example.invalid/pull/1".into(),
4561            branch: "old-pr".into(),
4562            head: "head".into(),
4563            source_head: None,
4564            source_run: None,
4565            source_proof: None,
4566            disposition: None,
4567            instruction: "old criteria".into(),
4568            approved_at: Timestamp::now(),
4569        });
4570        task.replacement = Some(crate::merge_decision::Replacement {
4571            question: "owner".into(),
4572            run: "old-run".into(),
4573            pr: "https://example.invalid/pull/1".into(),
4574            agent: "worker".into(),
4575            context: "evidence".into(),
4576        });
4577        task.resume_override = Some(OperatorResume {
4578            question_id: "old-question".into(),
4579            at: Timestamp::now(),
4580            conductor_rehold: None,
4581            forced: true,
4582            pinned_run: Some("old-run".into()),
4583        });
4584        task.interrupt = true;
4585        task.reassign_repository("new".into(), "test");
4586        assert!(task.review_branch.is_none());
4587        assert!(task.review_instruction.is_none());
4588        assert!(task.pr_recovery.is_none());
4589        assert!(task.replacement.is_none());
4590        assert!(task.resume_override.is_none());
4591        assert!(!task.interrupt);
4592        assert!(task.fresh_start);
4593        assert_eq!(task.instruction, "evidence");
4594    }
4595
4596    #[test]
4597    fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4598        let t = Task::new(
4599            "retry".into(),
4600            "do it".into(),
4601            PathBuf::from("."),
4602            Source::Human,
4603        );
4604        let mut value = serde_json::to_value(&t).unwrap();
4605        for field in ["resumption", "resumption_history", "operator_decided_at"] {
4606            value.as_object_mut().unwrap().remove(field);
4607        }
4608        value["schema"] = serde_json::json!(15);
4609        let mut legacy: Task = serde_json::from_value(value).unwrap();
4610        legacy.hold_machine(Some("automatic retry".into()));
4611        legacy.release();
4612        assert!(legacy.resumption.is_none());
4613        assert!(legacy.resumption_history.is_empty());
4614        assert!(legacy.operator_decided_at.is_none());
4615        legacy.release_operator("cli", None);
4616        legacy.start("run".into());
4617        let reloaded: Task =
4618            serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4619        assert!(reloaded.resume_override.is_none());
4620        assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
4621    }
4622
4623    #[test]
4624    fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
4625        let mut base = RunOverrides {
4626            merge: Some("pr".to_owned()),
4627            candidates: Some(3),
4628            ..RunOverrides::default()
4629        };
4630        base.merge_over(&RunOverrides {
4631            merge: Some("none".to_owned()),
4632            seed: Some(7),
4633            ..RunOverrides::default()
4634        });
4635        assert_eq!(base.merge.as_deref(), Some("none"));
4636        assert_eq!(base.candidates, Some(3));
4637        assert_eq!(base.seed, Some(7));
4638    }
4639
4640    #[test]
4641    fn an_already_landed_task_is_done_with_its_attempt_refunded() {
4642        let mut t = task("relanded");
4643        t.attempts = 1;
4644        t.status = TaskStatus::Running;
4645        t.already_landed("already in main as 0e368de", completion(&t));
4646        assert_eq!(t.status, TaskStatus::Done);
4647        assert_eq!(t.attempts, 0);
4648        assert!(t.hold_reason.is_none());
4649        assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
4650    }
4651
4652    #[test]
4653    fn missing_blocker_reason_follows_the_language() {
4654        let b = vec!["a".to_owned()];
4655        let en = missing_blocker_hold_reason_in(&b, &b, "en");
4656        assert_eq!(en, missing_blocker_hold_reason(&b, &b));
4657        assert!(en.starts_with("blocked on a"));
4658        assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
4659        assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
4660    }
4661
4662    use super::*;
4663
4664    fn completion(task: &Task) -> CompletionContext {
4665        CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
4666    }
4667
4668    #[test]
4669    fn completion_retains_the_hold_dependency_and_failure_it_clears() {
4670        let mut held = task("held evidence");
4671        held.hold_manual(Some("owner approval required".into()));
4672        held.last_error = Some("review budget exhausted".into());
4673        held.succeed(completion(&held));
4674        let event = held.completion_history.last().unwrap();
4675        assert_eq!(event.prior_status, TaskStatus::Held);
4676        assert_eq!(
4677            event.prior_hold_reason.as_deref(),
4678            Some("owner approval required")
4679        );
4680        assert_eq!(
4681            event.prior_error.as_deref(),
4682            Some("review budget exhausted")
4683        );
4684        assert!(held.hold_reason.is_none());
4685        assert!(held.last_error.is_none());
4686        let mut blocked = task("dependency evidence");
4687        blocked.block(
4688            vec!["dependency".into()],
4689            Some("waiting on migration".into()),
4690        );
4691        blocked.succeed(completion(&blocked));
4692        let event = blocked.completion_history.last().unwrap();
4693        assert_eq!(event.prior_status, TaskStatus::Blocked);
4694        assert_eq!(
4695            event.prior_block_reason.as_deref(),
4696            Some("waiting on migration")
4697        );
4698        assert!(blocked.block_reason.is_none());
4699        assert!(blocked.blocked_by.is_empty());
4700        let saved = serde_json::to_vec(&held).unwrap();
4701        let restored: Task = serde_json::from_slice(&saved).unwrap();
4702        assert_eq!(restored.completion_history, held.completion_history);
4703    }
4704
4705    #[test]
4706    fn completion_audit_is_append_only_under_stale_puts() {
4707        let dir = tempfile::tempdir().unwrap();
4708        let queue = Queue::at(dir.path().join("queue"));
4709        let mut current = task("audited");
4710        current.hold_manual(Some("inspect".into()));
4711        queue.put(&mut current).unwrap();
4712        let mut stale = queue.get(&current.id).unwrap();
4713        current.succeed(completion(&current));
4714        queue.put(&mut current).unwrap();
4715        let original = current.completion_history[0].clone();
4716        stale.last_error = Some("stale control state".into());
4717        queue.put(&mut stale).unwrap();
4718        assert_eq!(stale.status, TaskStatus::Done);
4719        assert_eq!(stale.completion_history, vec![original.clone()]);
4720        let mut context = completion(&current);
4721        context.reason = Some("not actually finished".into());
4722        current.reopen(context).unwrap();
4723        queue.put(&mut current).unwrap();
4724        stale.completion_history[0].actor = CompletionActor::Web;
4725        stale.completion_history[0].reason = Some("rewritten evidence".into());
4726        queue.put(&mut stale).unwrap();
4727        assert_eq!(stale.status, TaskStatus::Held);
4728        assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
4729        assert_eq!(stale.completion_history[0], original);
4730        assert_eq!(stale.completion_history, current.completion_history);
4731    }
4732
4733    #[test]
4734    fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
4735        let (_dir, q) = queue();
4736        let mut current = task("durable receipts");
4737        q.put(&mut current).unwrap();
4738        let mut stale = current.clone();
4739        let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
4740            "request": {
4741                "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
4742                "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
4743            },
4744            "at": stale.updated_at, "contract": "old-contract"
4745        }))
4746        .unwrap();
4747        stale.release_operator("triage", Some("triage-question"));
4748        stale.queue_repair(&grant);
4749        let reconciliation: crate::repair_budget::reconcile::Receipt =
4750            serde_json::from_value(serde_json::json!({
4751                "request": {
4752                    "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
4753                    "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
4754                    "request": "reconciliation", "reason": "retain the answer"
4755                },
4756                "grant": grant, "source": "answer", "application": "release",
4757                "decision": grant.at, "superseded_questions": []
4758            }))
4759            .unwrap();
4760        stale.repair_reconciliations.push(reconciliation.clone());
4761        stale.triage_applied.push("triage-question".into());
4762        stale.actions_applied.push("choice".into());
4763        stale.base_recovery_requests.push("base-request".into());
4764        stale.chat_notices.push("delivery".into());
4765        stale.chat_notice = Some(ChatNotice {
4766            key: "other-delivery".into(),
4767            at: grant.at,
4768            outcome: ChatNoticeOutcome::Posted,
4769        });
4770        for ledger in [
4771            &mut stale.decision_effects,
4772            &mut stale.dispatched_resumes,
4773            &mut stale.superseded_resumes,
4774        ] {
4775            ledger.insert("shared".into(), "stale".into());
4776            ledger.insert("only-stale".into(), "receipt".into());
4777        }
4778
4779        let mut latest_grant = grant.clone();
4780        latest_grant.request.request = "new-grant".into();
4781        current.queue_repair(&latest_grant);
4782        for ledger in [
4783            &mut current.decision_effects,
4784            &mut current.dispatched_resumes,
4785            &mut current.superseded_resumes,
4786        ] {
4787            ledger.insert("shared".into(), "committed".into());
4788        }
4789        current.succeed(completion(&current));
4790        let mut context = completion(&current);
4791        context.reason = Some("inspect again".into());
4792        current.reopen(context).unwrap();
4793        q.put(&mut current).unwrap();
4794
4795        for _ in 0..2 {
4796            q.put(&mut stale.clone()).unwrap();
4797            let saved = q.get(&current.id).unwrap();
4798            assert_eq!(saved.status, TaskStatus::Held);
4799            assert_eq!(saved.hold_reason, current.hold_reason);
4800            assert_eq!(saved.operator_decided_at, current.operator_decided_at);
4801            assert_eq!(saved.completion_history, current.completion_history);
4802            assert!(saved.resume_override.is_none());
4803            assert!(saved.resumption.is_none());
4804            assert_eq!(
4805                saved.resumption_history,
4806                [stale.resumption.clone().unwrap()]
4807            );
4808            assert_eq!(saved.triage_applied, ["triage-question"]);
4809            assert_eq!(saved.actions_applied, ["choice"]);
4810            assert_eq!(saved.base_recovery_requests, ["base-request"]);
4811            assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
4812            assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
4813            assert_eq!(
4814                saved.repair_reconciliations,
4815                std::slice::from_ref(&reconciliation)
4816            );
4817            for ledger in [
4818                saved.decision_effects,
4819                saved.dispatched_resumes,
4820                saved.superseded_resumes,
4821            ] {
4822                assert_eq!(ledger["shared"], "committed");
4823                assert_eq!(ledger["only-stale"], "receipt");
4824            }
4825        }
4826    }
4827
4828    #[test]
4829    fn repeated_completion_only_notifies_for_new_occurrences() {
4830        let mut task = chat_task();
4831        task.succeed(completion(&task));
4832        let first = task.chat_notice_key().unwrap();
4833        task.chat_notices.push(first.clone());
4834        task.succeed(completion(&task));
4835        assert_eq!(task.completion_history.len(), 1, "idempotent while done");
4836        assert_eq!(task.chat_notice_due(), None);
4837        let mut context = completion(&task);
4838        context.reason = Some("inspect".into());
4839        task.reopen(context).unwrap();
4840        task.succeed(completion(&task));
4841        let second = task.chat_notice_key().unwrap();
4842        assert_ne!(first, second);
4843        assert_eq!(task.chat_notice_due(), Some(second));
4844        assert_eq!(task.completion_history.len(), 3);
4845    }
4846
4847    #[test]
4848    fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
4849        let mut task = task("legacy");
4850        task.status = TaskStatus::Done;
4851        let mut value = serde_json::to_value(&task).unwrap();
4852        value.as_object_mut().unwrap().remove("completion_history");
4853        let task: Task = serde_json::from_value(value).unwrap();
4854        assert!(task.completion_history.is_empty());
4855        assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
4856    }
4857
4858    #[test]
4859    fn triage_applied_survives_release_and_old_records_read_as_empty() {
4860        let mut t = Task::new(
4861            "t".to_owned(),
4862            "i".to_owned(),
4863            PathBuf::from("r"),
4864            Source::Human,
4865        );
4866        t.mark_triage_applied("q1");
4867        t.mark_triage_applied("q1");
4868        t.hold_machine(Some("x".to_owned()));
4869        t.release();
4870        assert_eq!(t.triage_applied, ["q1"]);
4871        assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
4872
4873        let mut v = serde_json::to_value(&t).unwrap();
4874        v.as_object_mut().unwrap().remove("triage_applied");
4875        let old: Task = serde_json::from_value(v).unwrap();
4876        assert!(old.triage_applied.is_empty());
4877    }
4878
4879    #[test]
4880    fn task_counts_of_empty_is_all_zero() {
4881        assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
4882    }
4883
4884    #[test]
4885    fn task_counts_of_tallies_every_status() {
4886        let mut queued = Task::new(
4887            "q".to_owned(),
4888            "i".to_owned(),
4889            PathBuf::from("."),
4890            Source::Human,
4891        );
4892        queued.status = TaskStatus::Queued;
4893        let mut running = queued.clone();
4894        running.status = TaskStatus::Running;
4895        let mut done = queued.clone();
4896        done.status = TaskStatus::Done;
4897        let mut failed = queued.clone();
4898        failed.status = TaskStatus::Failed;
4899        let mut held = queued.clone();
4900        held.status = TaskStatus::Held;
4901        let mut blocked = queued.clone();
4902        blocked.status = TaskStatus::Blocked;
4903
4904        let mut parked = queued.clone();
4905        parked.status = TaskStatus::Parked;
4906
4907        let counts = TaskCounts::of(&[
4908            queued,
4909            running,
4910            done.clone(),
4911            done,
4912            failed,
4913            held,
4914            blocked,
4915            parked,
4916        ]);
4917        assert_eq!(
4918            counts,
4919            TaskCounts {
4920                queued: 1,
4921                running: 1,
4922                done: 2,
4923                failed: 1,
4924                held: 1,
4925                blocked: 1,
4926                parked: 1,
4927            }
4928        );
4929    }
4930
4931    #[test]
4932    fn task_implementers_persist_normalized_without_losing_history() {
4933        let (_dir, q) = queue();
4934        let mut t = task("keep me");
4935        t.hold_manual(Some("waiting".into()));
4936        t.runs.push("earlier-run".into());
4937        t.attachments.push("reference.txt".into());
4938        let cfg: crate::config::Config =
4939            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
4940                .unwrap();
4941        q.put(&mut t).unwrap();
4942        let original = serde_json::to_value(&t).unwrap();
4943        for n in [2, 1, 2] {
4944            t.set_implementers(n, &cfg).unwrap();
4945            q.put(&mut t).unwrap();
4946            t = q.get(&t.id).unwrap();
4947            assert_eq!(t.implementers(), Some(usize::from(n)));
4948            assert_eq!(t.solo, n == 1);
4949            if n == 1 {
4950                assert!(t.overrides.is_none());
4951            }
4952            let mut actual = serde_json::to_value(&t).unwrap();
4953            for field in ["solo", "overrides", "updated_at"] {
4954                actual[field] = original[field].clone();
4955            }
4956            assert_eq!(actual, original);
4957        }
4958        t.overrides.as_mut().unwrap().judges = Some(2);
4959        t.set_implementers(1, &cfg).unwrap();
4960        assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
4961        assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
4962    }
4963
4964    #[test]
4965    fn task_implementers_old_records_keep_inheritance_until_changed() {
4966        let mut value = serde_json::to_value(task("old task")).unwrap();
4967        value.as_object_mut().unwrap().remove("solo");
4968        value.as_object_mut().unwrap().remove("overrides");
4969        let mut old: Task = serde_json::from_value(value).unwrap();
4970        assert_eq!(old.implementers(), None);
4971        old.set_implementers(1, &crate::config::Config::default())
4972            .unwrap();
4973        assert!(old.solo);
4974        assert!(old.overrides.is_none());
4975    }
4976
4977    #[test]
4978    fn task_implementers_reject_invalid_counts_and_states() {
4979        let cfg = crate::config::Config::default();
4980        let mut t = task("unchanged");
4981        for n in [0, 4, 255] {
4982            assert!(t.set_implementers(n, &cfg).is_err());
4983        }
4984        for status in [
4985            TaskStatus::Running,
4986            TaskStatus::Done,
4987            TaskStatus::Failed,
4988            TaskStatus::Blocked,
4989            TaskStatus::Parked,
4990        ] {
4991            t.status = status;
4992            let before = serde_json::to_value(&t).unwrap();
4993            assert!(t.set_implementers(1, &cfg).is_err());
4994            assert_eq!(serde_json::to_value(&t).unwrap(), before);
4995        }
4996    }
4997
4998    /// A queue of its own, with no process-global state - which is the point of
4999    /// `Queue::at`, and why these can run in parallel.
5000    fn queue() -> (tempfile::TempDir, Queue) {
5001        let dir = tempfile::tempdir().unwrap();
5002        let q = Queue::at(dir.path().join("queue"));
5003        (dir, q)
5004    }
5005
5006    #[test]
5007    fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5008        let (_dir, q) = queue();
5009        let mut original = task("base recovery");
5010        original
5011            .decision_effects
5012            .insert("old-effect".into(), "receipt".into());
5013        original
5014            .dispatched_resumes
5015            .insert("dispatched".into(), "prior-run".into());
5016        original.resume_override = Some(OperatorResume {
5017            question_id: "prior-decision".into(),
5018            at: Timestamp::now(),
5019            conductor_rehold: None,
5020            forced: true,
5021            pinned_run: Some("retained-run".into()),
5022        });
5023        q.put(&mut original).unwrap();
5024        let expected = serde_json::to_value(&original).unwrap();
5025        let mut recovered = original.clone();
5026        recovered.base_recovery_requests.push("chat/request".into());
5027        recovered
5028            .resume_override
5029            .as_mut()
5030            .unwrap()
5031            .question_id
5032            .clear();
5033        q.commit_base_recovery(&mut recovered, &expected).unwrap();
5034        let saved = q.get(&original.id).unwrap();
5035        assert_eq!(saved.decision_effects, original.decision_effects);
5036        assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5037        assert_eq!(
5038            saved
5039                .superseded_resumes
5040                .get("prior-decision")
5041                .map(String::as_str),
5042            Some("retained-run")
5043        );
5044        assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5045        assert!(saved.resume_override.unwrap().question_id.is_empty());
5046        assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5047    }
5048
5049    #[test]
5050    fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5051        let (_dir, q) = queue();
5052        let mut stale = task("chat");
5053        q.put(&mut stale).unwrap();
5054        let mut fresh = q.get(&stale.id).unwrap();
5055        fresh.chat = Some("talk-1".to_owned());
5056        q.put(&mut fresh).unwrap();
5057        q.put(&mut stale).unwrap();
5058        assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5059    }
5060
5061    #[test]
5062    fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5063        let dir = tempfile::tempdir().unwrap();
5064        let q = Queue::at(dir.path().join("queue"));
5065        let mut t = task("held");
5066        q.put(&mut t).unwrap();
5067        assert_eq!(
5068            crate::notices::Notices::at(dir.path().join("notifications"))
5069                .list()
5070                .len(),
5071            0
5072        );
5073        t.hold_machine(Some("out of attempts".to_owned()));
5074        q.put(&mut t).unwrap();
5075        let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5076        assert_eq!(listed.len(), 1);
5077        assert!(listed[0].message.contains("out of attempts"));
5078    }
5079
5080    #[test]
5081    fn start_consumes_the_disk_resume_pin() {
5082        let mut t = task("pin");
5083        t.disk_resume_run = Some("run-1".into());
5084        t.start("run-1".into());
5085        assert!(t.disk_resume_run.is_none());
5086    }
5087
5088    fn task(title: &str) -> Task {
5089        Task::new(
5090            title.to_owned(),
5091            format!("do {title}"),
5092            PathBuf::from("."),
5093            Source::Human,
5094        )
5095    }
5096
5097    #[test]
5098    fn attempt_limit_inherits_old_records_and_controls_failure() {
5099        let mut t = task("budget");
5100        let mut old = serde_json::to_value(&t).unwrap();
5101        old.as_object_mut().unwrap().remove("attempt_limit");
5102        old["schema"] = serde_json::json!(15);
5103        let legacy: Task = serde_json::from_value(old).unwrap();
5104        assert_eq!(legacy.attempt_limit, None);
5105        assert_eq!(legacy.effective_attempt_limit(2), 2);
5106        t.attempts = 2;
5107        t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5108        t.fail("retry", 1);
5109        assert_eq!(t.status, TaskStatus::Failed);
5110        t.attempts = 3;
5111        t.fail("stop", 10);
5112        assert_eq!(t.status, TaskStatus::Held);
5113        t.change_attempt_limit(None).unwrap();
5114        assert_eq!(t.status, TaskStatus::Held);
5115        assert_eq!(t.attempts, 3);
5116        t.fail("inherit", 4);
5117        assert_eq!(t.status, TaskStatus::Failed);
5118        for status in [
5119            TaskStatus::Running,
5120            TaskStatus::Done,
5121            TaskStatus::Failed,
5122            TaskStatus::Blocked,
5123            TaskStatus::Parked,
5124        ] {
5125            t.status = status;
5126            assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5127            assert_eq!(t.attempt_limit, None);
5128        }
5129    }
5130
5131    #[test]
5132    fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5133        let mut t = task("retried");
5134        assert!(
5135            t.earlier_attempts().is_empty(),
5136            "a first attempt takes nothing over"
5137        );
5138        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5139        assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5140        // What the web note shows and what a takeover acts on are one rule.
5141        assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5142        assert_eq!(t.successor_of("bbbb"), None);
5143        assert_eq!(t.successor_of("zzzz"), None);
5144    }
5145
5146    #[test]
5147    fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5148        let (_dir, q) = queue();
5149        let mut t = task("resumed");
5150        for (runs, successor) in [
5151            (vec!["aaaa", "aaaa"], None),
5152            (vec!["aaaa", "bbbb", "aaaa"], None),
5153            (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5154            (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5155        ] {
5156            t.runs = runs.into_iter().map(str::to_owned).collect();
5157            q.put(&mut t).unwrap();
5158
5159            assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5160            assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5161            assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5162        }
5163    }
5164
5165    #[test]
5166    fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5167        let (_dir, q) = queue();
5168        let mut t = task("retried");
5169        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5170        q.put(&mut t).unwrap();
5171
5172        assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5173        assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5174        assert_eq!(
5175            q.superseded_by("cccc"),
5176            None,
5177            "the latest attempt replaces nothing"
5178        );
5179        assert_eq!(
5180            q.superseded_by("never-heard-of-it"),
5181            None,
5182            "a run belonging to no task on this queue is not superseded"
5183        );
5184
5185        let mut by = HashMap::new();
5186        by.insert("aaaa".to_owned(), "bbbb".to_owned());
5187        by.insert("bbbb".to_owned(), "cccc".to_owned());
5188        assert_eq!(
5189            q.superseded(),
5190            by,
5191            "the whole-map and single-run forms must agree"
5192        );
5193    }
5194
5195    #[test]
5196    fn superseded_attempts_is_empty_until_the_task_is_done() {
5197        let mut t = task("retried");
5198        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5199        t.status = TaskStatus::Failed;
5200        assert_eq!(
5201            t.superseded_attempts(true),
5202            &[] as &[String],
5203            "a task still retrying has no attempt yet that a later one made moot"
5204        );
5205
5206        t.status = TaskStatus::Running;
5207        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5208    }
5209
5210    #[test]
5211    fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5212        let mut t = task("retried");
5213        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5214        t.status = TaskStatus::Done;
5215        assert_eq!(
5216            t.superseded_attempts(true),
5217            &["aaaa".to_owned(), "bbbb".to_owned()],
5218            "cccc is the attempt whose success made the task done, and stays out"
5219        );
5220    }
5221
5222    #[test]
5223    fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5224        let mut t = task("first try landed");
5225        t.runs = vec!["aaaa".to_owned()];
5226        t.status = TaskStatus::Done;
5227        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5228    }
5229
5230    #[test]
5231    fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5232        // `succeed` is reachable directly - `magi task done`, its web
5233        // equivalent, and the conductor's `Recovery::Done` - on a task in
5234        // any status, including one whose last recorded attempt is itself
5235        // `Blocked`/`Failed`/anything but `Merged`/`Ready`. `runs.last()`
5236        // alone cannot tell that apart from the loop's own settle path, so
5237        // the caller's own read of that run's status is what decides this.
5238        let mut t = task("closed by hand after a manual merge");
5239        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5240        t.status = TaskStatus::Done;
5241        assert_eq!(
5242            t.superseded_attempts(false),
5243            &[] as &[String],
5244            "nothing here is provably why the task is done, so nothing is superseded"
5245        );
5246    }
5247
5248    #[test]
5249    fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5250        let (_dir, q) = queue();
5251        let mut t = task("retried twice");
5252        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5253        q.put(&mut t).unwrap();
5254
5255        assert_eq!(
5256            q.latest_attempt("aaaa"),
5257            Some("cccc".to_owned()),
5258            "an old attempt points straight at the chain's current head, not the \
5259             next attempt in the middle of it"
5260        );
5261        assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5262        assert_eq!(
5263            q.latest_attempt("cccc"),
5264            None,
5265            "the latest attempt is not superseded by anything"
5266        );
5267        assert_eq!(
5268            q.latest_attempt("never-heard-of-it"),
5269            None,
5270            "a run belonging to no task on this queue is not superseded"
5271        );
5272    }
5273
5274    #[test]
5275    fn a_markdown_heading_is_the_title_not_decoration() {
5276        // A task file's heading is the summary its author already wrote, so it
5277        // beats the prose underneath. Getting this backwards was visible in the
5278        // first smoke test: a task titled "# Rework the config loader" listed
5279        // as "It re-reads the file on every lookup".
5280        assert_eq!(
5281            title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5282            "Rework the config loader"
5283        );
5284        assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5285        assert_eq!(title_from("> quoted task", 40), "quoted task");
5286        // Nothing usable at all still has to produce something printable.
5287        assert_eq!(title_from("   \n\n", 40), "(empty task)");
5288        assert_eq!(title_from("###\n", 40), "(empty task)");
5289    }
5290
5291    #[test]
5292    fn a_long_title_is_elided_by_characters_not_bytes() {
5293        // Byte truncation would split a multi-byte character and panic.
5294        let long = "課題".repeat(30);
5295        let title = title_from(&long, 10);
5296        assert_eq!(title.chars().count(), 10);
5297        assert!(title.ends_with('…'));
5298    }
5299
5300    #[test]
5301    fn priority_wins_and_ties_break_oldest_first() {
5302        let (_dir, q) = queue();
5303        let mut a = task("first");
5304        let mut b = task("second");
5305        let mut c = task("urgent");
5306        // Ids carry a timestamp, so force a known order.
5307        a.id = "20260101-000001-aaaa".to_owned();
5308        b.id = "20260101-000002-bbbb".to_owned();
5309        c.id = "20260101-000003-cccc".to_owned();
5310        c.priority = 5;
5311        for t in [&mut a, &mut b, &mut c] {
5312            q.put(t).unwrap();
5313        }
5314
5315        // Priority first...
5316        assert_eq!(q.next_runnable().unwrap().id, c.id);
5317        c.hold_machine(None);
5318        q.put(&mut c).unwrap();
5319        // ...then oldest, so a burst of new work cannot starve older work.
5320        assert_eq!(q.next_runnable().unwrap().id, a.id);
5321        assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5322    }
5323
5324    #[test]
5325    fn a_blocked_task_never_starves_another_runnable_one() {
5326        let (_dir, q) = queue();
5327        let mut blocked = task("blocked");
5328        blocked.block(vec!["something".to_owned()], None);
5329        q.put(&mut blocked).unwrap();
5330
5331        let mut runnable = task("free to go");
5332        q.put(&mut runnable).unwrap();
5333
5334        let next = q.next_runnable().expect("a runnable task is still offered");
5335        assert_eq!(next.id, runnable.id);
5336    }
5337
5338    #[test]
5339    fn a_held_task_is_never_offered_to_the_loop() {
5340        let (_dir, q) = queue();
5341        let mut t = task("held");
5342        q.put(&mut t).unwrap();
5343        assert!(q.next_runnable().is_some());
5344
5345        t.hold_machine(None);
5346        q.put(&mut t).unwrap();
5347        assert!(
5348            q.next_runnable().is_none(),
5349            "a held task must wait for a human"
5350        );
5351
5352        // A failed task, by contrast, is exactly what the loop should retry.
5353        t.status = TaskStatus::Failed;
5354        q.put(&mut t).unwrap();
5355        assert!(q.next_runnable().is_some());
5356    }
5357
5358    #[test]
5359    fn attempts_are_capped_and_then_the_task_is_held() {
5360        let mut t = task("doomed");
5361
5362        t.start("run-1".to_owned());
5363        t.fail("gate red", 2);
5364        assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5365
5366        t.start("run-2".to_owned());
5367        t.fail("gate red", 2);
5368        assert_eq!(
5369            t.status,
5370            TaskStatus::Held,
5371            "out of attempts: stop spending money on it"
5372        );
5373        assert_eq!(t.runs, ["run-1", "run-2"]);
5374        assert_eq!(t.last_error.as_deref(), Some("gate red"));
5375        assert_eq!(
5376            t.hold_reason.as_deref(),
5377            Some("gate red"),
5378            "the hold must say why, not leave hold_reason null next to a \
5379             populated last_error"
5380        );
5381    }
5382
5383    #[test]
5384    fn handing_off_a_task_records_a_hold_reason_too() {
5385        let mut t = task("left a pull request");
5386        t.start("run-1".to_owned());
5387        t.handed_off("run ended with a pull request open [run run-1]");
5388        assert_eq!(t.status, TaskStatus::Held);
5389        assert_eq!(t.hold_source, Some(HoldSource::Machine));
5390        assert_eq!(
5391            t.hold_reason.as_deref(),
5392            Some("run ended with a pull request open [run run-1]")
5393        );
5394        assert_eq!(t.hold_reason, t.last_error);
5395    }
5396
5397    #[test]
5398    fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5399        let mut t = task("stalled by quota");
5400
5401        t.start("run-1".to_owned());
5402        assert_eq!(t.attempts, 1);
5403        t.stall("judge-1, judge-2 out of quota");
5404        assert_eq!(
5405            t.attempts, 0,
5406            "a closed quota window must not spend the task's retry budget"
5407        );
5408        assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5409        assert_eq!(
5410            t.last_error.as_deref(),
5411            Some("judge-1, judge-2 out of quota")
5412        );
5413
5414        // A task can therefore stall all night and still get its real attempts
5415        // once the quota resets - which is the whole point.
5416        for _ in 0..20 {
5417            t.start("run-n".to_owned());
5418            t.stall("still out of quota");
5419        }
5420        t.start("run-real".to_owned());
5421        t.fail("gate red", 2);
5422        assert_eq!(
5423            t.status,
5424            TaskStatus::Failed,
5425            "the first attempt that was really judged is attempt one"
5426        );
5427    }
5428
5429    #[test]
5430    fn releasing_a_held_task_gives_it_a_real_second_chance() {
5431        let mut t = task("retry me");
5432        t.start("run-1".to_owned());
5433        t.fail("gate red", 1);
5434        assert_eq!(t.status, TaskStatus::Held);
5435
5436        t.release();
5437        assert_eq!(t.status, TaskStatus::Queued);
5438        // Without resetting attempts the next failure would re-hold at once,
5439        // and a release would be a no-op the operator cannot see.
5440        assert_eq!(t.attempts, 0);
5441        assert!(t.last_error.is_none());
5442        assert_eq!(
5443            t.runs.len(),
5444            1,
5445            "history is kept: attempts reset, evidence does not"
5446        );
5447    }
5448
5449    #[test]
5450    fn a_hold_reason_survives_and_a_release_clears_it() {
5451        let mut t = task("waiting on something else");
5452        t.hold_manual(Some(
5453            "waiting for 20260101-000000-aaaa to land first".to_owned(),
5454        ));
5455        assert_eq!(t.status, TaskStatus::Held);
5456        assert_eq!(
5457            t.hold_reason.as_deref(),
5458            Some("waiting for 20260101-000000-aaaa to land first")
5459        );
5460
5461        // Holding again with no reason must not erase the one already there.
5462        t.hold_manual(None);
5463        assert_eq!(
5464            t.hold_reason.as_deref(),
5465            Some("waiting for 20260101-000000-aaaa to land first"),
5466            "a bare re-hold keeps whatever a human already wrote down"
5467        );
5468
5469        // A hold with no reason at all is still an ordinary, allowed hold.
5470        let mut plain = task("no reason given");
5471        plain.hold_manual(None);
5472        assert_eq!(plain.status, TaskStatus::Held);
5473        assert!(plain.hold_reason.is_none());
5474
5475        t.release();
5476        assert_eq!(t.status, TaskStatus::Queued);
5477        assert!(
5478            t.hold_reason.is_none(),
5479            "a stale reason must not greet the next person who holds this task"
5480        );
5481    }
5482
5483    #[test]
5484    fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5485        // `done` can close a held task directly - neither `magi task done`
5486        // nor `POST /api/queue/{id}/done` requires a release first - so a
5487        // task held for "waiting on 3ed9" and then closed without ever being
5488        // released must not still read as waiting on it afterwards.
5489        let mut t = task("landed by hand while held");
5490        t.hold_manual(Some("waiting on 3ed9".to_owned()));
5491        assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5492
5493        t.succeed(completion(&t));
5494        assert_eq!(t.status, TaskStatus::Done);
5495        assert!(
5496            t.hold_reason.is_none(),
5497            "a done task cannot still be waiting on something"
5498        );
5499    }
5500
5501    #[test]
5502    fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5503        // The web UI's "Hold" and "Mark done" buttons are both reachable on a
5504        // `blocked` task, not just on `queued`/`held` ones - neither requires
5505        // a release first. A task moved off `Blocked` that way must not still
5506        // carry the dependency it was waiting on: a dependency graph built
5507        // from `blocked_by` would otherwise keep drawing an edge for a task
5508        // that is not blocked on anything any more.
5509        let mut held = task("held straight out of blocked");
5510        held.block(
5511            vec!["20260101-000000-dead".to_owned()],
5512            Some("waiting on the migration script".to_owned()),
5513        );
5514        assert_eq!(held.status, TaskStatus::Blocked);
5515
5516        held.hold_manual(None);
5517        assert_eq!(held.status, TaskStatus::Held);
5518        assert!(
5519            held.blocked_by.is_empty(),
5520            "hold overrides the wait, same as release"
5521        );
5522        assert!(held.block_reason.is_none());
5523
5524        let mut done = task("closed straight out of blocked");
5525        done.block(
5526            vec!["20260101-000000-dead".to_owned()],
5527            Some("waiting on the migration script".to_owned()),
5528        );
5529        done.succeed(completion(&done));
5530        assert_eq!(done.status, TaskStatus::Done);
5531        assert!(
5532            done.blocked_by.is_empty(),
5533            "a done task cannot still be waiting on a dependency"
5534        );
5535        assert!(done.block_reason.is_none());
5536    }
5537
5538    #[test]
5539    fn a_blocked_task_is_never_offered_to_the_loop() {
5540        let mut t = task("blocked");
5541        assert!(t.status.runnable());
5542        t.block(
5543            vec!["dep-id".to_owned()],
5544            Some("waits on dep-id".to_owned()),
5545        );
5546        assert_eq!(t.status, TaskStatus::Blocked);
5547        assert!(!t.status.runnable());
5548        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5549    }
5550
5551    #[test]
5552    fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5553        let mut t = task("blocked on two");
5554        t.block(
5555            vec!["a".to_owned(), "b".to_owned()],
5556            Some("waits on a and b".to_owned()),
5557        );
5558
5559        t.unblock("a");
5560        assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5561        assert_eq!(t.blocked_by, ["b"]);
5562
5563        t.unblock("b");
5564        assert_eq!(t.status, TaskStatus::Queued);
5565        assert!(t.blocked_by.is_empty());
5566        assert!(t.block_reason.is_none());
5567    }
5568
5569    #[test]
5570    fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5571        let mut t = task("never blocked");
5572        t.unblock("whatever");
5573        assert_eq!(t.status, TaskStatus::Queued);
5574    }
5575
5576    #[test]
5577    fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
5578        // The bug this guards: a task an operator (or `crate::triage`) has
5579        // deliberately held, once `crate::conduct` blocks it on a follow-up
5580        // question, must not silently re-enter the competition queue the
5581        // moment that question is answered - whatever the answer said.
5582        let mut t = task("held, then asked about");
5583        t.hold_machine(Some("out of attempts".to_owned()));
5584        assert_eq!(t.status, TaskStatus::Held);
5585
5586        t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
5587        assert_eq!(t.status, TaskStatus::Blocked);
5588
5589        t.record_answer("what now?".to_owned(), "leave it held".to_owned());
5590        t.unblock("q1");
5591        assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
5592        assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
5593        assert_eq!(t.hold_source, Some(HoldSource::Machine));
5594        assert!(t.blocked_from.is_none(), "consumed once restored");
5595    }
5596
5597    #[test]
5598    fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
5599        let mut t = task("manually held, then asked about");
5600        t.hold_manual(Some("waiting on a dependency".to_owned()));
5601
5602        t.block(vec!["q1".to_owned()], None);
5603        t.unblock("q1");
5604
5605        assert_eq!(t.status, TaskStatus::Held);
5606        assert_eq!(t.hold_source, Some(HoldSource::Manual));
5607    }
5608
5609    #[test]
5610    fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
5611        // A second `Task::block` call - `crate::conduct` adding a question on
5612        // top of an existing block - must not overwrite `blocked_from` with
5613        // `Blocked` itself, or the task would restore into itself.
5614        let mut t = task("held, blocked twice");
5615        t.hold_machine(None);
5616        t.block(vec!["q1".to_owned()], Some("first".to_owned()));
5617        t.block(
5618            vec!["q1".to_owned(), "q2".to_owned()],
5619            Some("second".to_owned()),
5620        );
5621
5622        t.unblock("q1");
5623        assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
5624        t.unblock("q2");
5625        assert_eq!(t.status, TaskStatus::Held);
5626    }
5627
5628    #[test]
5629    fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
5630        // Whatever process was driving the run is gone by the time a
5631        // conductor's question about it gets answered - there is nothing left
5632        // to resume into.
5633        let mut t = task("blocked mid-run");
5634        t.start("run-1".to_owned());
5635        assert_eq!(t.status, TaskStatus::Running);
5636
5637        t.block(vec!["q1".to_owned()], None);
5638        t.unblock("q1");
5639        assert_eq!(t.status, TaskStatus::Queued);
5640    }
5641
5642    #[test]
5643    fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
5644        // `blocked_from` is `None` for a record written before schema 4 (or,
5645        // equivalently, deserialized straight from an on-disk file that never
5646        // had the field). Held evidence surviving on the task - never cleared
5647        // by `block` - is the only way left to tell such a record apart from
5648        // one blocked straight out of `Queued`.
5649        let mut t = task("legacy record, held before it was blocked");
5650        t.hold_source = Some(HoldSource::Machine);
5651        t.hold_reason = Some("legacy hold reason".to_owned());
5652        t.status = TaskStatus::Blocked;
5653        t.blocked_by = vec!["q1".to_owned()];
5654        t.blocked_from = None;
5655
5656        t.unblock("q1");
5657        assert_eq!(t.status, TaskStatus::Held);
5658    }
5659
5660    #[test]
5661    fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
5662        let mut t = task("legacy record, ordinary dependency block");
5663        t.status = TaskStatus::Blocked;
5664        t.blocked_by = vec!["dep".to_owned()];
5665        t.blocked_from = None;
5666
5667        t.unblock("dep");
5668        assert_eq!(t.status, TaskStatus::Queued);
5669    }
5670
5671    #[test]
5672    fn answering_a_question_is_recorded_and_survives_a_release() {
5673        let mut t = task("asked something");
5674        t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
5675        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
5676        t.unblock("q1");
5677        assert_eq!(t.status, TaskStatus::Queued);
5678        assert_eq!(t.answers.len(), 1);
5679        assert_eq!(t.answers[0].answer, "SQLite");
5680
5681        // A release resets attempts, not evidence - the same rule
5682        // `releasing_a_held_task_gives_it_a_real_second_chance` asserts for
5683        // `runs`.
5684        t.release();
5685        assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
5686    }
5687
5688    #[test]
5689    fn resumption_review_branch_requires_unchanged_authored_criteria() {
5690        for source in ["cli", "web"] {
5691            let mut t = task("review old candidate");
5692            t.request_review("candidate-A".into());
5693            t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
5694            let mut unchanged = t.clone();
5695            unchanged.release_operator(source, None);
5696            assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
5697            t.edit(
5698                "review approved head".into(),
5699                "Reuse measured PR head B; fix Clippy; review".into(),
5700            )
5701            .unwrap();
5702            t.release_operator(source, None);
5703            assert!(t.review_branch.is_none());
5704            assert!(t.review_instruction.is_none());
5705            // Legacy records capture their old criteria at the supported edit.
5706            let mut legacy = unchanged;
5707            legacy.review_instruction = None;
5708            legacy.hold_for_handover(None, "still checked out".into());
5709            legacy
5710                .edit("new plan".into(), "Reuse measured PR head B".into())
5711                .unwrap();
5712            legacy.release_operator(source, None);
5713            assert!(legacy.review_branch.is_none());
5714        }
5715    }
5716
5717    #[test]
5718    fn a_refused_handover_keeps_the_review_branch_across_release() {
5719        let mut t = task("refused takeover");
5720        t.start("run-1".to_owned());
5721        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
5722        assert_eq!(t.status, TaskStatus::Held);
5723        assert_eq!(t.attempts, 1);
5724        t.release();
5725        assert_eq!(t.status, TaskStatus::Queued);
5726        assert_eq!(t.attempts, 0);
5727        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5728
5729        // A fresh competition chosen afterwards is not a review.
5730        t.hold_for_handover(None, "again".to_owned());
5731        t.requeue();
5732        assert!(t.review_branch.is_none());
5733
5734        // A manual hold never keeps one.
5735        let mut m = task("manual");
5736        m.review_branch = Some("magi/x/A".to_owned());
5737        m.hold_manual(None);
5738        m.release();
5739        assert!(m.review_branch.is_none());
5740    }
5741
5742    #[test]
5743    fn requesting_review_requeues_the_task_and_remembers_the_branch() {
5744        let mut t = task("blocked run with a surviving branch");
5745        t.start("run-1".to_owned());
5746        t.fail("blocked with major findings", 5);
5747        assert_eq!(t.status, TaskStatus::Failed);
5748
5749        t.request_review("magi/eba2/A".to_owned());
5750        assert_eq!(t.status, TaskStatus::Queued);
5751        assert_eq!(t.attempts, 0);
5752        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
5753
5754        // An ordinary release (a human overriding the choice) drops it again.
5755        t.release();
5756        assert!(t.review_branch.is_none());
5757    }
5758
5759    #[test]
5760    fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
5761        let mut t = task("retry");
5762        t.start("run-1".to_owned());
5763        t.requeue();
5764        assert!(t.fresh_start);
5765
5766        t.release();
5767        assert!(!t.fresh_start);
5768    }
5769
5770    #[test]
5771    fn urgent_only_changes_queued_or_held_and_preserves_settings() {
5772        for status in [
5773            TaskStatus::Queued,
5774            TaskStatus::Held,
5775            TaskStatus::Running,
5776            TaskStatus::Done,
5777            TaskStatus::Failed,
5778            TaskStatus::Blocked,
5779            TaskStatus::Parked,
5780        ] {
5781            let mut t = task("urgent settings");
5782            t.status = status;
5783            t.attempts = 2;
5784            t.hold_reason = Some("waiting".into());
5785            t.priority = 7;
5786            t.interrupt = true;
5787            let before = serde_json::to_value(&t).unwrap();
5788            for urgent in [true, true, false, false] {
5789                let result = t.set_urgent(urgent);
5790                let mut expected = before.clone();
5791                if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
5792                    result.unwrap();
5793                    expected["urgent"] = urgent.into();
5794                } else {
5795                    let error = result.unwrap_err().to_string();
5796                    assert!(error.contains(status.as_str()), "{error}");
5797                    assert!(error.contains("queued or held"), "{error}");
5798                }
5799                assert_eq!(serde_json::to_value(&t).unwrap(), expected);
5800            }
5801        }
5802    }
5803
5804    #[test]
5805    fn priority_can_be_changed_while_queued_but_not_while_running() {
5806        let mut t = task("reprioritise me");
5807        t.set_priority(5).unwrap();
5808        assert_eq!(t.priority, 5);
5809
5810        t.start("run-1".to_owned());
5811        let err = t.set_priority(9).unwrap_err().to_string();
5812        assert!(err.contains("running"), "{err}");
5813        assert_eq!(t.priority, 5, "the rejected write must not partially apply");
5814    }
5815
5816    #[test]
5817    fn interrupt_can_be_marked_while_queued_but_not_while_running() {
5818        let mut t = task("interrupt me");
5819        assert!(!t.interrupt, "off unless asked, same as any other task");
5820
5821        t.set_interrupt(true).unwrap();
5822        assert!(t.interrupt);
5823
5824        t.start("run-1".to_owned());
5825        assert!(
5826            !t.interrupt,
5827            "the mark is one-shot: dispatching the task fulfils it, \
5828             whatever the run that follows ends up doing"
5829        );
5830        let err = t.set_interrupt(true).unwrap_err().to_string();
5831        assert!(err.contains("running"), "{err}");
5832        // Clearing is always allowed, even on a running task - there is
5833        // nothing left for it to interrupt once it has been claimed.
5834        t.set_interrupt(false).unwrap();
5835        assert!(!t.interrupt);
5836    }
5837
5838    /// R2-1-1: a task whose run fails and requeues must not go on
5839    /// re-triggering `crate::daemon`'s interrupt scheduler on every later
5840    /// boundary, attempt after attempt, until it exhausts its budget.
5841    #[test]
5842    fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
5843        let mut t = task("interrupt me");
5844        t.set_interrupt(true).unwrap();
5845        t.start("run-1".to_owned());
5846        t.fail("mock failure", 5);
5847        assert_eq!(t.status, TaskStatus::Failed);
5848        assert!(
5849            !t.interrupt,
5850            "one attempt already spent the mark; a retry is an ordinary \
5851             requeue, not a fresh interrupt request"
5852        );
5853    }
5854
5855    #[test]
5856    fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
5857        let (_dir, q) = queue();
5858        let mut a = task("first filed");
5859        let mut b = task("second filed");
5860        a.id = "20260101-000001-aaaa".to_owned();
5861        b.id = "20260101-000002-bbbb".to_owned();
5862        q.put(&mut a).unwrap();
5863        q.put(&mut b).unwrap();
5864
5865        assert_eq!(
5866            q.next_runnable().unwrap().id,
5867            a.id,
5868            "with equal priority the older task goes first, so a burst of \
5869             new work cannot starve it"
5870        );
5871        assert_eq!(
5872            q.list()[0].id,
5873            b.id,
5874            "but the list an operator reads is newest first, the same as \
5875             before priority existed - a's turn to run does not make it the \
5876             newest task"
5877        );
5878
5879        let mut a = q.get(&a.id).unwrap();
5880        a.set_priority(10).unwrap();
5881        q.put(&mut a).unwrap();
5882
5883        assert_eq!(
5884            q.next_runnable().unwrap().id,
5885            a.id,
5886            "a raised priority must be reflected the moment it is saved"
5887        );
5888        // `magi task list` and `GET /api/queue` both print `Queue::list()`
5889        // directly, so the raised task has to lead there too - not only in
5890        // what the loop would claim next.
5891        assert_eq!(
5892            q.list()[0].id,
5893            a.id,
5894            "the raised task must sort first in the list an operator reads, \
5895             not only in next_runnable's own ordering"
5896        );
5897    }
5898
5899    #[test]
5900    fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
5901        let mut t = Task::new(
5902            "old title".to_owned(),
5903            "old instruction".to_owned(),
5904            PathBuf::from("/repo"),
5905            Source::Agent {
5906                run: "20260101-000000-beef".to_owned(),
5907                node: "implement".to_owned(),
5908            },
5909        );
5910        let id = t.id.clone();
5911        let created_at = t.created_at;
5912        t.runs.push("20260101-000000-beef".to_owned());
5913
5914        t.edit("new title".to_owned(), "new instruction".to_owned())
5915            .unwrap();
5916
5917        assert_eq!(t.title, "new title");
5918        assert_eq!(t.instruction, "new instruction");
5919        assert_eq!(t.id, id, "editing must not mint a new id");
5920        assert_eq!(t.created_at, created_at);
5921        assert_eq!(
5922            t.source,
5923            Source::Agent {
5924                run: "20260101-000000-beef".to_owned(),
5925                node: "implement".to_owned(),
5926            },
5927            "editing must not turn agent attribution into human"
5928        );
5929        assert_eq!(t.runs, ["20260101-000000-beef"]);
5930    }
5931
5932    #[test]
5933    fn editing_is_refused_once_a_task_is_running_or_finished() {
5934        let mut running = task("in flight");
5935        running.start("run-1".to_owned());
5936        let err = running
5937            .edit("x".to_owned(), "y".to_owned())
5938            .unwrap_err()
5939            .to_string();
5940        assert!(err.contains("running"), "{err}");
5941
5942        let mut done = task("finished");
5943        done.succeed(completion(&done));
5944        let err = done
5945            .edit("x".to_owned(), "y".to_owned())
5946            .unwrap_err()
5947            .to_string();
5948        assert!(err.contains("done"), "{err}");
5949
5950        // Both queued and held are the point of the feature and must work.
5951        let mut queued = task("waiting");
5952        queued.edit("x".to_owned(), "y".to_owned()).unwrap();
5953        let mut held = task("parked");
5954        held.hold_machine(None);
5955        held.edit("x".to_owned(), "y".to_owned()).unwrap();
5956    }
5957
5958    #[test]
5959    fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
5960        let (_dir, q) = queue();
5961        let path = q.path_of("20260101-000000-aaaa");
5962        std::fs::create_dir_all(q.root()).unwrap();
5963        std::fs::write(
5964            &path,
5965            serde_json::json!({
5966                "schema": SCHEMA,
5967                "id": "20260101-000000-aaaa",
5968                "title": "from before hold reasons existed",
5969                "instruction": "from before hold reasons existed",
5970                "repo": ".",
5971                "source": { "kind": "human" },
5972                "status": "held",
5973                "created_at": Timestamp::now().to_string(),
5974                "updated_at": Timestamp::now().to_string(),
5975            })
5976            .to_string(),
5977        )
5978        .unwrap();
5979
5980        let task = q.get("20260101-000000-aaaa").expect("must still read");
5981        assert!(task.hold_reason.is_none());
5982        assert!(task.operator_held());
5983    }
5984
5985    #[test]
5986    fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
5987        let (_dir, q) = queue();
5988        let path = q.path_of("20260101-000000-bbbb");
5989        std::fs::create_dir_all(q.root()).unwrap();
5990        std::fs::write(
5991            &path,
5992            serde_json::json!({
5993                "schema": 2,
5994                "id": "20260101-000000-bbbb",
5995                "title": "old manual recovery",
5996                "instruction": "old manual recovery",
5997                "repo": ".",
5998                "source": { "kind": "human" },
5999                "status": "held",
6000                "hold_reason": "active manual recovery run20260912-224242-daf5",
6001                "created_at": Timestamp::now().to_string(),
6002                "updated_at": Timestamp::now().to_string(),
6003            })
6004            .to_string(),
6005        )
6006        .unwrap();
6007
6008        let task = q.get("20260101-000000-bbbb").expect("must still read");
6009        assert_eq!(task.hold_source, None);
6010        assert!(task.operator_held());
6011    }
6012
6013    #[test]
6014    fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6015        let (_dir, q) = queue();
6016        let path = q.path_of("20260101-000000-aaaa");
6017        std::fs::create_dir_all(q.root()).unwrap();
6018        std::fs::write(
6019            &path,
6020            serde_json::json!({
6021                "schema": SCHEMA,
6022                "id": "20260101-000000-aaaa",
6023                "title": "from before diagnostics existed",
6024                "instruction": "from before diagnostics existed",
6025                "repo": ".",
6026                "source": { "kind": "human" },
6027                "status": "held",
6028                "created_at": Timestamp::now().to_string(),
6029                "updated_at": Timestamp::now().to_string(),
6030            })
6031            .to_string(),
6032        )
6033        .unwrap();
6034
6035        let task = q.get("20260101-000000-aaaa").expect("must still read");
6036        assert!(task.diagnostic.is_none());
6037    }
6038
6039    #[test]
6040    fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6041        // Written by a build that predates `blocked_by`, `block_reason`,
6042        // `answers` and `review_branch` entirely - literal `"schema": 1`,
6043        // not `SCHEMA`, since the whole point is a build older than this one.
6044        let (_dir, q) = queue();
6045        let path = q.path_of("20260101-000000-aaaa");
6046        std::fs::create_dir_all(q.root()).unwrap();
6047        std::fs::write(
6048            &path,
6049            serde_json::json!({
6050                "schema": 1,
6051                "id": "20260101-000000-aaaa",
6052                "title": "from before blocking existed",
6053                "instruction": "from before blocking existed",
6054                "repo": ".",
6055                "source": { "kind": "human" },
6056                "status": "queued",
6057                "created_at": Timestamp::now().to_string(),
6058                "updated_at": Timestamp::now().to_string(),
6059            })
6060            .to_string(),
6061        )
6062        .unwrap();
6063
6064        let task = q.get("20260101-000000-aaaa").expect("must still read");
6065        assert!(task.blocked_by.is_empty());
6066        assert!(task.block_reason.is_none());
6067        assert!(task.answers.is_empty());
6068        assert!(task.review_branch.is_none());
6069    }
6070
6071    #[test]
6072    fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6073        // A diagnostic belongs to the run that produced it. Left in place
6074        // across a release, an unrelated later failure - a config error, say -
6075        // would go on showing evidence for a problem that is no longer why the
6076        // task is stuck.
6077        let mut held = task("diagnosed");
6078        held.start("run-1".to_owned());
6079        held.fail("gate red", 1);
6080        held.diagnostic = Some("cargo test failed: ...".to_owned());
6081        assert_eq!(held.status, TaskStatus::Held);
6082
6083        held.release();
6084        assert!(held.diagnostic.is_none());
6085
6086        held.diagnostic = Some("cargo test failed: ...".to_owned());
6087        held.succeed(completion(&held));
6088        assert!(held.diagnostic.is_none());
6089    }
6090
6091    #[test]
6092    fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6093        let mut t = task("retried");
6094        t.start("run-1".to_owned());
6095        t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6096        t.fail("unrelated config error", 5);
6097        assert_eq!(t.status, TaskStatus::Failed);
6098        assert!(
6099            t.diagnostic.is_none(),
6100            "fail() must not let an old diagnostic outlive the run that produced it"
6101        );
6102    }
6103
6104    #[test]
6105    fn a_claim_is_exclusive_and_releases_on_drop() {
6106        let (_dir, q) = queue();
6107        let mut t = task("contended");
6108        q.put(&mut t).unwrap();
6109
6110        let held = q.claim(&t.id).unwrap();
6111        assert!(
6112            q.claim(&t.id).is_err(),
6113            "two daemons must not drive one task into two runs"
6114        );
6115        drop(held);
6116        assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6117    }
6118
6119    #[test]
6120    fn a_round_trip_survives_disk() {
6121        let (_dir, q) = queue();
6122        let mut t = Task::new(
6123            "titled".to_owned(),
6124            "body".to_owned(),
6125            PathBuf::from("/repo"),
6126            Source::Agent {
6127                run: "20260101-000000-beef".to_owned(),
6128                node: "implement".to_owned(),
6129            },
6130        );
6131        t.priority = 3;
6132        q.put(&mut t).unwrap();
6133
6134        let back = q.get(&t.id).unwrap();
6135        assert_eq!(back.id, t.id);
6136        assert_eq!(back.priority, 3);
6137        assert_eq!(back.source.label(), "implement@beef");
6138        // A prefix is enough, the way run ids work everywhere else.
6139        assert_eq!(q.get(t.short()).unwrap().id, t.id);
6140    }
6141
6142    #[test]
6143    fn an_unreadable_task_does_not_take_the_queue_down() {
6144        let (_dir, q) = queue();
6145        let mut t = task("fine");
6146        q.put(&mut t).unwrap();
6147        std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6148
6149        let listed = q.list();
6150        assert_eq!(listed.len(), 1, "the readable task still lists");
6151        assert_eq!(listed[0].id, t.id);
6152    }
6153
6154    #[test]
6155    fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6156        let (_dir, q) = queue();
6157        let path = q.path_of("20260101-000000-aaaa");
6158        std::fs::create_dir_all(q.root()).unwrap();
6159        std::fs::write(
6160            &path,
6161            serde_json::json!({
6162                "schema": SCHEMA,
6163                "id": "20260101-000000-aaaa",
6164                "title": "from before solo existed",
6165                "instruction": "from before solo existed",
6166                "repo": ".",
6167                "source": { "kind": "human" },
6168                "status": "queued",
6169                "created_at": Timestamp::now().to_string(),
6170                "updated_at": Timestamp::now().to_string(),
6171            })
6172            .to_string(),
6173        )
6174        .unwrap();
6175
6176        let task = q.get("20260101-000000-aaaa").expect("must still read");
6177        assert!(!task.solo, "a queue file with no `solo` field means false");
6178    }
6179
6180    #[test]
6181    fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6182        let (_dir, q) = queue();
6183        let path = q.path_of("20260101-000000-bbbb");
6184        std::fs::create_dir_all(q.root()).unwrap();
6185        std::fs::write(
6186            &path,
6187            serde_json::json!({
6188                "schema": SCHEMA,
6189                "id": "20260101-000000-bbbb",
6190                "title": "from before urgent existed",
6191                "instruction": "from before urgent existed",
6192                "repo": ".",
6193                "source": { "kind": "human" },
6194                "status": "queued",
6195                "created_at": Timestamp::now().to_string(),
6196                "updated_at": Timestamp::now().to_string(),
6197            })
6198            .to_string(),
6199        )
6200        .unwrap();
6201
6202        let task = q.get("20260101-000000-bbbb").expect("must still read");
6203        assert!(
6204            !task.urgent,
6205            "a queue file with no `urgent` field means false, same as `solo`"
6206        );
6207    }
6208
6209    #[test]
6210    fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6211        let (_dir, q) = queue();
6212        let mut t = task("from the future");
6213        q.put(&mut t).unwrap();
6214        let path = q.path_of(&t.id);
6215        let body = std::fs::read_to_string(&path)
6216            .unwrap()
6217            .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6218        std::fs::write(&path, body).unwrap();
6219
6220        let err = q.get(&t.id).unwrap_err().to_string();
6221        assert!(err.contains("schema 99"), "{err}");
6222    }
6223
6224    #[test]
6225    fn revision_moves_when_the_queue_changes() {
6226        let (_dir, q) = queue();
6227        assert_eq!(q.revision(), 0, "an empty queue has no revision");
6228        let mut t = task("first");
6229        q.put(&mut t).unwrap();
6230        assert!(q.revision() > 0, "a written task moves the revision");
6231    }
6232
6233    #[test]
6234    fn revision_moves_when_deleting_an_older_task() {
6235        let (dir, q) = queue();
6236        let questions = Questions::at(dir.path().join("questions"));
6237        let mut t1 = task("older");
6238        q.put(&mut t1).unwrap();
6239        // Ensure mtime ticks forward.
6240        std::thread::sleep(std::time::Duration::from_millis(10));
6241        let mut t2 = task("newer");
6242        q.put(&mut t2).unwrap();
6243
6244        let rev_before = q.revision();
6245        q.remove(&t1.id, false, &questions).unwrap();
6246        let rev_after = q.revision();
6247
6248        assert_ne!(
6249            rev_before, rev_after,
6250            "deleting an older task must change the revision so other clients see the deletion"
6251        );
6252    }
6253
6254    #[test]
6255    fn removing_a_task_takes_it_out_of_the_listing() {
6256        let (dir, q) = queue();
6257        let questions = Questions::at(dir.path().join("questions"));
6258        let mut t = task("delete me");
6259        q.put(&mut t).unwrap();
6260        let removed = q.remove(t.short(), false, &questions).unwrap();
6261        assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6262        assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6263        assert!(q.list().is_empty());
6264        assert!(
6265            q.remove(&t.id, false, &questions).is_err(),
6266            "removing twice is an error"
6267        );
6268    }
6269
6270    #[test]
6271    fn removing_a_task_takes_its_stale_lock_with_it() {
6272        let (dir, q) = queue();
6273        let questions = Questions::at(dir.path().join("questions"));
6274        let mut t = task("interrupted");
6275        q.put(&mut t).unwrap();
6276
6277        // A daemon killed mid-run leaves this behind. Nothing holds it: the
6278        // process that would have dropped the guard is gone.
6279        let claim = q.claim(&t.id).unwrap();
6280        std::mem::forget(claim);
6281        assert!(
6282            q.claim(&t.id).is_err(),
6283            "the orphaned lock is what makes the task look claimed"
6284        );
6285
6286        // A live daemon on this task is refused, whatever the lock says.
6287        let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6288        assert!(err.contains("live daemon"), "{err}");
6289        assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6290
6291        // With no daemon behind it, the lock is stale and goes with the task.
6292        q.remove(&t.id, false, &questions).unwrap();
6293        assert!(q.list().is_empty());
6294        let mut again = task("interrupted");
6295        again.id = t.id.clone();
6296        q.put(&mut again).unwrap();
6297        assert!(
6298            q.claim(&t.id).is_ok(),
6299            "a task that comes back must be claimable, which a left-behind lock would prevent"
6300        );
6301    }
6302
6303    fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6304        crate::notices::Notices::at(dir.join("notifications")).list()
6305    }
6306
6307    #[test]
6308    fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6309        let (dir, q) = queue();
6310        let questions = Questions::at(dir.path().join("questions"));
6311        let mut dep = task("dependency");
6312        q.put(&mut dep).unwrap();
6313        let mut blocked = task("waiting");
6314        blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6315        q.put(&mut blocked).unwrap();
6316
6317        let removed = q.remove(&dep.id, false, &questions).unwrap();
6318        assert_eq!(removed.released, [blocked.id.clone()]);
6319        assert!(removed.still_blocked.is_empty());
6320
6321        let after = q.get(&blocked.id).unwrap();
6322        assert_eq!(after.status, TaskStatus::Queued);
6323        assert!(after.blocked_by.is_empty());
6324        assert!(after.block_reason.is_none());
6325        let notes = notices_of(dir.path());
6326        assert_eq!(notes.len(), 1, "{notes:?}");
6327        assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6328        assert_eq!(
6329            notes[0].link,
6330            Some(crate::notices::Link::Task {
6331                id: blocked.id.clone(),
6332            })
6333        );
6334    }
6335
6336    #[test]
6337    fn removing_one_of_two_dependencies_keeps_the_other() {
6338        let (dir, q) = queue();
6339        let questions = Questions::at(dir.path().join("questions"));
6340        let mut dep = task("dependency");
6341        q.put(&mut dep).unwrap();
6342        let mut other = task("other");
6343        q.put(&mut other).unwrap();
6344        let mut blocked = task("waiting");
6345        blocked.block(
6346            vec![dep.id.clone(), other.id.clone()],
6347            Some("waits on both".to_owned()),
6348        );
6349        q.put(&mut blocked).unwrap();
6350
6351        let removed = q.remove(&dep.id, false, &questions).unwrap();
6352        assert!(removed.released.is_empty());
6353        assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6354
6355        let after = q.get(&blocked.id).unwrap();
6356        assert_eq!(after.status, TaskStatus::Blocked);
6357        assert_eq!(after.blocked_by, [other.id.clone()]);
6358        // The tombstone stays while a task still names the id... only this
6359        // one's dependency is gone, so nothing references it and it may go.
6360        assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6361    }
6362
6363    #[test]
6364    fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6365        let (dir, q) = queue();
6366        let questions = Questions::at(dir.path().join("questions"));
6367        let mut dep = task("dependency");
6368        q.put(&mut dep).unwrap();
6369        let mut blocked = task("waiting");
6370        blocked.block(vec![dep.id.clone()], None);
6371        q.put(&mut blocked).unwrap();
6372
6373        // The dependent is claimed elsewhere, so `remove` has to skip it.
6374        let claim = q.claim(&blocked.id).unwrap();
6375        let removed = q.remove(&dep.id, false, &questions).unwrap();
6376        assert!(removed.released.is_empty());
6377        drop(claim);
6378
6379        let mut task = q.get(&blocked.id).unwrap();
6380        assert_eq!(task.status, TaskStatus::Blocked);
6381        assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6382        assert_eq!(
6383            q.apply_deleted_blockers(&mut task, &questions),
6384            [dep.id.clone()]
6385        );
6386        assert_eq!(task.status, TaskStatus::Queued);
6387    }
6388
6389    #[test]
6390    fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6391        let (dir, q) = queue();
6392        let questions = Questions::at(dir.path().join("questions"));
6393        let mut dep = task("dependency");
6394        dep.id = "20261013-193611-ca5b".into();
6395        q.put(&mut dep).unwrap();
6396        let mut waiting = task("waiting");
6397        waiting.block(vec!["ca5b".into()], None);
6398        q.put(&mut waiting).unwrap();
6399        q.remove(&dep.id, false, &questions).unwrap();
6400        assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6401        assert_eq!(
6402            dependency(&q, &questions, "ca5b"),
6403            Dependency::Deleted(dep.id)
6404        );
6405    }
6406
6407    #[test]
6408    fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6409        let (dir, queue) = queue();
6410        let questions = Questions::at(dir.path().join("questions"));
6411        let mut dep = task("dependency");
6412        dep.id = "20261013-193611-ca5b".into();
6413        queue.put(&mut dep).unwrap();
6414        std::fs::create_dir_all(questions.root()).unwrap();
6415        let question_id = "20261014-193611-ca5b";
6416        std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6417        assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6418        assert_eq!(
6419            dependency(&queue, &questions, "ca5b"),
6420            Dependency::Ambiguous
6421        );
6422        assert_eq!(
6423            dependency(&queue, &questions, &dep.id),
6424            Dependency::Task(dep.id)
6425        );
6426        assert_eq!(
6427            dependency(&queue, &questions, question_id),
6428            Dependency::Question(question_id.into())
6429        );
6430        assert_eq!(
6431            dependency(&queue, &questions, "missing"),
6432            Dependency::Missing
6433        );
6434    }
6435
6436    #[test]
6437    fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6438        let dir = tempfile::tempdir().unwrap();
6439        let q = Queue::at(dir.path().join("not-a-directory"));
6440        std::fs::write(q.root(), "file").unwrap();
6441        let questions = Questions::at(dir.path().join("questions"));
6442        assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6443        assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6444    }
6445
6446    #[test]
6447    fn a_dependency_without_a_tombstone_is_still_missing() {
6448        let (dir, q) = queue();
6449        let questions = Questions::at(dir.path().join("questions"));
6450        let mut dep = task("dependency");
6451        q.put(&mut dep).unwrap();
6452        std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6453        assert_eq!(
6454            missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6455            [dep.id.clone()]
6456        );
6457        assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6458    }
6459
6460    #[test]
6461    fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6462        let mut t = task("held");
6463        t.hold_machine(Some("because".to_owned()));
6464        t.blocked_by = vec!["gone".to_owned()];
6465        assert!(!t.dependency_deleted("gone"));
6466        assert_eq!(t.status, TaskStatus::Held);
6467    }
6468
6469    #[test]
6470    fn a_failed_record_removal_takes_the_tombstone_back() {
6471        let (_dir, q) = queue();
6472        let mut t = task("stays");
6473        q.put(&mut t).unwrap();
6474        q.write_tombstone(&t.id).unwrap();
6475        let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
6476        assert!(err.is_err());
6477        // `remove` is what withdraws the marker; a live record is never
6478        // treated as deleted whatever is on disk.
6479        assert!(!q.was_deleted(&t.id));
6480    }
6481
6482    fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
6483        let p = dir.join(name);
6484        std::fs::write(&p, body).unwrap();
6485        p
6486    }
6487
6488    #[test]
6489    fn an_attachment_copy_survives_deleting_its_source() {
6490        let (dir, q) = queue();
6491        let src = source_file(dir.path(), "shot.png", "pixels");
6492        let mut t = task("with a picture");
6493        let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
6494        q.put(&mut t).unwrap();
6495        std::fs::remove_file(&src).unwrap();
6496        assert_eq!(names, ["shot.png"]);
6497        let loaded = q.get(&t.id).unwrap();
6498        let paths = q.attachment_paths(&loaded);
6499        assert_eq!(paths.len(), 1);
6500        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
6501    }
6502
6503    #[test]
6504    fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
6505        let (dir, q) = queue();
6506        let mut t = task("bad names");
6507        for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
6508            let src = source_file(dir.path(), name, "x");
6509            assert!(
6510                q.attach(&mut t, &[src]).is_err(),
6511                "`{name}` must be refused"
6512            );
6513        }
6514        // A drive-qualified name cannot exist as a file on Windows (joining it
6515        // to a directory yields a drive-relative path to `foo.png` instead),
6516        // so the rule is asserted on the name itself, everywhere.
6517        assert!(!crate::ask::valid_asset_name("C:foo.png"));
6518        #[cfg(not(windows))]
6519        {
6520            let src = source_file(dir.path(), "C:foo.png", "x");
6521            assert!(q.attach(&mut t, &[src]).is_err());
6522        }
6523        let long = format!("{}.png", "a".repeat(70));
6524        let src = source_file(dir.path(), &long, "x");
6525        assert!(q.attach(&mut t, &[src]).is_err());
6526        assert!(t.attachments.is_empty());
6527        assert!(!q.attachments_dir(&t.id).exists());
6528    }
6529
6530    #[test]
6531    fn a_taken_attachment_name_is_numbered_not_overwritten() {
6532        let (dir, q) = queue();
6533        let a = source_file(dir.path(), "shot.png", "one");
6534        let sub = dir.path().join("other");
6535        std::fs::create_dir_all(&sub).unwrap();
6536        let b = source_file(&sub, "shot.png", "two");
6537        let mut t = task("collision");
6538        q.attach(&mut t, &[a]).unwrap();
6539        q.attach(&mut t, &[b]).unwrap();
6540        assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
6541        let paths = q.attachment_paths(&t);
6542        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
6543        assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
6544    }
6545
6546    #[test]
6547    fn a_renumbered_name_stays_inside_the_length_bound() {
6548        let (dir, q) = queue();
6549        let name = format!("{}.png", "a".repeat(60));
6550        assert_eq!(name.len(), 64);
6551        let a = source_file(dir.path(), &name, "one");
6552        let sub = dir.path().join("other");
6553        std::fs::create_dir_all(&sub).unwrap();
6554        let b = source_file(&sub, &name, "two");
6555        let mut t = task("long");
6556        q.attach(&mut t, &[a, b]).unwrap();
6557        assert_eq!(t.attachments.len(), 2);
6558        assert!(
6559            t.attachments
6560                .iter()
6561                .all(|n| crate::ask::valid_asset_name(n))
6562        );
6563        assert!(t.attachments[1].ends_with("-2.png"));
6564    }
6565
6566    #[test]
6567    fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
6568        let (dir, q) = queue();
6569        let good = source_file(dir.path(), "good.png", "ok");
6570        let mut t = task("partial");
6571        q.attach(&mut t, &[good]).unwrap();
6572        let more = source_file(dir.path(), "more.png", "ok");
6573        let missing = dir.path().join("missing.png");
6574        assert!(q.attach(&mut t, &[more, missing]).is_err());
6575        assert_eq!(t.attachments, ["good.png"]);
6576        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6577            .unwrap()
6578            .flatten()
6579            .collect();
6580        assert_eq!(on_disk.len(), 1);
6581    }
6582
6583    /// Make the next `put` of `t` fail: its temp file's path is a directory.
6584    fn block_put(q: &Queue, t: &Task) -> PathBuf {
6585        let tmp = q.path_of(&t.id).with_extension("json.tmp");
6586        std::fs::create_dir_all(&tmp).unwrap();
6587        tmp
6588    }
6589
6590    #[test]
6591    fn a_failed_put_leaves_no_new_attachment_directory() {
6592        let (dir, q) = queue();
6593        let mut t = task("fresh");
6594        let tmp = block_put(&q, &t);
6595        let src = source_file(dir.path(), "shot.png", "x");
6596        assert!(q.attach_and_put(&mut t, &[src]).is_err());
6597        assert!(t.attachments.is_empty());
6598        assert!(!q.attachments_dir(&t.id).exists());
6599        assert!(!q.path_of(&t.id).exists());
6600        std::fs::remove_dir(tmp).unwrap();
6601    }
6602
6603    #[test]
6604    fn a_failed_put_removes_only_the_copy_it_just_made() {
6605        let (dir, q) = queue();
6606        let mut t = task("edited");
6607        let first = source_file(dir.path(), "first.png", "1");
6608        q.attach_and_put(&mut t, &[first]).unwrap();
6609        block_put(&q, &t);
6610        let second = source_file(dir.path(), "second.png", "2");
6611        assert!(q.attach_and_put(&mut t, &[second]).is_err());
6612        assert_eq!(t.attachments, ["first.png"]);
6613        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
6614            .unwrap()
6615            .flatten()
6616            .map(|e| e.file_name().to_string_lossy().into_owned())
6617            .collect();
6618        assert_eq!(on_disk, ["first.png"]);
6619        assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
6620    }
6621
6622    #[test]
6623    fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
6624        let (dir, q) = queue();
6625        let questions = Questions::at(dir.path().join("questions"));
6626        let gone = task("gone");
6627        let mut other = task("other");
6628        let mut live = task("live");
6629        q.put(&mut other).unwrap();
6630        q.put(&mut live).unwrap();
6631        // `gone` has no record: its removal finished deleting the record but
6632        // not the set-aside attachments.
6633        let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
6634        std::fs::create_dir_all(&orphan).unwrap();
6635        std::fs::write(orphan.join("shot.png"), "x").unwrap();
6636        // `live` still has a record, so its `.removing` belongs to a removal
6637        // in progress and must be left alone.
6638        let busy = q.root.join(format!("{}.attachments.removing", live.id));
6639        std::fs::create_dir_all(&busy).unwrap();
6640
6641        q.remove(&other.id, false, &questions).unwrap();
6642        assert!(!orphan.exists(), "an orphan is swept");
6643        assert!(busy.exists(), "a removal in progress is left alone");
6644    }
6645
6646    #[test]
6647    fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
6648        let (dir, q) = queue();
6649        let questions = Questions::at(dir.path().join("questions"));
6650        let mut t = task("stuck");
6651        let src = source_file(dir.path(), "shot.png", "x");
6652        q.attach_and_put(&mut t, &[src]).unwrap();
6653        // A non-empty directory already at the set-aside name makes the rename
6654        // fail; its record is present, so the sweep leaves it in place.
6655        let aside = q.root.join(format!("{}.attachments.removing", t.id));
6656        std::fs::create_dir_all(&aside).unwrap();
6657        std::fs::write(aside.join("old.png"), "o").unwrap();
6658        assert!(q.remove(&t.id, false, &questions).is_err());
6659        assert!(q.path_of(&t.id).exists());
6660        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6661    }
6662
6663    #[test]
6664    fn a_failed_record_removal_puts_the_attachments_back() {
6665        let (dir, q) = queue();
6666        let mut t = task("rollback");
6667        let src = source_file(dir.path(), "shot.png", "x");
6668        q.attach_and_put(&mut t, &[src]).unwrap();
6669        let err = q
6670            .remove_record_with_attachments(&t.id, |_| {
6671                Err(std::io::Error::other("injected failure"))
6672            })
6673            .unwrap_err();
6674        assert!(format!("{err:#}").contains("injected failure"));
6675        assert!(q.path_of(&t.id).exists());
6676        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
6677        assert!(
6678            !q.root
6679                .join(format!("{}.attachments.removing", t.id))
6680                .exists()
6681        );
6682    }
6683
6684    #[test]
6685    fn editing_a_task_keeps_its_attachments() {
6686        let (dir, q) = queue();
6687        let src = source_file(dir.path(), "shot.png", "x");
6688        let mut t = task("editable");
6689        q.attach(&mut t, &[src]).unwrap();
6690        t.edit("new".to_owned(), "new text".to_owned()).unwrap();
6691        q.put(&mut t).unwrap();
6692        assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
6693    }
6694
6695    #[test]
6696    fn removing_a_task_deletes_its_attachments() {
6697        let (dir, q) = queue();
6698        let questions = Questions::at(dir.path().join("questions"));
6699        let src = source_file(dir.path(), "shot.png", "x");
6700        let mut t = task("doomed");
6701        q.attach(&mut t, &[src]).unwrap();
6702        q.put(&mut t).unwrap();
6703        assert!(q.attachments_dir(&t.id).is_dir());
6704        q.remove(&t.id, false, &questions).unwrap();
6705        assert!(!q.attachments_dir(&t.id).exists());
6706        assert!(q.list().is_empty());
6707    }
6708
6709    #[test]
6710    fn a_task_written_before_attachments_still_reads() {
6711        let (_dir, q) = queue();
6712        let mut t = task("old");
6713        q.put(&mut t).unwrap();
6714        let path = q.path_of(&t.id);
6715        let mut v: serde_json::Value =
6716            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
6717        v.as_object_mut().unwrap().remove("attachments");
6718        std::fs::write(&path, v.to_string()).unwrap();
6719        assert!(q.get(&t.id).unwrap().attachments.is_empty());
6720    }
6721
6722    #[test]
6723    fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
6724        let q = Queue::at(PathBuf::from("relative-queue"));
6725        let mut t = task("rel");
6726        t.attachments.push("shot.png".to_owned());
6727        let paths = q.attachment_paths(&t);
6728        assert!(paths[0].is_absolute(), "{}", paths[0].display());
6729        assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
6730    }
6731
6732    fn upgrade_parked(id: &str, started: &str) -> Task {
6733        let mut t = task(id);
6734        t.id = id.into();
6735        t.start(format!("run-{id}"));
6736        t.park("upgrade");
6737        t.record_pass_at(
6738            &format!("run-{id}"),
6739            0,
6740            Some(started.parse().unwrap()),
6741            1,
6742            Some(crate::run::ParkCause::Upgrade {
6743                from: "old".into(),
6744                to: None,
6745            }),
6746        );
6747        t
6748    }
6749
6750    #[test]
6751    fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
6752        // A was claimed first but its graph pass started later (slow start-up).
6753        let stamp = |id: &str, dispatched: &str, started: &str| {
6754            let mut t = task(id);
6755            t.id = id.into();
6756            t.start(format!("run-{id}"));
6757            t.park("upgrade");
6758            t.dispatched_at = Some(dispatched.parse().unwrap());
6759            t.record_pass_at(
6760                &format!("run-{id}"),
6761                0,
6762                Some(started.parse().unwrap()),
6763                1,
6764                Some(crate::run::ParkCause::Upgrade {
6765                    from: "old".into(),
6766                    to: None,
6767                }),
6768            );
6769            t
6770        };
6771        let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
6772        let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
6773        assert!(dispatch_order(&a, &b).is_lt());
6774    }
6775
6776    #[test]
6777    fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
6778        let (_dir, q) = queue();
6779        let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
6780        let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
6781        earlier.priority = -10;
6782        let mut fresh = task("fresh");
6783        fresh.id = "newer".into();
6784        fresh.priority = 100;
6785        for t in [&mut fresh, &mut later, &mut earlier] {
6786            q.put(t).unwrap();
6787        }
6788        let reloaded = Queue::at(q.root().to_owned());
6789        let mut tasks = reloaded.list();
6790        tasks.sort_unstable_by(dispatch_order);
6791        assert_eq!(
6792            tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
6793            vec!["earlier", "later", "newer"]
6794        );
6795        assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
6796        assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
6797    }
6798
6799    #[test]
6800    fn upgrade_resume_legacy_order_uses_settlement_and_id() {
6801        let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
6802        let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
6803        for t in [&mut a, &mut b] {
6804            let mut value = serde_json::to_value(&*t).unwrap();
6805            value["passes"][0]
6806                .as_object_mut()
6807                .unwrap()
6808                .remove("started_at");
6809            *t = serde_json::from_value(value).unwrap();
6810        }
6811        assert!(dispatch_order(&a, &b).is_lt());
6812        b.passes[0].settled_at = a.passes[0].settled_at;
6813        assert!(dispatch_order(&a, &b).is_lt());
6814    }
6815
6816    #[test]
6817    fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
6818        let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
6819        assert!(original.upgrade_resume_key().is_some());
6820        for cause in [
6821            crate::run::ParkCause::Operator,
6822            crate::run::ParkCause::Question,
6823            crate::run::ParkCause::Interrupt {
6824                reason: "interrupt".into(),
6825            },
6826            crate::run::ParkCause::Unspecified,
6827        ] {
6828            let mut t = original.clone();
6829            t.passes[0].parked = Some(cause);
6830            assert!(t.upgrade_resume_key().is_none());
6831            let mut fresh = task("fresh");
6832            fresh.priority = 1;
6833            assert!(dispatch_order(&fresh, &t).is_lt());
6834        }
6835        let mut t = original.clone();
6836        t.release();
6837        assert!(t.upgrade_resume_key().is_none());
6838        t.edit("edited".into(), "new instruction".into()).unwrap();
6839        assert!(t.upgrade_resume_key().is_none());
6840        let mut t = original.clone();
6841        t.requeue();
6842        t.status = TaskStatus::Parked;
6843        assert!(t.upgrade_resume_key().is_none());
6844        let mut t = original.clone();
6845        t.start("different-run".into());
6846        t.park("no upgrade");
6847        assert!(t.upgrade_resume_key().is_none());
6848    }
6849
6850    #[test]
6851    fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
6852        let dir = tempfile::tempdir().unwrap();
6853        let q = Queue::at(dir.path().join("queue"));
6854        let mut t = task("resume");
6855        t.start("A".into());
6856        t.record_pass("A", 0, 1, None);
6857        t.start("B".into());
6858        q.put(&mut t).unwrap();
6859        assert_eq!(t.runs, vec!["A", "B"]);
6860        t.start("A".into());
6861        t.record_pass("A", 1, 3, None);
6862        q.put(&mut t).unwrap();
6863        let saved = q.get(&t.id).unwrap();
6864        assert_eq!(saved.runs, vec!["B", "A"]);
6865        assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
6866        assert_eq!(saved.attempts, 3);
6867        assert_eq!(saved.passes.len(), 2);
6868        assert_eq!(saved.passes[0].run, "A");
6869        assert_eq!(saved.passes[1].run, "A");
6870    }
6871
6872    #[test]
6873    fn repeated_start_records_one_run_and_separate_passes() {
6874        let mut t = task("resume");
6875        t.start("same-run".into());
6876        t.record_pass("same-run", 0, 1, None);
6877        t.start("same-run".into());
6878        t.record_pass("same-run", 1, 2, None);
6879        assert_eq!(t.runs, vec!["same-run"]);
6880        assert_eq!(t.attempts, 2);
6881        assert_eq!(t.passes.len(), 2);
6882    }
6883
6884    #[test]
6885    fn link_run_adds_a_run_once_and_touches_nothing_else() {
6886        let dir = tempfile::tempdir().unwrap();
6887        let queue = Queue::at(dir.path().join("queue"));
6888        let mut t = Task::new(
6889            "t".to_owned(),
6890            "do it".to_owned(),
6891            PathBuf::from("."),
6892            Source::Human,
6893        );
6894        queue.put(&mut t).unwrap();
6895        let before = queue.get(&t.id).unwrap();
6896
6897        let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
6898        assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
6899        assert_eq!(linked.status, before.status);
6900        assert_eq!(linked.attempts, before.attempts);
6901        assert_eq!(linked.interrupt, before.interrupt);
6902
6903        let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6904        assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
6905        assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
6906        assert!(queue.link_run("no-such-task", "r").is_err());
6907    }
6908
6909    #[test]
6910    fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
6911        let dir = tempfile::tempdir().unwrap();
6912        let queue = Queue::at(dir.path().join("queue"));
6913        let mut t = Task::new(
6914            "t".to_owned(),
6915            "do it".to_owned(),
6916            PathBuf::from("."),
6917            Source::Human,
6918        );
6919        queue.put(&mut t).unwrap();
6920        // The daemon's copy, taken before the link.
6921        let mut snapshot = queue.get(&t.id).unwrap();
6922        queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
6923
6924        snapshot.start("20260930-000000-aaaa".to_owned());
6925        queue.put(&mut snapshot).unwrap();
6926
6927        let stored = queue.get(&t.id).unwrap();
6928        assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
6929        assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
6930        assert_eq!(stored.attempts, 1);
6931    }
6932
6933    #[test]
6934    fn concurrent_links_and_daemon_saves_lose_nothing() {
6935        let dir = tempfile::tempdir().unwrap();
6936        let queue = Queue::at(dir.path().join("queue"));
6937        let mut t = Task::new(
6938            "t".to_owned(),
6939            "do it".to_owned(),
6940            PathBuf::from("."),
6941            Source::Human,
6942        );
6943        queue.put(&mut t).unwrap();
6944        let id = t.id.clone();
6945
6946        let linkers: Vec<_> = (0..4)
6947            .map(|n| {
6948                let (queue, id) = (queue.clone(), id.clone());
6949                std::thread::spawn(move || {
6950                    for k in 0..10 {
6951                        queue
6952                            .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
6953                            .unwrap();
6954                    }
6955                })
6956            })
6957            .collect();
6958        // The daemon's side: transitions saved from its own, ever staler,
6959        // copy of the task.
6960        let mut mine = queue.get(&id).unwrap();
6961        for k in 0..10 {
6962            mine.start(format!("20260930-000009-d{k:03}"));
6963            queue.put(&mut mine).unwrap();
6964        }
6965        for l in linkers {
6966            l.join().unwrap();
6967        }
6968
6969        let stored = queue.get(&id).unwrap();
6970        assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
6971        assert_eq!(
6972            stored.attempts, 10,
6973            "linking never rewinds the daemon's work"
6974        );
6975    }
6976
6977    fn age_lock(path: &Path) {
6978        let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
6979        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
6980            .unwrap();
6981    }
6982
6983    #[test]
6984    fn concurrent_stale_takeover_yields_one_holder() {
6985        use std::sync::atomic::{AtomicUsize, Ordering};
6986        use std::sync::{Arc, Barrier};
6987        for _ in 0..5 {
6988            let dir = tempfile::tempdir().unwrap();
6989            let q = Queue::at(dir.path().to_path_buf());
6990            let lock = dir.path().join("t.write-lock");
6991            std::fs::write(&lock, "dead-0000").unwrap();
6992            age_lock(&lock);
6993            let n = 6;
6994            let barrier = Arc::new(Barrier::new(n));
6995            let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
6996            let handles: Vec<_> = (0..n)
6997                .map(|_| {
6998                    let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
6999                    std::thread::spawn(move || {
7000                        b.wait();
7001                        let g = q.lock_task("t").unwrap();
7002                        let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7003                        max.fetch_max(held, Ordering::SeqCst);
7004                        std::thread::sleep(std::time::Duration::from_millis(20));
7005                        now.fetch_sub(1, Ordering::SeqCst);
7006                        drop(g);
7007                    })
7008                })
7009                .collect();
7010            for h in handles {
7011                h.join().unwrap();
7012            }
7013            assert_eq!(max.load(Ordering::SeqCst), 1);
7014            assert!(!lock.exists());
7015        }
7016    }
7017
7018    #[test]
7019    fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7020        let dir = tempfile::tempdir().unwrap();
7021        let q = Queue::at(dir.path().to_path_buf());
7022        let lock = dir.path().join("t.write-lock");
7023        let a = q.lock_task("t").unwrap();
7024        // Simulate a foreign/legacy writer replacing the file. A modern
7025        // writer cannot acquire it while this guard's process is alive.
7026        let replacement = owner_token();
7027        std::fs::write(&lock, &replacement).unwrap();
7028        drop(a);
7029        assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7030    }
7031
7032    #[test]
7033    fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7034        let dir = tempfile::tempdir().unwrap();
7035        let q = Queue::at(dir.path().to_path_buf());
7036        let held = q.lock_task("t").unwrap();
7037        let path = dir.path().join("t.write-lock");
7038        age_lock(&path);
7039        assert!(!break_stale(&path, &held.token));
7040        let (started_tx, started_rx) = std::sync::mpsc::channel();
7041        let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7042        let updater = std::thread::spawn(move || {
7043            started_tx.send(()).unwrap();
7044            let _write = q.lock_task("t").unwrap();
7045            acquired_tx.send(()).unwrap();
7046        });
7047        started_rx.recv().unwrap();
7048        assert!(
7049            acquired_rx
7050                .recv_timeout(std::time::Duration::from_millis(100))
7051                .is_err()
7052        );
7053        assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7054        drop(held);
7055        acquired_rx
7056            .recv_timeout(std::time::Duration::from_secs(2))
7057            .unwrap();
7058        updater.join().unwrap();
7059        assert!(!path.exists());
7060    }
7061
7062    #[test]
7063    fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7064        let dir = tempfile::tempdir().unwrap();
7065        let lock = dir.path().join("t.write-lock");
7066        std::fs::write(&lock, "new-token").unwrap();
7067        assert!(!break_stale(&lock, "old-token"));
7068        assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7069        // Same token but fresh: not stale any more, so also left alone.
7070        assert!(!break_stale(&lock, "new-token"));
7071        assert!(lock.exists());
7072        age_lock(&lock);
7073        assert!(break_stale(&lock, "new-token"));
7074        assert!(!lock.exists());
7075    }
7076
7077    #[test]
7078    fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7079        let dir = tempfile::tempdir().unwrap();
7080        let lock = dir.path().join("t.write-lock");
7081        std::fs::write(&lock, "dead-1").unwrap();
7082        age_lock(&lock);
7083        let marker = break_marker(&lock, "dead-1");
7084        std::fs::write(&marker, "crashed-remover").unwrap();
7085        // Fresh marker: another remover is working, so nothing is broken.
7086        assert!(!break_stale(&lock, "dead-1"));
7087        assert!(lock.exists());
7088        // Stale marker: recovered, then the lock is broken.
7089        age_lock(&marker);
7090        assert!(break_stale(&lock, "dead-1"));
7091        assert!(!lock.exists());
7092        assert!(!marker.exists());
7093    }
7094
7095    fn chat_task() -> Task {
7096        Task::new(
7097            "t".to_owned(),
7098            "do t".to_owned(),
7099            PathBuf::from("."),
7100            Source::Agent {
7101                run: "20260902-000000-beef".to_owned(),
7102                node: CHAT_NODE.to_owned(),
7103            },
7104        )
7105    }
7106
7107    #[test]
7108    fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7109        let mut t = chat_task();
7110        t.hold_machine(Some("waiting".into()));
7111        let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7112        t.held_at = Some(old);
7113        t.block(vec!["decision".into()], None);
7114        t.hold_machine(Some("same waiting decision".into()));
7115        assert_eq!(t.held_at, Some(old));
7116        t.start("real-new-run".into());
7117        t.fail("new failure", 1);
7118        assert_ne!(
7119            t.held_at,
7120            Some(old),
7121            "old answers cannot approve a new hold"
7122        );
7123    }
7124
7125    #[test]
7126    fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7127        let (_dir, queue) = queue();
7128        let mut t = chat_task();
7129        t.start("old-run".into());
7130        t.hold_machine(Some("operator is considering recovery".into()));
7131        t.chat_notice = Some(ChatNotice {
7132            key: format!("held#{}", t.held_at.unwrap()),
7133            at: Timestamp::now(),
7134            outcome: ChatNoticeOutcome::Posted,
7135        });
7136        let mut raw = serde_json::to_value(&t).unwrap();
7137        raw.as_object_mut().unwrap().remove("chat_notices");
7138        raw.as_object_mut().unwrap().remove("hold_notice_cause");
7139        std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7140        std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7141        assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7142        queue
7143            .modify(&t.id, |task| {
7144                task.requeue();
7145                task.link_run("unprepared-run");
7146                task.startup_notice_cause("startup-source");
7147                task.fail("same unresolved preflight", 0);
7148                true
7149            })
7150            .unwrap();
7151        assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7152        queue
7153            .modify(&t.id, |task| {
7154                task.succeed(completion(task));
7155                true
7156            })
7157            .unwrap();
7158        assert!(
7159            queue
7160                .get(&t.id)
7161                .unwrap()
7162                .chat_notice_due()
7163                .unwrap()
7164                .starts_with("done:")
7165        );
7166    }
7167
7168    #[test]
7169    fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7170        let mut t = chat_task();
7171        t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7172        let key = t.chat_notice_key().unwrap();
7173        t.chat_notices.push(key);
7174        t.release();
7175        t.block(
7176            vec!["b".into(), "a".into(), "a".into()],
7177            Some("still waiting on prerequisites".into()),
7178        );
7179        assert_eq!(t.chat_notice_due(), None);
7180        t.block(
7181            vec!["new-question".into()],
7182            Some("different decision".into()),
7183        );
7184        assert!(t.chat_notice_due().is_some());
7185    }
7186
7187    #[test]
7188    fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7189        let mut t = chat_task();
7190        t.start("existing-run".into());
7191        t.fail("implementation failed", 1);
7192        let failed = t.chat_notice_key().unwrap();
7193        t.chat_notices.push(failed.clone());
7194        t.release_operator("test", None);
7195        t.start("existing-run".into());
7196        t.fail_startup("startup-source", "same unresolved recovery source", 1);
7197        assert_eq!(
7198            t.chat_notice_due(),
7199            None,
7200            "no-progress recovery stays quiet"
7201        );
7202        t.release_operator("test", None);
7203        t.start("existing-run".into());
7204        t.fail_startup("startup-attachments", "attachment missing", 1);
7205        let attachments = t.chat_notice_due().expect("new attachment blocker");
7206        assert_ne!(attachments, failed);
7207        assert_eq!(
7208            t.hold_notice_cause.as_ref().unwrap().stage,
7209            "startup-attachments"
7210        );
7211        t.chat_notices.push(attachments);
7212        t.release_operator("test", None);
7213        t.start("existing-run".into());
7214        t.fail_startup(
7215            "startup-attachments",
7216            "same missing attachment, reworded",
7217            1,
7218        );
7219        assert_eq!(
7220            t.chat_notice_due(),
7221            None,
7222            "same stage after attempt counter reset"
7223        );
7224        t.release_operator("test", None);
7225        t.start("existing-run".into());
7226        t.fail_startup("startup-config", "different preflight stage", 1);
7227        assert!(t.chat_notice_due().is_some());
7228        assert_eq!(
7229            t.hold_notice_cause.as_ref().unwrap().stage,
7230            "startup-config"
7231        );
7232    }
7233
7234    #[test]
7235    fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7236        let mut t = chat_task();
7237        t.hold_machine(Some("startup source missing".into()));
7238        t.startup_notice_cause("startup-source");
7239        let first = t.chat_notice_key().unwrap();
7240        t.chat_notices.push(first.clone());
7241        t.release_operator("test", None);
7242        t.startup_notice_cause("startup-source");
7243        t.hold_machine(Some("same source cannot be read".into()));
7244        assert_eq!(t.chat_notice_due(), None);
7245        t.startup_notice_cause("startup-config");
7246        assert!(t.chat_notice_due().is_some(), "different startup stage");
7247        t.notice_cause("failed", Some("existing-run"), Some(0));
7248        let run_failure = t.chat_notice_key().unwrap();
7249        t.chat_notices.push(run_failure.clone());
7250        t.release_operator("test", None);
7251        t.startup_notice_cause("startup-source");
7252        t.hold_machine(Some("no new work happened".into()));
7253        assert_eq!(t.chat_notice_due(), None);
7254        t.notice_cause("failed", Some("existing-run"), Some(1));
7255        assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7256        assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7257    }
7258
7259    #[test]
7260    fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7261        let mut t = chat_task();
7262        t.hold_machine(Some("still waiting".into()));
7263        t.chat_notice = Some(ChatNotice {
7264            key: "held#2026-10-14T00:00:00Z".into(),
7265            at: Timestamp::now(),
7266            outcome: ChatNoticeOutcome::Posted,
7267        });
7268        assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7269        t.import_chat_notice();
7270        t.notice_cause("failed", Some("new-run"), Some(0));
7271        assert!(t.chat_notice_due().is_some(), "new producer evidence");
7272        t.succeed(completion(&t));
7273        assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7274    }
7275
7276    #[test]
7277    fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7278        let mut t = chat_task();
7279        assert_eq!(t.chat_notice_due(), None, "queued");
7280        t.start("r1".to_owned());
7281        assert_eq!(t.chat_notice_due(), None, "running");
7282        t.fail("boom", 3);
7283        assert_eq!(t.status, TaskStatus::Failed);
7284        assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7285        t.start("r2".to_owned());
7286        t.park("upgrade");
7287        assert_eq!(t.chat_notice_due(), None, "parked");
7288        t.fail("boom", 1);
7289        assert_eq!(t.status, TaskStatus::Held);
7290        let key = t
7291            .chat_notice_due()
7292            .expect("held on the last attempt is final");
7293        t.chat_notice = Some(ChatNotice {
7294            key,
7295            at: Timestamp::now(),
7296            outcome: ChatNoticeOutcome::Posted,
7297        });
7298        assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7299        t.release();
7300        assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7301        t.start("r3".to_owned());
7302        t.succeed(completion(&t));
7303        assert!(t.chat_notice_due().is_some(), "done is a new final state");
7304    }
7305
7306    #[test]
7307    fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7308        for key in ["done", "done#0", "done#1", "done#12"] {
7309            let mut t = chat_task();
7310            t.status = TaskStatus::Done;
7311            t.chat_notice = Some(ChatNotice {
7312                key: key.to_owned(),
7313                at: Timestamp::now(),
7314                outcome: ChatNoticeOutcome::Posted,
7315            });
7316            assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7317            assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7318            let mut context = completion(&t);
7319            context.reason = Some("inspect again".into());
7320            t.reopen(context).unwrap();
7321            t.start("r2".to_owned());
7322            t.succeed(completion(&t));
7323            assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7324            assert!(
7325                t.chat_notice_due().is_some(),
7326                "new occurrence, old receipt: {key}"
7327            );
7328        }
7329    }
7330
7331    #[test]
7332    fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7333        let mut t = chat_task();
7334        t.hold_manual(Some("wait".to_owned()));
7335        let first = t.chat_notice_due().expect("held");
7336        t.chat_notice = Some(ChatNotice {
7337            key: first.clone(),
7338            at: Timestamp::now(),
7339            outcome: ChatNoticeOutcome::Posted,
7340        });
7341        t.hold_manual(Some("still waiting".to_owned()));
7342        assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7343        t.release();
7344        std::thread::sleep(std::time::Duration::from_millis(5));
7345        t.hold_manual(None);
7346        assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7347    }
7348
7349    #[test]
7350    fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7351        let mut human = task("h");
7352        human.succeed(completion(&human));
7353        assert_eq!(human.chat_notice_due(), None);
7354        // A follow-up only inherits the chat; it did not file the task.
7355        let mut inherited = task("i");
7356        inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7357        inherited.succeed(completion(&inherited));
7358        assert_eq!(inherited.chat_notice_due(), None);
7359        let mut old = chat_task();
7360        old.schema = 12;
7361        old.status = TaskStatus::Done;
7362        assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7363        let mut live = chat_task();
7364        live.schema = 12;
7365        live.start("r1".to_owned());
7366        live.succeed(completion(&live));
7367        assert!(live.chat_notice_due().is_some(), "started by this build");
7368        let mut held = chat_task();
7369        held.schema = 12;
7370        held.hold_machine(Some("config".to_owned()));
7371        assert!(held.chat_notice_due().is_some(), "held before any start");
7372    }
7373
7374    #[test]
7375    fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7376        let tmp = tempfile::tempdir().expect("tempdir");
7377        let q = Queue::at(tmp.path().join("queue"));
7378        let mut t = chat_task();
7379        t.succeed(completion(&t));
7380        q.put(&mut t).expect("put");
7381        let mut stale = q.get(&t.id).expect("get");
7382        let key = t.chat_notice_due().expect("due");
7383        q.modify(&t.id, |x| {
7384            x.chat_notice = Some(ChatNotice {
7385                key: key.clone(),
7386                at: Timestamp::now(),
7387                outcome: ChatNoticeOutcome::Posted,
7388            });
7389            true
7390        })
7391        .expect("modify");
7392        q.put(&mut stale).expect("stale put");
7393        assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7394    }
7395
7396    #[test]
7397    fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7398        // `Task` rejects unknown fields, so a build without `sources` cannot
7399        // read a record that carries the key, even an empty one.
7400        let mut t = task("plain");
7401        let value = serde_json::to_value(&t).unwrap();
7402        assert!(value.get("sources").is_none(), "{value}");
7403        t.sources.pick_commits.push(crate::refs::Input {
7404            token: "abc1234".into(),
7405            sha: "a".repeat(40),
7406            provenance: crate::refs::Provenance::ExplicitCli,
7407        });
7408        let value = serde_json::to_value(&t).unwrap();
7409        assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7410        let restored: Task = serde_json::from_value(value).unwrap();
7411        assert_eq!(restored.sources, t.sources);
7412    }
7413
7414    /// A queue whose id source yields `ids` in order, then fresh ones.
7415    fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7416        let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7417        let n = std::sync::atomic::AtomicUsize::new(0);
7418        Queue::at(dir.join("queue")).with_id_source(move || {
7419            let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7420            ids.get(i)
7421                .cloned()
7422                .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7423        })
7424    }
7425
7426    const TAKEN: &str = "20260101-000000-aaaa";
7427
7428    #[test]
7429    fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7430        let dir = tempfile::tempdir().unwrap();
7431        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7432        let mut first = task("first");
7433        first.start("run-1".into());
7434        first.succeed(completion(&first));
7435        q.put(&mut first).unwrap();
7436        assert_eq!(first.id, TAKEN);
7437        let stored_before = q.get(&first.id).unwrap();
7438        assert!(!stored_before.runs.is_empty());
7439
7440        let mut second = task("second");
7441        q.put(&mut second).unwrap();
7442
7443        assert_ne!(second.id, first.id);
7444        assert!(second.runs.is_empty());
7445        assert!(second.passes.is_empty());
7446        assert!(second.chat_notices.is_empty());
7447        assert!(second.chat_notice.is_none());
7448        assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7449        let a = q.get(&first.id).unwrap();
7450        let b = q.get(&second.id).unwrap();
7451        assert_eq!(a.title, "first");
7452        assert_eq!(a.runs, stored_before.runs);
7453        assert_eq!(a.passes, stored_before.passes);
7454        assert_eq!(a.chat_notices, stored_before.chat_notices);
7455        assert_eq!(a.chat_notice, stored_before.chat_notice);
7456        assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7457        assert_eq!(b.title, "second");
7458        assert!(b.runs.is_empty());
7459        assert!(b.passes.is_empty());
7460        assert!(b.chat_notice.is_none());
7461
7462        // A later save is an update: it still merges.
7463        let mut again = q.get(&second.id).unwrap();
7464        again.title = "second, edited".into();
7465        q.put(&mut again).unwrap();
7466        assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7467        assert_eq!(q.list().len(), 2);
7468    }
7469
7470    #[test]
7471    fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
7472        let dir = tempfile::tempdir().unwrap();
7473        let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
7474        std::fs::create_dir_all(q.root()).unwrap();
7475        std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
7476        std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
7477        let mut t = task("t");
7478        q.put(&mut t).unwrap();
7479        assert_eq!(t.id, "free");
7480    }
7481
7482    #[test]
7483    fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
7484        let dir = tempfile::tempdir().unwrap();
7485        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7486        let mut first = task("first");
7487        q.put(&mut first).unwrap();
7488        let mut second = task("second");
7489        let claim = q.file_claimed(&mut second).unwrap();
7490        assert_ne!(second.id, first.id);
7491        assert!(q.claim(&second.id).is_err());
7492        assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
7493        drop(claim);
7494    }
7495
7496    #[test]
7497    fn an_attached_new_task_skips_a_taken_id() {
7498        let dir = tempfile::tempdir().unwrap();
7499        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7500        let mut first = task("first");
7501        q.put(&mut first).unwrap();
7502        let src = source_file(dir.path(), "shot.png", "x");
7503        let mut second = task("second");
7504        q.attach_and_put(&mut second, &[src]).unwrap();
7505        assert_ne!(second.id, first.id);
7506        assert!(!q.attachments_dir(&first.id).exists());
7507        assert_eq!(q.attachment_paths(&second).len(), 1);
7508        assert!(q.attachment_paths(&second)[0].is_file());
7509    }
7510
7511    #[test]
7512    fn attaching_before_putting_a_new_task_reserves_the_id() {
7513        let dir = tempfile::tempdir().unwrap();
7514        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7515        let mut first = task("first");
7516        q.put(&mut first).unwrap();
7517        let src = source_file(dir.path(), "shot.png", "x");
7518        let mut second = task("second");
7519        q.attach(&mut second, &[src]).unwrap();
7520        assert_ne!(second.id, first.id);
7521        assert!(q.attachments_dir(&second.id).is_dir());
7522        q.put(&mut second).unwrap();
7523        assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
7524        assert_eq!(q.get(&first.id).unwrap().title, "first");
7525        assert!(q.get(&first.id).unwrap().attachments.is_empty());
7526    }
7527
7528    #[test]
7529    fn create_new_keeps_its_already_exists_meaning() {
7530        let dir = tempfile::tempdir().unwrap();
7531        let q = Queue::at(dir.path().join("queue"));
7532        let mut a = task("a");
7533        a.id = "fixed-id".into();
7534        assert!(q.create_new(&mut a).unwrap());
7535        let mut b = task("b");
7536        b.id = "fixed-id".into();
7537        assert!(!q.create_new(&mut b).unwrap());
7538        assert_eq!(q.get("fixed-id").unwrap().title, "a");
7539    }
7540
7541    #[test]
7542    fn filing_gives_up_when_no_id_is_ever_free() {
7543        let dir = tempfile::tempdir().unwrap();
7544        let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
7545        let mut first = task("first");
7546        q.put(&mut first).unwrap();
7547        let mut second = task("second");
7548        assert!(q.put(&mut second).is_err());
7549        assert_eq!(q.get(&first.id).unwrap().title, "first");
7550    }
7551}