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