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