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