Skip to main content

magi/
triage.rs

1//! Held-task triage: walking `held` tasks so a hold left by an accident does
2//! not sit unread forever next to one a human placed on purpose.
3//!
4//! [`crate::queue::HoldSource`] already distinguishes "the daemon or
5//! conductor held this during its own recovery" ([`HoldSource::Machine`],
6//! documented as recoverable) from "an operator held this on purpose"
7//! ([`HoldSource::Manual`]). What was missing was anything that actually acts
8//! on that distinction: nothing walked the held list and asked whether a
9//! machine hold's cause was still true, and a record written before
10//! `hold_source` existed (schema < 3, `None`) was silently protected forever
11//! by [`Task::operator_held`]'s conservative default - never wrong, but also
12//! never looked at again by anything.
13//!
14//! [`run_once`] is that walk. For every `held` task it finds:
15//!
16//! - [`HoldSource::Machine`]: if [`machine_cause_resolved`] can tell the
17//!   disk cause is gone, the same task returns to `queued`, preserving attempts
18//!   and retained execution evidence. Known disk waits remain monitored without
19//!   questions while pressure or measurement failure persists. Unknown causes
20//!   get one [`Question`] and remain held until answered.
21//! - `None` (a legacy record, or a hold nobody explained): always a question,
22//!   exactly once - the whole point being that "protected forever" must not
23//!   mean "never shown to anyone" either.
24//! - [`HoldSource::Manual`]: never touched automatically. Only once the hold
25//!   has sat untouched past [`MANUAL_STALE_AFTER`] does it earn a question of
26//!   its own, asking whether it is still wanted.
27//!
28//! Every question this module files carries [`NODE`] and uses the task id as
29//! [`Question::run`] - the same convention `crate::conduct`'s own questions
30//! use for a task rather than a run (see `conduct::apply_one`'s own comment
31//! on why the dedupe check there also filters on `node`, not `run` alone: an
32//! ordinary graph question's `run` is a real run id, and a coincidental
33//! equality with some task's id must not be read as "about this task").
34//! [`RecoveryIndex`] follows the identical rule.
35//!
36//! # Why answers apply here rather than through `crate::queue::Task::block`
37//!
38//! `crate::conduct` blocks a task on its own question
39//! (`Task::block(vec![question_id], …)`), and `crate::daemon::resolve_blockers`
40//! unblocks it - unconditionally, back to `queued` - the moment that question
41//! is answered, whatever the answer actually said. That is correct for
42//! `conduct`: the *content* of the answer is meant for whoever reads
43//! `Task::answers` next, not for the resolver.
44//!
45//! A triage question's answer is different: "not yet" and "discard it" do two
46//! entirely different, non-resuming things, and only "resume it" may put the
47//! task back in line. Reusing the generic blocked/unblock path would resume
48//! every answer alike, so this module never calls [`Task::block`] and never
49//! leaves a triaged task anything but `held` while its question is open.
50//! [`interpret_answer`] reads [`Question::resolution`] itself and
51//! [`run_once`] acts on it directly: [`Task::release`] for an actual "resume
52//! it" choice, [`Queue::remove`] for "discard it" (捨ててよい really means
53//! "you may throw this away", not "leave it sitting held" - the English
54//! wording must say the same thing, not "leave it held"), and
55//! [`Task::hold_manual`] for anything else - which both keeps the task held
56//! and reclassifies it as a hold an operator has now actually seen, one
57//! `crate::conduct` and a later triage pass leave alone.
58//!
59//! The choice is read by its **position** in [`Question::choices`]
60//! ([`Wording::choices3`] always puts "resume" first and
61//! "discard" third), never by comparing the answer text against [`Wording`]'s
62//! own strings picked from whatever config is in force *now* - the language a
63//! question was filed in and the language a later `run_once` call happens to
64//! read back are not guaranteed to be the same call's [`Config`], and a text
65//! comparison would silently misread a real "resume" answer as "keep held"
66//! the moment they disagree.
67//!
68//! # Idempotency
69//!
70//! [`run_once`] runs on every daemon idle tick (see `crate::daemon::poll`)
71//! and on every `magi task triage`; the existing maintenance service also checks
72//! disk waits while other tasks run, at most once per minute per task. Thus an answered question must be applied to
73//! a task **at most once**, and a *fresh* question for the same task (once it
74//! is held again, or goes stale) must still be possible. The record is
75//! [`Task::triage_applied`], the question ids already applied. It cannot live
76//! in [`Task::hold_reason`]: [`Task::release`] clears that, so a "resume"
77//! answer left no trace, and a released task that failed back to `held` was
78//! released again by the same old answer with its attempts reset - forever.
79//! A task that comes back to `held` after an applied answer is therefore a
80//! new hold, handled per [`HoldSource`] (a fresh question for a machine hold).
81//! [`already_applied`] also still reads the `[triage:<short>]` marker
82//! [`keep_held_note`] appends to the hold reason, for records that pre-date
83//! the field.
84
85use std::path::{Path, PathBuf};
86use std::time::Duration;
87
88use jiff::Timestamp;
89
90use crate::ask::{Question, QuestionStatus, Questions};
91use crate::config::Config;
92use crate::queue::{HoldSource, OperatorResume, Queue, Task, TaskStatus};
93
94/// Node recorded on every question this module files - `crate::conduct::NODE`
95/// for the same idea applied to a `crate::conduct` decision instead.
96pub const NODE: &str = "triage";
97
98/// Node on the question filed about a stuck dependency root - see
99/// [`ask_about_stuck_roots`]. Separate from [`NODE`] because the choices mean
100/// something else (position 2 is "detach the dependants", not "discard").
101pub const DEPS_NODE: &str = "triage-deps";
102
103/// Seat name on a filed question. Not a real agent seat - there is no model
104/// call anywhere in this module - but every [`Question`] needs one, and every
105/// other deterministic filer (`crate::land`'s merge approval) names itself
106/// the same way.
107const SEAT: &str = "triage";
108
109/// How long a [`HoldSource::Manual`] hold sits untouched before triage asks
110/// whether it is still wanted.
111///
112/// A judgement call, not a `magi.toml` setting - the same reasoning
113/// `ask::REPLY_QUIET_WINDOW` documents for itself: there is no operator
114/// preference for "how long is too long to ignore my own hold" that a
115/// per-repository config could be *right* about. Seven days is long enough
116/// that an ordinary multi-day hold (waiting on a dependency, waiting on the
117/// operator's own schedule) never gets nagged, and short enough that a hold
118/// nobody has looked at in a week surfaces again rather than aging into the
119/// kind of silent backlog this feature exists to prevent.
120const MANUAL_STALE_AFTER: Duration = Duration::from_secs(7 * 24 * 60 * 60);
121
122/// Localised strings for a filed question, the same idea as `crate::land`'s
123/// own `Words`/`words()` - only the languages magi can actually check are
124/// translated, and anything else falls back to English.
125struct Wording {
126    lang: &'static str,
127    resume: &'static str,
128    wait: &'static str,
129    discard: &'static str,
130}
131
132const EN: Wording = Wording {
133    lang: "en",
134    resume: "resume it",
135    wait: "not yet",
136    discard: "discard it",
137};
138
139const JA: Wording = Wording {
140    lang: "ja",
141    resume: "再開してよい",
142    wait: "まだ待って",
143    discard: "捨ててよい",
144};
145
146/// Pick the wording. Codes and names both, the same acceptance
147/// `crate::land::words` gives `[graph] language`.
148fn wording(language: &str) -> &'static Wording {
149    if crate::lang::is_japanese(language) {
150        &JA
151    } else {
152        &EN
153    }
154}
155
156impl Wording {
157    fn choices3(&self) -> Vec<String> {
158        vec![
159            self.resume.to_owned(),
160            self.wait.to_owned(),
161            self.discard.to_owned(),
162        ]
163    }
164
165    fn choices_manual(&self) -> Vec<String> {
166        let (resume, wait) = if self.lang == "ja" {
167            ("再開する", "まだ止めておく")
168        } else {
169            ("resume it", "keep it held")
170        };
171        vec![resume.to_owned(), wait.to_owned(), self.discard.to_owned()]
172    }
173
174    fn source_label(&self, source: Option<HoldSource>) -> &'static str {
175        match (self.lang, source) {
176            ("ja", Some(HoldSource::Machine)) => "machine(機械による自動保留)",
177            ("ja", Some(HoldSource::Manual)) => "manual(操作者による手動保留)",
178            ("ja", None) => "unknown(schema 3 未満の旧レコード、または理由未記録)",
179            (_, Some(HoldSource::Machine)) => "machine (automatic recovery hold)",
180            (_, Some(HoldSource::Manual)) => "manual (an operator held this)",
181            (_, None) => "unknown (pre-schema-3 record, or never recorded)",
182        }
183    }
184
185    /// The body under the summary: everything an operator needs to judge this
186    /// without opening a terminal - id, title, hold reason, hold source.
187    ///
188    /// Falls back to [`Task::last_error`] when [`Task::hold_reason`] is empty:
189    /// a record written before `Task::fail`/`Task::handed_off` started
190    /// copying `why` into `hold_reason` too, or one written by a still older
191    /// build, would otherwise leave the question blank for exactly the case
192    /// requirement 4 exists for.
193    fn detail(&self, task: &Task, why: &str) -> String {
194        let none = if self.lang == "ja" {
195            "(記録なし)"
196        } else {
197            "(none recorded)"
198        };
199        let reason = task
200            .hold_reason
201            .as_deref()
202            .or(task.last_error.as_deref())
203            .unwrap_or(none);
204        format!(
205            "task: {} ({})\ntitle: {}\nhold source: {}\nhold reason: {reason}\n\n{why}",
206            task.id,
207            task.short(),
208            task.title,
209            self.source_label(task.hold_source),
210        )
211    }
212
213    fn summary_machine_unknown(&self, task: &Task) -> String {
214        if self.lang == "ja" {
215            format!("保留タスク {} の再開可否を判断してください", task.short())
216        } else {
217            format!("decide whether to resume held task {}", task.short())
218        }
219    }
220
221    fn why_machine(&self) -> &'static str {
222        if self.lang == "ja" {
223            "機械的な保留(machine hold)ですが、原因がすでに解消しているかを自動では判断できませんでした。"
224        } else {
225            "This is a machine hold, but whether its cause has resolved could not be \
226             checked automatically."
227        }
228    }
229
230    fn summary_conductor_override(&self, task: &Task) -> String {
231        if self.lang == "ja" {
232            format!(
233                "再開と回答済みのタスク {} を conductor が再び保留しました",
234                task.short()
235            )
236        } else {
237            format!(
238                "task {} was resumed at your word, but the conductor held it again",
239                task.short()
240            )
241        }
242    }
243
244    fn why_conductor_override(&self, o: &OperatorResume) -> String {
245        let reason = o.conductor_rehold.as_deref().unwrap_or_default();
246        if self.lang == "ja" {
247            format!(
248                "{} に再開と回答済みですが、conductor が再び hold しました。conductor の理由: \
249                 {reason}\n\n強制再キューを選ぶと、以後 conductor はこのタスクを hold できません。",
250                o.at
251            )
252        } else {
253            format!(
254                "You answered \"resume\" at {}, but the conductor held the task again. \
255                 Its reason: {reason}\n\nForcing a requeue stops the conductor from \
256                 holding this task again.",
257                o.at
258            )
259        }
260    }
261
262    /// Positions match [`AnswerAction`]: 0 resume, 1 keep held, 2 discard.
263    fn choices_conductor_override(&self) -> Vec<String> {
264        if self.lang == "ja" {
265            vec![
266                "強制再キュー(conductor は再 hold 不可)".to_owned(),
267                "手動 hold のまま".to_owned(),
268                "捨ててよい".to_owned(),
269            ]
270        } else {
271            vec![
272                "force requeue (conductor must not hold again)".to_owned(),
273                "keep held (manual)".to_owned(),
274                "discard".to_owned(),
275            ]
276        }
277    }
278
279    fn summary_legacy(&self, task: &Task) -> String {
280        if self.lang == "ja" {
281            format!(
282                "hold_source が不明な保留タスク {} を確認してください",
283                task.short()
284            )
285        } else {
286            format!(
287                "held task {} has no recorded hold source - please take a look",
288                task.short()
289            )
290        }
291    }
292
293    fn why_legacy(&self) -> &'static str {
294        if self.lang == "ja" {
295            "hold_source が記録されていません。schema 3 より前のレコードか、理由が記録されなかった \
296             holdです。人が意図して止めたのか、クラッシュや強制再起動で宙に浮いただけなのか、\
297             このデータからは区別できません。"
298        } else {
299            "No hold_source was recorded - either a pre-schema-3 record, or a hold whose \
300             reason was never written down. Whether this was a deliberate hold or the \
301             leftover of a crash cannot be told from the data alone."
302        }
303    }
304
305    fn summary_manual_stale(&self, task: &Task, days: i64) -> String {
306        if self.lang == "ja" {
307            format!(
308                "{days}日間 保留されたままの手動保留タスク {} を確認してください",
309                task.short()
310            )
311        } else {
312            format!(
313                "held task {} has been on a manual hold for {days} day(s)",
314                task.short()
315            )
316        }
317    }
318
319    fn why_manual(&self) -> &'static str {
320        if self.lang == "ja" {
321            "操作者が明示的に止めた保留ですが、長期間そのままになっています。まだ止めておくか、\
322             再開するか教えてください。"
323        } else {
324            "An operator held this on purpose, but it has sat untouched for a while. Say \
325             whether to keep holding it or resume it."
326        }
327    }
328}
329
330/// Which of the three situations this module recognises a held task is in.
331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332enum Bucket {
333    /// `HoldSource::Machine`, cause not verifiably resolved.
334    MachineUnknown,
335    /// `HoldSource::Machine`, held by the conductor after the operator
336    /// answered "resume" (see [`Task::resume_override`]).
337    ConductorOverride,
338    /// `hold_source` is `None`.
339    Legacy,
340    /// `HoldSource::Manual`, held past [`MANUAL_STALE_AFTER`].
341    ManualStale,
342}
343
344/// What one [`run_once`] pass did, task ids in each list.
345#[derive(Debug, Clone, Default)]
346pub struct Report {
347    /// A `HoldSource::Machine` hold whose cause was found resolved, put back
348    /// in line automatically.
349    pub resumed: Vec<String>,
350    /// A fresh question was filed this pass.
351    pub asked: Vec<String>,
352    /// An operator's answer to an earlier triage question was applied.
353    pub answered: Vec<String>,
354    /// A `blocked` task whose `blocked_by` named an id that no longer exists
355    /// was moved to a machine hold this pass - see
356    /// [`quarantine_orphaned_blocked`]. Distinct from `asked`: the question
357    /// about it, if any, is filed in the same pass and only counted there.
358    pub quarantined: Vec<String>,
359    /// A disk-wait task whose untouched, automatically filed triage question
360    /// was superseded as part of its automatic resume. No owner answer exists.
361    pub superseded: Vec<String>,
362    /// A recovered disk-wait task that still needs an explicit owner decision
363    /// (an owner-touched or unrelated question/approval); monitoring continues.
364    pub needs_owner: Vec<String>,
365}
366
367impl Report {
368    /// Is there nothing to report? Callers use this to skip logging an empty
369    /// pass rather than repeating "triaged 0 held task(s)" on every idle tick.
370    pub fn is_empty(&self) -> bool {
371        self.resumed.is_empty()
372            && self.asked.is_empty()
373            && self.answered.is_empty()
374            && self.quarantined.is_empty()
375            && self.superseded.is_empty()
376            && self.needs_owner.is_empty()
377    }
378}
379
380/// The repository a task's config and disk check should read from. Mirrors
381/// `crate::conduct::repo_for`'s own fallback, duplicated rather than shared
382/// because that one is private to its module and the two are one `if` each.
383fn repo_for(task: &Task) -> PathBuf {
384    if task.repo.as_os_str().is_empty() {
385        PathBuf::from(".")
386    } else {
387        task.repo.clone()
388    }
389}
390
391/// Only exact legacy admission messages may migrate without structured evidence.
392fn is_disk_hold(task: &Task) -> bool {
393    task.has_disk_capacity_cause()
394        || (task.schema < 22
395            && task
396                .hold_reason
397                .as_deref()
398                .is_some_and(crate::disk::is_gate_reason))
399}
400
401pub(crate) fn disk_wait_eligible(task: &Task) -> bool {
402    disk_wait_known(task, &crate::run::home())
403}
404
405/// Run evidence is mandatory for resource-block and emergency-writer holds.
406fn disk_wait_known(task: &Task, home: &Path) -> bool {
407    if task.status != TaskStatus::Held
408        || task.hold_source != Some(HoldSource::Machine)
409        || task
410            .resume_override
411            .as_ref()
412            .is_some_and(|o| o.conductor_rehold.is_some())
413    {
414        return false;
415    }
416    if task.has_disk_capacity_cause() {
417        return true;
418    }
419    // Legacy prose is not authority to reinterpret an explicit recovery pin.
420    if task.resume_override.is_some() {
421        return false;
422    }
423    if is_disk_hold(task) {
424        return true;
425    }
426    if task.schema >= 22 {
427        return false;
428    }
429    if !task.hold_reason.as_deref().is_some_and(|r| {
430        r.starts_with(crate::disk::RUNNING_PRESSURE) || r.starts_with(crate::cache::RESOURCE_HOLD)
431    }) {
432        return false;
433    }
434    let Some(id) = task.execution_runs().last() else {
435        return false;
436    };
437    let Ok(state) = crate::run::RunState::load_under(id, home) else {
438        return false;
439    };
440    state.id == *id
441        && state.resource_block.as_ref().is_some_and(|b| {
442            let expected = match b.kind.as_str() {
443                "disk pressure" => format!("{}{}", crate::disk::RUNNING_PRESSURE, b.detail),
444                "disk admission" => format!(
445                    "{}{}; no attempt was spent; resume to retry the affected operation",
446                    crate::cache::RESOURCE_HOLD,
447                    b.description()
448                ),
449                _ => return false,
450            };
451            matches!(b.cause, crate::run::ResourceBlockCause::Other)
452                && task.hold_reason.as_deref() == Some(expected.as_str())
453        })
454}
455
456/// Has a `HoldSource::Machine` hold's cause resolved? `Some(true)` means yes -
457/// safe to requeue. `Some(false)` means the same cause was checked and is
458/// still in force. `None` means this hold's cause is not one this module
459/// knows how to re-check at all, and a human has to look.
460fn machine_cause_resolved(task: &Task, cfg: &Config) -> Option<bool> {
461    machine_cause_resolved_under(task, cfg, &crate::run::home())
462}
463
464fn machine_cause_resolved_under(task: &Task, cfg: &Config, home: &Path) -> Option<bool> {
465    machine_cause_resolved_with_admission(task, cfg, home, |paths, floor| {
466        let admit = if paths.contains(&crate::build_target::root(home)) {
467            crate::retention::OutputLease::admit_isolated
468        } else {
469            crate::retention::OutputLease::admit
470        };
471        admit(home, paths, floor).is_ok()
472    })
473}
474
475fn cache_wait_run(task: &Task, home: &Path) -> Option<crate::run::RunState> {
476    if !task
477        .hold_reason
478        .as_deref()?
479        .starts_with(crate::cache::RESOURCE_HOLD)
480    {
481        return None;
482    }
483    let id = task.execution_runs().last()?;
484    let state = crate::run::RunState::load_under(id, home).ok()?;
485    (state.id == *id).then_some(state)
486}
487
488fn known_isolated_cache_wait(task: &Task, home: &Path) -> bool {
489    let Some(crate::run::ResourceBlockCause::IsolatedCacheTimeout { target, .. }) =
490        cache_wait_run(task, home)
491            .and_then(|state| state.resource_block)
492            .map(|block| block.cause)
493    else {
494        return false;
495    };
496    crate::build_target::check_prune(home, &target).is_ok_and(|owned| owned)
497}
498
499fn machine_cause_resolved_with_admission(
500    task: &Task,
501    cfg: &Config,
502    home: &Path,
503    admission_available: impl Fn(&[PathBuf], u64) -> bool,
504) -> Option<bool> {
505    if disk_wait_known(task, home) {
506        let saved = if let Some(id) = task.disk_wait_run() {
507            let Ok(state) = crate::run::RunState::load_under(id, home) else {
508                return Some(false);
509            };
510            if state.id != *id || !state.status.resumable() {
511                return Some(false);
512            }
513            Some(state)
514        } else {
515            None
516        };
517        let override_config = task
518            .build_cache_override(cfg)
519            .map(|(mode, _)| mode)
520            .filter(|mode| saved.is_none() && *mode != cfg.verify.build_cache)
521            .map(|mode| {
522                let mut config = cfg.clone();
523                config.verify.build_cache = mode;
524                config
525            });
526        let (repo, config) = saved.as_ref().map_or_else(
527            || (repo_for(task), override_config.as_ref().unwrap_or(cfg)),
528            |state| (state.repo.clone(), &state.config),
529        );
530        if crate::daemon::disk_gate_at(&repo, config, || home.to_owned()).is_some() {
531            return Some(false);
532        }
533        let mut paths = vec![repo];
534        if let Some(state) = &saved {
535            paths.push(state.worktree_root());
536            paths.extend(state.candidates.iter().map(|c| c.worktree.clone()));
537        } else {
538            paths.push(
539                config
540                    .graph
541                    .worktree_root
542                    .clone()
543                    .unwrap_or_else(crate::run::default_worktree_root),
544            );
545        }
546        if crate::build_target::isolated(config) {
547            paths.push(crate::build_target::root(home));
548        } else {
549            paths.extend(config.cache_dir());
550        }
551        let mut floor = config.disk.min_free_bytes;
552        if saved.is_some()
553            && !crate::build_target::isolated(config)
554            && !crate::build_target::isolated(cfg)
555        {
556            let repo = repo_for(task);
557            if crate::daemon::disk_gate_at(&repo, cfg, || home.to_owned()).is_some() {
558                return Some(false);
559            }
560            paths.push(repo);
561            paths.extend(cfg.cache_dir());
562            paths.push(
563                cfg.graph
564                    .worktree_root
565                    .clone()
566                    .unwrap_or_else(crate::run::default_worktree_root),
567            );
568            floor = floor.max(cfg.disk.min_free_bytes);
569        }
570        return Some(admission_available(&paths, floor));
571    }
572    if let Some(state) = cache_wait_run(task, home) {
573        let block = state.resource_block.as_ref()?;
574        if let crate::run::ResourceBlockCause::IsolatedCacheTimeout { target, .. } = &block.cause {
575            return Some(
576                crate::build_target::check_prune(home, target).is_ok_and(|owned| owned)
577                    && !crate::cache::in_use(home, target),
578            );
579        }
580        // A free cache lease resolves contention, not malformed manifests,
581        // failed writes, cancellation, or unknown infrastructure failures.
582        if block.kind != "shared build cache"
583            || !matches!(block.cause, crate::run::ResourceBlockCause::Timeout { .. })
584        {
585            return None;
586        }
587        return Some(
588            state
589                .config
590                .cache_dir()
591                .is_none_or(|dir| !crate::cache::in_use(home, &dir)),
592        );
593    }
594    None
595}
596
597/// Is a `HoldSource::Manual` hold old enough to earn a "still wanted?"
598/// question? Same comparison `crate::clean::due` uses for a run's fold grace,
599/// against [`MANUAL_STALE_AFTER`] instead of a configured one.
600fn manual_is_stale(task: &Task, now: Timestamp) -> bool {
601    now.as_second() - task.updated_at.as_second() > MANUAL_STALE_AFTER.as_secs() as i64
602}
603
604/// The marker [`apply_answer`] writes into [`Task::hold_reason`] and
605/// [`already_applied`] reads back - see this module's own doc on why.
606fn marker_for(q: &Question) -> String {
607    format!("[triage:{}]", q.short())
608}
609
610/// Has `q`'s answer already been applied to `task`? See this module's doc.
611/// Checks [`Task::triage_applied`] first, which survives [`Task::release`].
612fn already_applied(task: &Task, q: &Question) -> bool {
613    if task.triage_applied(&q.id) {
614        return true;
615    }
616    // Records written before `Task::triage_applied` existed carry only the
617    // "keep held" marker in the hold reason.
618    let marker = marker_for(q);
619    task.hold_reason
620        .as_deref()
621        .is_some_and(|r| r.contains(marker.as_str()))
622}
623
624/// Applied answers remain consumed even when migration fences their saved reply.
625fn consumed(task: &Task, q: &Question) -> bool {
626    if q.node == NODE {
627        already_applied(task, q)
628    } else {
629        task.triage_applied(&q.id)
630    }
631}
632
633/// Latest recovery questions from one effect-view scan. Task filename ids
634/// participate in prefix resolution even when their records are unreadable.
635pub(crate) struct RecoveryIndex {
636    latest: std::collections::HashMap<(String, String), Question>,
637}
638
639impl RecoveryIndex {
640    pub(crate) fn load(questions: &Questions) -> Self {
641        let queue = Queue::at(
642            questions
643                .root()
644                .parent()
645                .unwrap_or(Path::new(""))
646                .join("queue"),
647        );
648        let tasks = queue.list();
649        let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
650        Self::from_scan(&queue, &tasks, questions.list_for_effects_in(&ownership))
651    }
652
653    fn from_scan(queue: &Queue, tasks: &[Task], all: Vec<Question>) -> Self {
654        let ids = crate::queue::record_ids(queue.root(), "json").unwrap_or_default();
655        let by_id: std::collections::HashMap<_, _> =
656            tasks.iter().map(|task| (task.id.as_str(), task)).collect();
657        let exact: std::collections::HashSet<_> = ids.iter().map(String::as_str).collect();
658        let mut aliases: std::collections::HashMap<&str, Option<&str>> = Default::default();
659        for id in &ids {
660            for boundary in id
661                .char_indices()
662                .map(|(i, _)| i)
663                .chain(std::iter::once(id.len()))
664            {
665                for alias in [&id[..boundary], &id[boundary..]] {
666                    let entry = aliases.entry(alias).or_insert(Some(id));
667                    if *entry != Some(id.as_str()) {
668                        *entry = None;
669                    }
670                }
671            }
672        }
673        let mut index = Self {
674            latest: Default::default(),
675        };
676        for q in all {
677            if q.node != NODE && q.node != DEPS_NODE {
678                continue;
679            }
680            let resolved = if exact.contains(q.run.as_str()) {
681                Some(q.run.as_str())
682            } else {
683                aliases.get(q.run.as_str()).copied().flatten()
684            };
685            if let Some(id) = resolved
686                && by_id.get(id).is_some_and(|task| {
687                    crate::repair_budget::reconcile::superseded_question(task, &q)
688                })
689            {
690                continue;
691            }
692            let key = (q.node.clone(), q.run.clone());
693            let entry = index.latest.entry(key).or_insert_with(|| q.clone());
694            if (q.asked_at, &q.id) > (entry.asked_at, &entry.id) {
695                *entry = q;
696            }
697        }
698        index
699    }
700
701    fn latest(&self, node: &str, task_id: &str) -> Option<Question> {
702        self.latest
703            .get(&(node.to_owned(), task_id.to_owned()))
704            .cloned()
705    }
706
707    pub(crate) fn pending(&self, task: &Task) -> Vec<Question> {
708        [NODE, DEPS_NODE]
709            .into_iter()
710            .filter_map(|node| {
711                self.latest(node, &task.id).filter(|q| {
712                    !consumed(task, q)
713                        && (q.status.open()
714                            || awaiting_task_chat(q, task)
715                            || q.status == QuestionStatus::Answered)
716                })
717            })
718            .collect()
719    }
720
721    fn displayed_open(&self, task: &Task) -> Option<Question> {
722        [NODE, DEPS_NODE]
723            .into_iter()
724            .filter(|node| {
725                task.status == TaskStatus::Held
726                    || (*node == DEPS_NODE && task.status == TaskStatus::Blocked)
727            })
728            .filter_map(|node| self.latest(node, &task.id))
729            .find(|q| q.status.open() && !consumed(task, q))
730    }
731}
732
733/// What an answered triage question's choice means, independent of which
734/// language it was filed in.
735#[derive(Debug, Clone, Copy, PartialEq, Eq)]
736enum AnswerAction {
737    /// The first choice, always "resume it" / "再開してよい" / "再開する" -
738    /// see [`Wording::choices3`], whose first entry
739    /// is always the resume choice.
740    Resume,
741    /// The third choice, present only in [`Wording::choices3`]: "discard it"
742    /// / "捨ててよい".
743    Discard,
744    /// Anything else: the second choice ("not yet" / "keep it held"), or an
745    /// answer that does not match any offered choice at all (should not
746    /// happen for a multiple-choice question, but the safe default is to
747    /// keep holding rather than guess at "resume").
748    KeepHeld,
749}
750
751/// Read `q`'s answer as an [`AnswerAction`].
752///
753/// Matched by **position in `q.choices`**, never by comparing the answer text
754/// against [`Wording`]'s own strings: [`Wording`] is picked from the task's
755/// *current* repository config, which can differ from whatever language was
756/// in force when the question was filed (a `--config` override on one `magi
757/// task triage` call and not the next, or the repository's config edited in
758/// between). Comparing text would then silently misread an actual "resume"
759/// answer as "keep held" - the choices themselves are fixed at filing time,
760/// in [`file_question`], and never change afterwards, so their position is
761/// the one thing that stays true regardless of which language reads them
762/// back.
763fn interpret_answer(q: &Question) -> AnswerAction {
764    let resolution = q.resolution().unwrap_or_default();
765    match q.choices.iter().position(|c| *c == resolution) {
766        Some(0) => AnswerAction::Resume,
767        Some(2) => AnswerAction::Discard,
768        _ => AnswerAction::KeepHeld,
769    }
770}
771
772/// Legacy triage has a fixed issuer-owned keep-held slot. Its resume slot
773/// may requeue, so it deliberately does not qualify for contextual resume.
774pub(crate) fn contextual_keep_held(q: &Question, label: &str) -> bool {
775    q.node == NODE
776        && q.seat == SEAT
777        && q.actions.is_empty()
778        && q.choices.get(1).is_some_and(|c| c == label)
779}
780
781/// The note [`already_applied`] looks for, appended to (never replacing)
782/// whatever [`Task::hold_reason`] already said - the original cause is still
783/// worth reading in `magi task show` after the operator answers "not yet",
784/// and [`Task::hold_manual`] would otherwise overwrite it outright.
785fn keep_held_note(task: &Task, q: &Question, resolution: &str) -> String {
786    let marker = format!("{} operator: {resolution}", marker_for(q));
787    match task.hold_reason.as_deref() {
788        Some(existing) if !existing.is_empty() => format!("{existing}\n{marker}"),
789        _ => marker,
790    }
791}
792
793/// File a fresh triage question for `task` and return it. The caller is
794/// responsible for having already established there is no open one - see
795/// [`RecoveryIndex`] - so this never checks again.
796fn file_question(
797    questions: &Questions,
798    ownership: &crate::task_chat::InquiryOwnership,
799    task: &Task,
800    bucket: Bucket,
801    w: &Wording,
802    now: Timestamp,
803) -> Option<Question> {
804    let (summary, why, choices) = match bucket {
805        Bucket::MachineUnknown => (
806            w.summary_machine_unknown(task),
807            w.why_machine().to_owned(),
808            w.choices3(),
809        ),
810        Bucket::ConductorOverride => (
811            w.summary_conductor_override(task),
812            task.resume_override
813                .as_ref()
814                .map(|o| w.why_conductor_override(o))
815                .unwrap_or_default(),
816            w.choices_conductor_override(),
817        ),
818        Bucket::Legacy => (
819            w.summary_legacy(task),
820            w.why_legacy().to_owned(),
821            w.choices3(),
822        ),
823        Bucket::ManualStale => {
824            let days = (now.as_second() - task.updated_at.as_second()) / (24 * 60 * 60);
825            (
826                w.summary_manual_stale(task, days),
827                w.why_manual().to_owned(),
828                w.choices_manual(),
829            )
830        }
831    };
832    let mut q = Question::new(
833        task.id.clone(),
834        NODE.to_owned(),
835        SEAT.to_owned(),
836        summary,
837        w.detail(task, &why),
838        choices,
839    );
840    q.triage_generation = Some(task.resumption.as_ref().map_or(0, |r| r.generation));
841    questions.put_executable_in(&mut q, ownership).ok()?;
842    Some(q)
843}
844
845/// What a deputy is told about a triage question: the task, why it is held and
846/// what each position does, in the words [`interpret_answer`] /
847/// [`interpret_deps_answer`] apply them. Written from the stored record; a task
848/// that no longer exists is said to be missing, never reconstructed.
849pub(crate) fn deputy_brief(q: &Question, queue: &Queue) -> String {
850    let task = queue.get(&q.run).ok();
851    let mut s = match &task {
852        Some(t) => format!(
853            "Task {} (`magi task show {}`), \"{}\", is {}. Hold source: {}. Reason: {}.",
854            t.id,
855            t.id,
856            t.title,
857            t.status.as_str(),
858            match t.hold_source {
859                Some(HoldSource::Machine) => "machine (an automatic hold)",
860                Some(HoldSource::Manual) => "manual (an operator held it)",
861                None => "unknown (an old record, treated as the operator's)",
862            },
863            t.hold_reason
864                .as_deref()
865                .or(t.last_error.as_deref())
866                .unwrap_or("(none recorded)")
867        ),
868        None => format!("Task {} no longer exists (its record is gone).", q.run),
869    };
870    if task.as_ref().is_some_and(disk_wait_eligible) {
871        s.push_str("\n\nDisk capacity waits are monitored automatically. No owner answer is needed for an untouched automatic disk triage question. Explicit holds, discussion and other approvals still require owner resolution.");
872    }
873    s.push_str("\n\nWhat each option does, by position:");
874    let n = q.choices.len();
875    for (i, c) in q.choices.iter().enumerate() {
876        let effect = if q.node == DEPS_NODE {
877            match i {
878                0 => "the dependency is released so the loop runs it",
879                1 => {
880                    "the dependants are detached and the dependency task is DELETED; this cannot be undone"
881                }
882                2 => "the dependants are detached; the dependency stays as it is",
883                _ => "nothing is applied",
884            }
885        } else {
886            match i {
887                0 => "the task is released and requeued",
888                2 if n > 2 => "the task is DELETED; this cannot be undone",
889                _ => "the task stays held, with the answer noted",
890            }
891        };
892        s.push_str(&format!("\n- `{c}`: {effect}"));
893    }
894    s.push_str(
895        "\n\nThe daemon applies the answer on its next pass; you apply nothing. When \
896         the owner's words pick an option - including releasing a task they held \
897         themselves, or deleting it - settle it.",
898    );
899    s
900}
901
902/// Move every `blocked` task whose `blocked_by` names a task or question id
903/// that no longer exists to a machine hold, before the per-`held` walk
904/// [`run_once`] does gets a look at it.
905///
906/// `crate::daemon::resolve_blockers` already catches the same situation on
907/// every idle poll, and [`Queue::remove`] already catches it the moment a
908/// dependency is deleted through `magi task rm` - both call the same
909/// [`crate::queue::missing_blockers`]/[`crate::queue::missing_blocker_hold_reason`]
910/// this does. This third copy exists because a dependency can also be deleted
911/// by hand (the file just removed from disk, not through either of those
912/// paths), and because a queue can carry a `blocked` task with a
913/// long-since-deleted dependency from *before* either catch above ever
914/// existed - and such a task is `blocked`, never `held`, so it is invisible
915/// to the rest of this module without this pass. Running it here, first, is
916/// also what makes `magi task triage` alone - with no daemon running at all -
917/// enough to fix one: the task lands `held` in this same call, and the
918/// ordinary loop below files its question in the very same pass.
919fn quarantine_orphaned_blocked(queue: &Queue, questions: &Questions) -> Vec<String> {
920    let mut quarantined = Vec::new();
921    for listed in queue.list() {
922        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
923            continue;
924        }
925        let Ok(_claim) = queue.claim(&listed.id) else {
926            continue;
927        };
928        let Ok(mut task) = queue.get(&listed.id) else {
929            continue;
930        };
931        if task.status != TaskStatus::Blocked {
932            continue;
933        }
934        let deleted = queue.apply_deleted_blockers(&mut task, questions);
935        if !deleted.is_empty() && queue.put(&mut task).is_ok() {
936            for id in &deleted {
937                queue.note_dependency_deleted(&task, id);
938            }
939        }
940        if task.status != TaskStatus::Blocked {
941            continue;
942        }
943        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
944        if missing.is_empty() {
945            continue;
946        }
947        let language = crate::lang::of_repo(&repo_for(&task));
948        let mut cause = missing.clone();
949        cause.sort();
950        cause.dedup();
951        task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
952        task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
953            &task.blocked_by,
954            &missing,
955            &language,
956        )));
957        if queue.put(&mut task).is_ok() {
958            quarantined.push(task.id.clone());
959        }
960    }
961    quarantined
962}
963
964/// Choices of a [`DEPS_NODE`] question, by position: release the root, discard
965/// it, or detach the dependants from it.
966#[derive(Debug, Clone, Copy, PartialEq, Eq)]
967enum DepsAction {
968    Release,
969    Discard,
970    Detach,
971    /// An answer that matches no offered choice: nothing is changed.
972    Nothing,
973}
974
975fn interpret_deps_answer(q: &Question) -> DepsAction {
976    let resolution = q.resolution().unwrap_or_default();
977    match q.choices.iter().position(|c| *c == resolution) {
978        Some(0) => DepsAction::Release,
979        Some(1) => DepsAction::Discard,
980        Some(2) => DepsAction::Detach,
981        _ => DepsAction::Nothing,
982    }
983}
984
985/// Summary, body and choices of the question about one stuck root.
986fn deps_texts(w: &Wording, root: &Task, dependants: &[&Task]) -> (String, String, Vec<String>) {
987    let ja = w.lang == "ja";
988    let reason = root
989        .hold_reason
990        .as_deref()
991        .or(root.last_error.as_deref())
992        .unwrap_or(if ja {
993            "(記録なし)"
994        } else {
995            "(none recorded)"
996        });
997    let list: String = dependants
998        .iter()
999        .map(|t| format!("- {} {}\n", t.short(), t.title))
1000        .collect();
1001    if ja {
1002        (
1003            format!(
1004                "{} ({}) が {} 件のタスクを止めています",
1005                root.short(),
1006                root.status.as_str(),
1007                dependants.len()
1008            ),
1009            format!(
1010                "task: {} ({})\ntitle: {}\n状態: {}\n理由: {reason}\n\n\
1011                 このタスクは自動では実行されないため、依存している次のタスクは永遠に待ち続けます:\n{list}",
1012                root.id,
1013                root.short(),
1014                root.title,
1015                root.status.as_str()
1016            ),
1017            vec![
1018                "依存先を再開する".to_owned(),
1019                "依存先を捨てる(依存タスクは切り離して実行)".to_owned(),
1020                "依存タスクを切り離す(依存先はそのまま)".to_owned(),
1021            ],
1022        )
1023    } else {
1024        (
1025            format!(
1026                "{} ({}) is freezing {} blocked task(s)",
1027                root.short(),
1028                root.status.as_str(),
1029                dependants.len()
1030            ),
1031            format!(
1032                "task: {} ({})\ntitle: {}\nstatus: {}\nreason: {reason}\n\n\
1033                 Nothing in the loop will ever run this task, so these dependants wait \
1034                 forever:\n{list}",
1035                root.id,
1036                root.short(),
1037                root.title,
1038                root.status.as_str()
1039            ),
1040            vec![
1041                "release the dependency".to_owned(),
1042                "discard the dependency (dependants are detached and run)".to_owned(),
1043                "detach the dependants (the dependency stays as it is)".to_owned(),
1044            ],
1045        )
1046    }
1047}
1048
1049/// Detach every `blocked` task that names `root` directly: drop that one id
1050/// from its `blocked_by` (`Task::unblock`), so a dependant with another
1051/// unresolved blocker keeps waiting on it. Idempotent.
1052fn detach_dependants(queue: &Queue, questions: &Questions, root: &str) {
1053    for listed in queue.list() {
1054        if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| matches!(crate::queue::dependency(queue, questions, b), crate::queue::Dependency::Task(id) if id == root)) {
1055            continue;
1056        }
1057        let Ok(_claim) = queue.claim(&listed.id) else {
1058            continue;
1059        };
1060        let Ok(mut t) = queue.get(&listed.id) else {
1061            continue;
1062        };
1063        if t.status != TaskStatus::Blocked {
1064            continue;
1065        }
1066        for id in t.blocked_by.clone() {
1067            if matches!(crate::queue::dependency(queue, questions, &id), crate::queue::Dependency::Task(full) if full == root)
1068            {
1069                t.unblock(&id);
1070            }
1071        }
1072        let _ = queue.put(&mut t);
1073    }
1074}
1075
1076/// Apply an answered [`DEPS_NODE`] question. Every step is idempotent, so a
1077/// pass that dies half way is finished by the next one. Returns whether the
1078/// answer was consumed.
1079fn apply_deps_answer(
1080    queue: &Queue,
1081    questions: &Questions,
1082    q: &Question,
1083    now: Timestamp,
1084    ownership: &crate::task_chat::InquiryOwnership,
1085) -> bool {
1086    let Ok(_claim) = queue.claim(&q.run) else {
1087        return false;
1088    };
1089    let Ok(current) = questions.get_for_effects_in(&q.id, ownership) else {
1090        return false;
1091    };
1092    if current.status != QuestionStatus::Answered {
1093        return false;
1094    }
1095    let q = &current;
1096    let Ok(mut root) = queue.get(&q.run) else {
1097        return false;
1098    };
1099    if root.triage_applied(&q.id) {
1100        return false;
1101    }
1102    if root.operator_decided_at.is_some_and(|at| at > q.asked_at)
1103        || q.triage_generation
1104            .is_some_and(|g| g != root.resumption.as_ref().map_or(0, |r| r.generation))
1105    {
1106        root.mark_triage_applied(&q.id);
1107        return queue.put(&mut root).is_ok();
1108    }
1109    match interpret_deps_answer(q) {
1110        DepsAction::Release => {
1111            if root.status == TaskStatus::Running {
1112                return false;
1113            }
1114            if crate::repair_budget::reconcile::blocker(queue, &root).is_some() {
1115                let Ok(receipt) = crate::repair_budget::reconcile::blocked_resume(q) else {
1116                    return false;
1117                };
1118                root.decision_effects.insert(q.id.clone(), receipt);
1119                root.mark_triage_applied(&q.id);
1120                return queue.put(&mut root).is_ok();
1121            }
1122            root.answers.push(crate::queue::AnsweredQuestion {
1123                question: q.summary.clone(),
1124                answer: q.resolution().unwrap_or_default(),
1125            });
1126            if crate::base_sync_recovery::held_task(queue, &root) {
1127                root.mark_triage_applied(&q.id);
1128                return queue.put(&mut root).is_ok();
1129            }
1130            let before = root.operator_decided_at;
1131            let contract =
1132                crate::repair_budget::contract(&root, crate::repair_budget::Kind::Review).ok();
1133            root.release_operator("triage-dependencies", Some(&q.id));
1134            if let Some(contract) = contract
1135                && let Ok(evidence) = crate::repair_budget::reconcile::effect_evidence(
1136                    q,
1137                    before,
1138                    &contract,
1139                    root.resumption.as_ref().expect("release"),
1140                )
1141            {
1142                root.decision_effects.insert(q.id.clone(), evidence);
1143            }
1144            root.resume_override = Some(OperatorResume {
1145                question_id: q.id.clone(),
1146                at: now,
1147                conductor_rehold: None,
1148                forced: false,
1149                pinned_run: None,
1150            });
1151        }
1152        DepsAction::Discard => {
1153            detach_dependants(queue, questions, &root.id);
1154            return queue.discard_triage(&root.id, questions, &q.id).is_ok();
1155        }
1156        DepsAction::Detach => detach_dependants(queue, questions, &root.id),
1157        // Matches no offered choice, so there is nothing to apply. Left unmarked:
1158        // marking it applied would read as "settled", and the next stuck check
1159        // would file an identical question at once. Unmarked, it stays an
1160        // answered question awaiting application, which suppresses re-asking.
1161        DepsAction::Nothing => return false,
1162    }
1163    root.mark_triage_applied(&q.id);
1164    queue.put(&mut root).is_ok()
1165}
1166
1167fn repair_receipt_notice(queue: &Queue, task: &Task) -> bool {
1168    let Some(detail) = crate::repair_budget::reconcile::blocker(queue, task) else {
1169        return false;
1170    };
1171    if let Some(home) = queue.root().parent() {
1172        let _ = crate::task_inquiry::Outbox::at(home).file_for_occurrence(
1173            task,
1174            task.runs.last().cloned(),
1175            "repair-receipt-recovery".into(),
1176            &task
1177                .repair_grants
1178                .last()
1179                .expect("diagnosed receipt")
1180                .request
1181                .request,
1182            "Retained repair receipt needs reconciliation",
1183            &detail,
1184        );
1185    }
1186    true
1187}
1188
1189/// One question per stuck dependency root. Answers are applied by the
1190/// pre-scheduling sweep. See [`crate::blockers`] for what "stuck" means.
1191///
1192/// Not re-asked: a root with an open or answered-unapplied question; one whose
1193/// own hold question ([`NODE`]) is still pending; and one whose question was
1194/// abandoned unless the root or a task it freezes changed since. An *applied*
1195/// answer leaves nothing stuck (released, discarded, or detached), so a root
1196/// that is stuck again is a new situation and is asked about afresh.
1197fn ask_about_stuck_roots(
1198    queue: &Queue,
1199    questions: &Questions,
1200    config_override: Option<&Path>,
1201    report: &mut Report,
1202) {
1203    let all = questions.list_for_effects();
1204    let tasks = queue.list();
1205    let recovery = RecoveryIndex::from_scan(queue, &tasks, all.clone());
1206    let inv = crate::blockers::Inventory::load_with_tasks(queue, questions, tasks);
1207    let mut frozen: std::collections::BTreeMap<String, Vec<String>> = Default::default();
1208    for (id, roots) in inv.stuck() {
1209        for root in roots {
1210            if root != id {
1211                frozen.entry(root).or_default().push(id.clone());
1212            }
1213        }
1214    }
1215    // A cycle root freezes the others but may have no dependants of its own
1216    // listed above when it is alone; a root with nothing to name is not asked.
1217
1218    let ownership = crate::task_chat::InquiryOwnership::default();
1219    for mut q in all
1220        .iter()
1221        .filter(|q| q.node == DEPS_NODE && q.status.open())
1222        .cloned()
1223    {
1224        if inv.task(&q.run).is_some_and(|task| consumed(task, &q)) {
1225            continue;
1226        }
1227        if !frozen.contains_key(&q.run) {
1228            q.abandon("nothing waits on this task anymore");
1229            let _ = questions.put_executable_in(&mut q, &ownership);
1230        }
1231    }
1232
1233    for (root_id, dependant_ids) in &frozen {
1234        let Ok(_claim) = queue.claim(root_id) else {
1235            continue;
1236        };
1237        // Recheck the chain immediately before asking: an earlier inventory
1238        // may have seen a held prerequisite that has since started running.
1239        let seeds: Vec<_> = std::iter::once(root_id)
1240            .chain(dependant_ids.iter())
1241            .filter_map(|id| queue.get(id).ok())
1242            .collect();
1243        let current = crate::blockers::Inventory::load_for_tasks(queue, questions, &seeds);
1244        let Some(root) = current.task(root_id) else {
1245            continue;
1246        };
1247        if crate::base_sync_recovery::held_task(queue, root) {
1248            continue;
1249        }
1250        // A monitored disk wait recovers by itself; dependants simply keep
1251        // waiting, and no owner question may freeze its automatic recovery.
1252        if disk_wait_known(root, questions.root().parent().unwrap_or(Path::new(""))) {
1253            continue;
1254        }
1255        let dependants: Vec<&Task> = dependant_ids
1256            .iter()
1257            .filter_map(|d| current.task(d))
1258            .filter(|t| current.stuck_roots(t).contains(root_id))
1259            .collect();
1260        if dependants.is_empty() {
1261            continue;
1262        }
1263        if repair_receipt_notice(queue, root) {
1264            continue;
1265        }
1266        let latest = recovery.latest(DEPS_NODE, root_id);
1267        match latest.as_ref() {
1268            Some(q) if !consumed(root, q) && (q.status.open() || awaiting_task_chat(q, root)) => {
1269                continue;
1270            }
1271            Some(q) if q.status == QuestionStatus::Answered && !consumed(root, q) => {
1272                continue;
1273            }
1274            Some(q) if q.status == QuestionStatus::Abandoned => {
1275                let changed = root.updated_at > q.asked_at
1276                    || dependants.iter().any(|t| t.updated_at > q.asked_at);
1277                if !changed {
1278                    continue;
1279                }
1280            }
1281            _ => {}
1282        }
1283        if !recovery.pending(root).is_empty() {
1284            continue;
1285        }
1286        let cfg = Config::discover(&repo_for(root), config_override)
1287            .ok()
1288            .map(|(c, _)| c);
1289        let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1290        let (summary, detail, choices) = deps_texts(w, root, &dependants);
1291        let mut question = Question::new(
1292            root.id.clone(),
1293            DEPS_NODE.to_owned(),
1294            SEAT.to_owned(),
1295            summary,
1296            detail,
1297            choices,
1298        );
1299        question.triage_generation = Some(root.resumption.as_ref().map_or(0, |r| r.generation));
1300        if questions
1301            .put_executable_in(&mut question, &ownership)
1302            .is_ok()
1303        {
1304            report.asked.push(root.id.clone());
1305        }
1306    }
1307}
1308
1309/// Apply settled built-in answers before scheduling or conductor invocation.
1310/// Kept separate from diagnosis so queued tasks can recover legacy answers too.
1311pub fn apply_answers(queue: &Queue, questions: &Questions) -> Vec<String> {
1312    let mut applied = Vec::new();
1313    let ownership = crate::task_chat::InquiryOwnership::default();
1314    for q in questions.list_for_effects_in(&ownership) {
1315        if q.node == DEPS_NODE
1316            && q.status == QuestionStatus::Answered
1317            && apply_deps_answer(queue, questions, &q, Timestamp::now(), &ownership)
1318        {
1319            applied.push(q.run.clone());
1320        }
1321    }
1322    // Dependency answers above may change task and question state.
1323    let tasks = queue.list();
1324    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1325    let recovery =
1326        RecoveryIndex::from_scan(queue, &tasks, questions.list_for_effects_in(&ownership));
1327    for listed in tasks {
1328        let Some(q) = recovery.latest(NODE, &listed.id) else {
1329            continue;
1330        };
1331        if q.status != QuestionStatus::Answered || already_applied(&listed, &q) {
1332            continue;
1333        }
1334        let Ok(_claim) = queue.claim(&listed.id) else {
1335            continue;
1336        };
1337        let Ok(mut task) = queue.get(&listed.id) else {
1338            continue;
1339        };
1340        // Settlement holds this same task claim; discard a reply read before
1341        // it won the claim rather than executing a settled answer.
1342        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1343            continue;
1344        };
1345        if q.status != QuestionStatus::Answered {
1346            continue;
1347        }
1348        if already_applied(&task, &q)
1349            || !matches!(task.status, TaskStatus::Held | TaskStatus::Queued)
1350        {
1351            continue;
1352        }
1353        let generation = task.resumption.as_ref().map_or(0, |r| r.generation);
1354        let action = interpret_answer(&q);
1355        let mut newer_decision = q.triage_generation.is_some_and(|g| g != generation)
1356            || task.resumption.as_ref().is_some_and(|r| r.at > q.asked_at)
1357            || task.held_at.is_some_and(|at| at > q.asked_at)
1358            || task.operator_decided_at.is_some_and(|at| at > q.asked_at);
1359        // A later explicit keep-held answer is itself a newer operator
1360        // decision, even when the question predates the release. Resume and
1361        // discard still require the question's original scope to match.
1362        if matches!(action, AnswerAction::KeepHeld)
1363            && q.answered_at.is_some_and(|at| {
1364                task.operator_decided_at
1365                    .is_none_or(|decision| at > decision)
1366                    && task.resumption.as_ref().is_none_or(|r| at > r.at)
1367            })
1368        {
1369            newer_decision = false;
1370        }
1371        // Audit the answer even when a later release or manual hold wins.
1372        let resolution = q.resolution().unwrap_or_default();
1373        task.answers.push(crate::queue::AnsweredQuestion {
1374            question: q.summary.clone(),
1375            answer: if newer_decision {
1376                format!("{resolution} (superseded by a later operator decision)")
1377            } else {
1378                resolution
1379            },
1380        });
1381        if !newer_decision {
1382            match action {
1383                AnswerAction::Resume if crate::base_sync_recovery::held_task(queue, &task) => {
1384                    // The original answer remains in answers; it cannot authorize
1385                    // a new implementation or an additional base rebase.
1386                }
1387                AnswerAction::Resume
1388                    if crate::repair_budget::reconcile::blocker(queue, &task).is_some() =>
1389                {
1390                    let Ok(receipt) = crate::repair_budget::reconcile::blocked_resume(&q) else {
1391                        continue;
1392                    };
1393                    task.decision_effects.insert(q.id.clone(), receipt);
1394                }
1395                AnswerAction::Resume => {
1396                    let before = task.operator_decided_at;
1397                    let contract =
1398                        crate::repair_budget::contract(&task, crate::repair_budget::Kind::Review)
1399                            .ok();
1400                    task.release_operator("triage", Some(&q.id));
1401                    if let Some(contract) = contract
1402                        && let Ok(evidence) = crate::repair_budget::reconcile::effect_evidence(
1403                            &q,
1404                            before,
1405                            &contract,
1406                            task.resumption.as_ref().expect("release"),
1407                        )
1408                    {
1409                        task.decision_effects.insert(q.id.clone(), evidence);
1410                    }
1411                    task.resume_override = Some(OperatorResume {
1412                        question_id: q.id.clone(),
1413                        at: Timestamp::now(),
1414                        conductor_rehold: None,
1415                        forced: true,
1416                        pinned_run: None,
1417                    });
1418                }
1419                AnswerAction::KeepHeld => {
1420                    let note = keep_held_note(&task, &q, &q.resolution().unwrap_or_default());
1421                    task.hold_manual(Some(note));
1422                }
1423                AnswerAction::Discard => {
1424                    if queue.discard_triage(&task.id, questions, &q.id).is_ok() {
1425                        applied.push(task.id);
1426                    }
1427                    continue;
1428                }
1429            }
1430        }
1431        task.mark_triage_applied(&q.id);
1432        if queue.put(&mut task).is_ok() {
1433            applied.push(task.id);
1434        }
1435    }
1436    applied
1437}
1438const DISK_SUPERSEDED: &str =
1439    "Automatic disk wait superseded unanswered triage; no owner answer or approval was created";
1440
1441fn untouched_disk_question(q: &Question, task: &Task) -> bool {
1442    q.status.open()
1443        && q.node == NODE
1444        && q.seat == SEAT
1445        && q.run == task.id
1446        && q.routed_task.as_deref().is_none_or(|id| id == task.id)
1447        && q.triage_generation == Some(task.resumption.as_ref().map_or(0, |r| r.generation))
1448        && task.held_at.is_some_and(|at| q.asked_at >= at)
1449        && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1450        && q.answer.is_none()
1451        && q.answered_at.is_none()
1452        && q.accepted_answer_at.is_none()
1453        && q.thread.is_empty()
1454        && q.actions.is_empty()
1455        && q.merge_target.is_none()
1456        && [&EN, &JA].iter().any(|w| {
1457            q.summary == w.summary_machine_unknown(task)
1458                && q.choices == w.choices3()
1459                && q.detail == w.detail(task, w.why_machine())
1460        })
1461}
1462
1463/// Refresh old persisted wording without raising, relighting or delivering a notice.
1464fn refresh_disk_notices(home: &Path, task: &Task) {
1465    let notices = crate::notices::Notices::at(home.join("notifications"));
1466    let Some(task_notice) = crate::notices::task_held(task) else {
1467        return;
1468    };
1469    for (key, message) in [
1470        (task_notice.key, task_notice.message),
1471        (
1472            format!("disk:{}", repo_for(task).display()),
1473            format!(
1474                "Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.",
1475                task.id
1476            ),
1477        ),
1478    ] {
1479        let id = crate::notices::id_of(&key);
1480        if notices
1481            .get(&id)
1482            .is_ok_and(|n| n.key == key && n.message != message)
1483        {
1484            let _ = notices.update(&id, |n| {
1485                if n.key == key {
1486                    n.message = message;
1487                }
1488            });
1489        }
1490    }
1491}
1492
1493/// All source changes use the question lock; native decisions additionally use
1494/// their execution claim. Abandonment precedes requeue, so interrupted writes
1495/// leave a held task that the next pass can safely finish, never fake consent.
1496fn resume_disk_task(
1497    queue: &Queue,
1498    questions: &Questions,
1499    task: &mut Task,
1500    ownership: &crate::task_chat::InquiryOwnership,
1501) -> anyhow::Result<bool> {
1502    let expected = task.clone();
1503    let home = questions
1504        .root()
1505        .parent()
1506        .ok_or_else(|| anyhow::anyhow!("missing question home"))?;
1507    let _lease = if let Some(id) = task.disk_wait_run() {
1508        anyhow::ensure!(
1509            task.resume_override
1510                .as_ref()
1511                .and_then(|o| o.pinned_run.as_ref())
1512                .is_none_or(|pin| pin == id),
1513            "selected recovery run differs from disk wait evidence"
1514        );
1515        let state = crate::run::RunState::load_under(id, home)?;
1516        anyhow::ensure!(
1517            state.id == *id && state.status.resumable() && !task.fresh_start,
1518            "retained execution cannot resume"
1519        );
1520        anyhow::ensure!(
1521            state.liveness_under(
1522                home,
1523                crate::daemon::is_working_on(home, id, Timestamp::now())
1524            ) == crate::run::Liveness::Dead,
1525            "retained execution is not proven idle"
1526        );
1527        Some(crate::driver::maintenance(home, id)?)
1528    } else {
1529        None
1530    };
1531    let outbox = crate::task_inquiry::Outbox::at(home);
1532    let all = questions.list_for_effects_in(ownership);
1533    let pending: Vec<_> = all
1534        .iter()
1535        .filter(|q| {
1536            // Legacy task/run aliases are blockers, never supersession proof.
1537            (!q.run.is_empty()
1538                && std::iter::once(task.id.as_str())
1539                    .chain(task.execution_runs().iter().map(String::as_str))
1540                    .any(|id| id == q.run || id.starts_with(&q.run) || id.ends_with(&q.run)))
1541                && (q.status.open()
1542                    || ((q.node == NODE || q.node == DEPS_NODE)
1543                        && (awaiting_task_chat(q, task)
1544                            || (q.status == QuestionStatus::Answered
1545                                && !already_applied(task, q)))))
1546        })
1547        .collect();
1548    // Multiple questions or any different approval requires owner resolution.
1549    anyhow::ensure!(pending.len() <= 1, "multiple decisions remain");
1550    let candidate = pending.first().copied();
1551    if let Some(q) = candidate {
1552        anyhow::ensure!(untouched_disk_question(q, task), "owner decision remains");
1553    }
1554    for inquiry in outbox.pending()? {
1555        if inquiry.task == task.id && inquiry.decision.is_some() {
1556            anyhow::ensure!(
1557                candidate.is_some_and(|q| q.id == inquiry.id),
1558                "unrelated decision remains"
1559            );
1560        }
1561    }
1562    if let Some(q) = candidate {
1563        let _execution = outbox.execution_claim(&q.id)?;
1564        questions.update_in(&q.id, ownership, |current| {
1565            anyhow::ensure!(untouched_disk_question(current, task), "question changed");
1566            let inquiry = match outbox.get(&q.id) {
1567                Ok(inquiry) => inquiry,
1568                Err(error)
1569                    if error
1570                        .downcast_ref::<std::io::Error>()
1571                        .is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) =>
1572                {
1573                    anyhow::ensure!(
1574                        current.routed_chat.is_none(),
1575                        "delivered inquiry is missing; owner reconciliation required"
1576                    );
1577                    // Persist a no-effect native receipt even if delivery has
1578                    // not run yet. A concurrent producer replay preserves it.
1579                    outbox.enqueue(crate::task_chat::live_record(home, task, current))?
1580                }
1581                Err(error) => return Err(error),
1582            };
1583            anyhow::ensure!(
1584                inquiry.task == task.id
1585                    && inquiry.repo == task.repo
1586                    && inquiry.source == format!("{}:{}:{}", NODE, SEAT, task.id)
1587                    && current
1588                        .routed_chat
1589                        .as_ref()
1590                        .is_none_or(|chat| inquiry.delivered_to.as_ref() == Some(chat)),
1591                "inquiry binding changed"
1592            );
1593            outbox.update_decision(&q.id, |d| {
1594                if d.status == crate::task_decision::Status::Resolved {
1595                    anyhow::ensure!(
1596                        d.request.is_none()
1597                            && d.history
1598                                .last()
1599                                .is_some_and(|e| e.evidence == DISK_SUPERSEDED),
1600                        "decision already settled by owner"
1601                    );
1602                    return Ok(false);
1603                }
1604                anyhow::ensure!(
1605                    d.status == crate::task_decision::Status::AwaitingOwner
1606                        && d.request.is_none()
1607                        && d.source_answer_at.is_none(),
1608                    "owner request remains"
1609                );
1610                d.settle(DISK_SUPERSEDED)
1611            })?;
1612            current.abandon(DISK_SUPERSEDED);
1613            Ok(())
1614        })?;
1615    }
1616    if let Some(q) = candidate {
1617        task.mark_triage_applied(&q.id);
1618    }
1619    task.resume_disk_wait();
1620    queue.commit_disk_wait(task, &expected)?;
1621    let notices = crate::notices::Notices::at(home.join("notifications"));
1622    let keys = [
1623        format!("disk-recovered:{}", task.id),
1624        format!("disk:{}", repo_for(task).display()),
1625        format!("task:{}", task.id),
1626    ];
1627    let repo_waiting = queue
1628        .list()
1629        .iter()
1630        .any(|other| other.repo == task.repo && disk_wait_eligible(other));
1631    for notice in notices.list() {
1632        if notice.key == keys[0]
1633            || notice.key == keys[2]
1634            || (!repo_waiting && notice.key == keys[1])
1635        {
1636            let _ = notices.dismiss(&notice.id);
1637        }
1638    }
1639    Ok(candidate.is_some())
1640}
1641
1642/// Run one deterministic triage pass over every `held` task in `queue`. No
1643/// model call anywhere in this function - see this module's own doc for what
1644/// each `HoldSource` gets instead.
1645///
1646/// `config_override` is threaded straight to [`Config::discover`], the same
1647/// role `daemon::Opts::config` plays for `daemon::prepare` - an explicit
1648/// `--config` from the caller, or `None` to let each task's own repository
1649/// pick its layers.
1650///
1651/// Safe to call on every daemon idle tick and from `magi task triage` alike:
1652/// a task already answered and applied is left alone (see
1653/// [`already_applied`]), and a task with an open question is left alone too,
1654/// so repeated calls with nothing new to say do nothing.
1655///
1656/// Also runs [`quarantine_orphaned_blocked`], so a `blocked` task whose
1657/// dependency no longer exists is caught and turned into a fresh `held`
1658/// question in this same pass, not left for a later call to notice.
1659/// Reconcile held tasks and requeue proven resource recoveries without owner consent.
1660pub fn run_once(
1661    queue: &Queue,
1662    questions: &Questions,
1663    config_override: Option<&Path>,
1664    now: Timestamp,
1665) -> Report {
1666    run_once_inner(queue, questions, config_override, now, false)
1667}
1668
1669/// Existing maintenance service calls this even while other repositories run.
1670pub(crate) fn monitor_disk_waits(
1671    queue: &Queue,
1672    questions: &Questions,
1673    config: Option<&Path>,
1674    now: Timestamp,
1675) -> Report {
1676    run_once_inner(queue, questions, config, now, true)
1677}
1678
1679fn run_once_inner(
1680    queue: &Queue,
1681    questions: &Questions,
1682    config_override: Option<&Path>,
1683    now: Timestamp,
1684    disk_only: bool,
1685) -> Report {
1686    run_once_with_probe(
1687        queue,
1688        questions,
1689        config_override,
1690        now,
1691        disk_only,
1692        machine_cause_resolved,
1693    )
1694}
1695
1696fn run_once_with_probe(
1697    queue: &Queue,
1698    questions: &Questions,
1699    config_override: Option<&Path>,
1700    now: Timestamp,
1701    disk_only: bool,
1702    resolved: impl Fn(&Task, &Config) -> Option<bool>,
1703) -> Report {
1704    let mut report = Report {
1705        answered: if disk_only {
1706            Vec::new()
1707        } else {
1708            apply_answers(queue, questions)
1709        },
1710        quarantined: if disk_only {
1711            Vec::new()
1712        } else {
1713            quarantine_orphaned_blocked(queue, questions)
1714        },
1715        ..Report::default()
1716    };
1717    if !disk_only {
1718        ask_about_stuck_roots(queue, questions, config_override, &mut report);
1719    }
1720    let recovery = RecoveryIndex::load(questions);
1721    let ownership = crate::task_chat::InquiryOwnership::default();
1722    for listed in queue.list() {
1723        if listed.status != TaskStatus::Held {
1724            continue;
1725        }
1726        let Ok(_claim) = queue.claim(&listed.id) else {
1727            continue;
1728        };
1729        let Ok(mut task) = queue.get(&listed.id) else {
1730            continue;
1731        };
1732        // Re-read under the claim: a release or a re-hold landed by a human
1733        // between the listing above and the claim just taken must not be
1734        // clobbered by a decision based on the stale copy.
1735        if task.status != TaskStatus::Held {
1736            continue;
1737        }
1738        if crate::base_sync_recovery::held_task(queue, &task) {
1739            continue;
1740        }
1741        if !disk_only {
1742            match crate::head_e2e_stop::triage_status(queue, &task) {
1743                crate::head_e2e_stop::TriageStatus::NotHeadE2e => {}
1744                crate::head_e2e_stop::TriageStatus::HoldStillActive => continue,
1745                crate::head_e2e_stop::TriageStatus::ResolvedChanged => {
1746                    task.resume_head_e2e_wait();
1747                    if queue.put(&mut task).is_ok() {
1748                        report.resumed.push(task.id.clone());
1749                    }
1750                    continue;
1751                }
1752            }
1753        }
1754        if repair_receipt_notice(queue, &task) {
1755            continue;
1756        }
1757        // A question about what this task freezes is already the one question
1758        // it owes the operator; a second, about the hold itself, would ask two
1759        // things at once.
1760        // A monitored disk wait is exempt: a deps question opened before this
1761        // wait was recognised must not stop its recheck. The recovery path
1762        // itself refuses to resume past a question that needs the owner.
1763        if !disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new("")))
1764            && deps_pending_in(&recovery, &task)
1765        {
1766            continue;
1767        }
1768
1769        let explicit = match &task.overrides {
1770            Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
1771            _ => config_override,
1772        };
1773        let cfg = Config::discover(&repo_for(&task), explicit)
1774            .ok()
1775            .map(|(c, _)| c);
1776        let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1777
1778        if disk_wait_known(&task, questions.root().parent().unwrap_or(Path::new(""))) {
1779            if task
1780                .disk_checked_at
1781                .is_some_and(|at| now.as_second() - at.as_second() < 60)
1782            {
1783                continue;
1784            }
1785            let expected = task.clone();
1786            task.disk_checked_at = Some(now);
1787            if !task.has_disk_capacity_cause() {
1788                // Legacy exact-format migration only; never re-bind a stale cause.
1789                task.mark_disk_capacity();
1790            }
1791            if queue.commit_disk_wait(&mut task, &expected).is_err() {
1792                continue;
1793            }
1794            refresh_disk_notices(questions.root().parent().unwrap_or(Path::new("")), &task);
1795            // Even missing configuration/evidence stays a monitored wait. Never
1796            // turn measurement failure or continued pressure into an owner poll.
1797            if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1798                match resume_disk_task(queue, questions, &mut task, &ownership) {
1799                    Ok(superseded) => {
1800                        if superseded {
1801                            report.superseded.push(task.id.clone());
1802                        }
1803                        report.resumed.push(task.id.clone());
1804                    }
1805                    Err(error) => {
1806                        if !report.needs_owner.contains(&task.id) {
1807                            report.needs_owner.push(task.id.clone());
1808                        }
1809                        crate::notices::raise_in(
1810                        questions.root().parent().unwrap_or(Path::new("")),
1811                        crate::notices::Notice::warn(
1812                            &format!("disk-recovered:{}", task.id),
1813                            format!(
1814                                "Task {}: disk capacity recovered; automatic recovery is still blocked ({error}). Existing owner decisions and unrelated approvals require explicit resolution. Disk monitoring continues.",
1815                                task.id
1816                            ),
1817                        ).link(crate::notices::Link::Task { id: task.id.clone() }).about([task.id.clone()]),
1818                    );
1819                    }
1820                }
1821            }
1822            continue;
1823        }
1824        if disk_only {
1825            continue;
1826        }
1827
1828        if let Some(q) = recovery.latest(NODE, &task.id) {
1829            if !consumed(&task, &q) && (q.status.open() || awaiting_task_chat(&q, &task)) {
1830                // Already asked, still waiting - nothing to do this pass.
1831                continue;
1832            }
1833            // Abandoned, or an already-applied answer: fall through to the
1834            // ordinary per-source handling below, which is how a stale
1835            // `HoldSource::Manual` re-ask - or a fresh machine/legacy
1836            // question, once a prior one settled the task back into a hold -
1837            // gets filed.
1838        }
1839
1840        match task.hold_source {
1841            Some(HoldSource::Machine) => {
1842                let overridden = task
1843                    .resume_override
1844                    .as_ref()
1845                    .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1846                if overridden {
1847                    if file_question(
1848                        questions,
1849                        &ownership,
1850                        &task,
1851                        Bucket::ConductorOverride,
1852                        w,
1853                        now,
1854                    )
1855                    .is_some()
1856                    {
1857                        report.asked.push(task.id.clone());
1858                    }
1859                } else if cfg.as_ref().and_then(|c| resolved(&task, c)) == Some(true) {
1860                    task.release();
1861                    if queue.put(&mut task).is_ok() {
1862                        report.resumed.push(task.id.clone());
1863                    }
1864                } else if !known_isolated_cache_wait(&task, &crate::run::home())
1865                    && file_question(questions, &ownership, &task, Bucket::MachineUnknown, w, now)
1866                        .is_some()
1867                {
1868                    report.asked.push(task.id.clone());
1869                }
1870            }
1871            None => {
1872                if file_question(questions, &ownership, &task, Bucket::Legacy, w, now).is_some() {
1873                    report.asked.push(task.id.clone());
1874                }
1875            }
1876            Some(HoldSource::Manual) => {
1877                if manual_is_stale(&task, now)
1878                    && file_question(questions, &ownership, &task, Bucket::ManualStale, w, now)
1879                        .is_some()
1880                {
1881                    report.asked.push(task.id.clone());
1882                }
1883            }
1884        }
1885    }
1886    report
1887}
1888
1889/// The open triage question about `task_id`, if any - what `magi task show`
1890/// prints so a held task's card names the question waiting on it, not only
1891/// its hold reason. `None` once it is answered or abandoned: nothing is
1892/// waiting on it anymore.
1893pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1894    let queue = question_queue(questions);
1895    let task = queue.get(task_id).ok()?;
1896    display_index(questions, &queue, std::slice::from_ref(&task)).displayed_open(&task)
1897}
1898
1899/// Does this module still have unfinished business with `task`?
1900///
1901/// True while its latest triage question is still open (waiting on an
1902/// answer), and true for a beat longer than [`open_question_for`] alone
1903/// would say: once answered, the question sits [`QuestionStatus::Answered`]
1904/// but unread until the next [`run_once`] pass actually applies it (see
1905/// [`already_applied`]), and [`run_once`] only ever runs on a fully idle
1906/// daemon tick - far less often than `crate::conduct` polls. A caller that
1907/// only checked "is a question open" would walk straight through that gap
1908/// the moment the operator answers, moving the task out of `held` before
1909/// [`run_once`] gets a turn - orphaning the very answer it was about to
1910/// apply, the same failure mode this function exists to keep `crate::conduct`
1911/// out of. `crate::conduct::apply_one` is exactly that caller.
1912pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1913    !pending_recovery_questions(questions, task).is_empty()
1914}
1915
1916/// The exact recovery decisions that prevent triage/conductor progress,
1917/// including routed decisions and answers not yet applied to this task.
1918pub(crate) fn pending_recovery_questions(questions: &Questions, task: &Task) -> Vec<Question> {
1919    RecoveryIndex::load(questions).pending(task)
1920}
1921
1922fn awaiting_task_chat(q: &Question, task: &Task) -> bool {
1923    q.status != QuestionStatus::Abandoned
1924        && q.routed_chat.is_some()
1925        && !already_applied(task, q)
1926        && task.resumption.as_ref().map_or(0, |r| r.generation) == q.triage_generation.unwrap_or(0)
1927        && task.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1928}
1929
1930/// Is the latest [`DEPS_NODE`] question about `task` still open, or answered
1931/// but not yet applied? Same reasoning as [`pending_for`]: the gap between an
1932/// answer and the next [`run_once`] pass must not be walked through.
1933fn deps_pending_in(recovery: &RecoveryIndex, task: &Task) -> bool {
1934    match recovery.latest(DEPS_NODE, &task.id) {
1935        Some(q) if consumed(task, &q) => false,
1936        Some(q) if q.status.open() || awaiting_task_chat(&q, task) => true,
1937        Some(q) if q.status == QuestionStatus::Answered => true,
1938        _ => false,
1939    }
1940}
1941
1942/// Every task id with an open triage question right now - what `magi task
1943/// list` uses to mark a held task that is already waiting on an operator
1944/// decision, rather than have it read identically to one nobody has looked
1945/// at yet.
1946pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1947    let queue = question_queue(questions);
1948    let tasks = queue.list();
1949    let index = display_index(questions, &queue, &tasks);
1950    tasks
1951        .iter()
1952        .filter(|task| index.displayed_open(task).is_some())
1953        .map(|task| task.id.clone())
1954        .collect()
1955}
1956
1957fn question_queue(questions: &Questions) -> Queue {
1958    Queue::at(
1959        questions
1960            .root()
1961            .parent()
1962            .unwrap_or(Path::new(""))
1963            .join("queue"),
1964    )
1965}
1966
1967/// Presentation reads saved answers, never the execution-only migration fence.
1968fn display_index(questions: &Questions, queue: &Queue, tasks: &[Task]) -> RecoveryIndex {
1969    RecoveryIndex::from_scan(queue, tasks, questions.list())
1970}
1971
1972#[cfg(test)]
1973mod tests {
1974    use super::*;
1975    use crate::ask::Answer;
1976    use crate::queue::Source;
1977    use jiff::SignedDuration;
1978
1979    fn store() -> (tempfile::TempDir, Queue, Questions) {
1980        let dir = tempfile::tempdir().unwrap();
1981        let q = Queue::at(dir.path().join("queue"));
1982        let s = Questions::at(dir.path().join("questions"));
1983        (dir, q, s)
1984    }
1985
1986    fn task(title: &str, repo: PathBuf) -> Task {
1987        Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
1988    }
1989
1990    fn disk_task(repo: PathBuf) -> Task {
1991        let mut t = task("capacity", repo);
1992        t.hold_machine(crate::disk::gate_in(1_477_050_368, 3_221_225_472, "ja"));
1993        t.mark_disk_capacity();
1994        t.attempts = 3;
1995        t
1996    }
1997
1998    #[test]
1999    fn disk_wait_repeated_pressure_measurement_failure_and_recovery_cost_nothing() {
2000        let (dir, queue, questions) = store();
2001        let cfg = gate_disabled_config(dir.path());
2002        let mut t = disk_task(dir.path().to_owned());
2003        queue.put(&mut t).unwrap();
2004        let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2005        let before = serde_json::to_value(notices.list()).unwrap();
2006        let start = Timestamp::now();
2007        let probes = std::cell::Cell::new(0);
2008        for seconds in [0, 1, 10, 60, 61, 120] {
2009            let report = run_once_with_probe(
2010                &queue,
2011                &questions,
2012                Some(&cfg),
2013                start + SignedDuration::from_secs(seconds),
2014                true,
2015                |_, _| {
2016                    probes.set(probes.get() + 1);
2017                    Some(false) // includes a failed measurement: never permission
2018                },
2019            );
2020            assert!(report.is_empty());
2021            assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2022        }
2023        assert_eq!(
2024            probes.get(),
2025            3,
2026            "resource probes are bounded to one per minute"
2027        );
2028        assert!(questions.list().is_empty());
2029        assert_eq!(serde_json::to_value(notices.list()).unwrap(), before);
2030        let recovered = run_once_with_probe(
2031            &queue,
2032            &questions,
2033            Some(&cfg),
2034            start + SignedDuration::from_secs(180),
2035            true,
2036            |_, _| Some(true),
2037        );
2038        assert_eq!(recovered.resumed, [t.id.clone()]);
2039        let saved = queue.get(&t.id).unwrap();
2040        assert_eq!(saved.status, TaskStatus::Queued);
2041        assert_eq!(saved.attempts, 3);
2042        let again = run_once_with_probe(
2043            &queue,
2044            &questions,
2045            Some(&cfg),
2046            start + SignedDuration::from_secs(240),
2047            true,
2048            |_, _| panic!("queued tasks are not relaunched"),
2049        );
2050        assert!(again.is_empty());
2051    }
2052
2053    #[test]
2054    fn disk_wait_supersedes_only_untouched_automatic_questions_in_both_stores() {
2055        for routed in [false, true] {
2056            let (dir, queue, questions) = store();
2057            let cfg = gate_disabled_config(dir.path());
2058            let mut t = disk_task(dir.path().to_owned());
2059            queue.put(&mut t).unwrap();
2060            let q = file_question(
2061                &questions,
2062                &crate::task_chat::InquiryOwnership::default(),
2063                &t,
2064                Bucket::MachineUnknown,
2065                &JA,
2066                Timestamp::now(),
2067            )
2068            .unwrap();
2069            if routed {
2070                crate::task_chat::sweep(
2071                    &queue,
2072                    &crate::talk::Talks::at(dir.path().join("talks")),
2073                    &questions,
2074                    dir.path(),
2075                );
2076                assert!(
2077                    crate::task_inquiry::Outbox::at(dir.path())
2078                        .get(&q.id)
2079                        .is_ok()
2080                );
2081            }
2082            let start = Timestamp::now();
2083            for seconds in [0, 60, 120] {
2084                assert!(
2085                    run_once_with_probe(
2086                        &queue,
2087                        &questions,
2088                        Some(&cfg),
2089                        start + SignedDuration::from_secs(seconds),
2090                        true,
2091                        |_, _| Some(false)
2092                    )
2093                    .is_empty()
2094                );
2095                assert!(questions.read_history(&q.id).unwrap().status.open());
2096                assert_eq!(questions.list().len(), 1);
2097            }
2098            let report = monitor_disk_waits(
2099                &queue,
2100                &questions,
2101                Some(&cfg),
2102                start + SignedDuration::from_secs(180),
2103            );
2104            assert_eq!(report.resumed, [t.id.clone()], "routed={routed}");
2105            let source = questions.read_history(&q.id).unwrap();
2106            assert_eq!(source.status, QuestionStatus::Abandoned);
2107            assert!(source.answer.is_none());
2108            assert!(source.answered_at.is_none());
2109            assert!(!pending_for(&questions, &queue.get(&t.id).unwrap()));
2110            if routed {
2111                let d = crate::task_inquiry::Outbox::at(dir.path())
2112                    .get(&q.id)
2113                    .unwrap()
2114                    .decision
2115                    .unwrap();
2116                assert_eq!(d.status, crate::task_decision::Status::Resolved);
2117                assert!(
2118                    d.request.is_none(),
2119                    "system supersession fabricates no owner request"
2120                );
2121            }
2122        }
2123    }
2124
2125    #[test]
2126    fn disk_wait_respects_owner_hold_discussion_and_unrelated_approvals() {
2127        for kind in [
2128            "manual",
2129            "answered",
2130            "discussion",
2131            "unrelated",
2132            "override",
2133            "native-hold",
2134            "missing-native",
2135        ] {
2136            let (dir, queue, questions) = store();
2137            let cfg = gate_disabled_config(dir.path());
2138            let mut t = disk_task(dir.path().to_owned());
2139            queue.put(&mut t).unwrap();
2140            let q = file_question(
2141                &questions,
2142                &crate::task_chat::InquiryOwnership::default(),
2143                &t,
2144                Bucket::MachineUnknown,
2145                &EN,
2146                Timestamp::now(),
2147            )
2148            .unwrap();
2149            match kind {
2150                "manual" => {
2151                    t.hold_manual(Some("owner hold".into()));
2152                    queue.put(&mut t).unwrap();
2153                }
2154                "answered" => {
2155                    questions
2156                        .update(&q.id, |q| q.answer(Answer::Choice(q.choices[1].clone())))
2157                        .unwrap();
2158                }
2159                "discussion" => {
2160                    questions
2161                        .update(&q.id, |q| q.say("please wait".to_owned()))
2162                        .unwrap();
2163                }
2164                "unrelated" => {
2165                    questions
2166                        .update(&q.id, |q| {
2167                            q.node = "land".into();
2168                            Ok(())
2169                        })
2170                        .unwrap();
2171                }
2172                "override" => {
2173                    t.resume_override = Some(OperatorResume {
2174                        question_id: "owner".into(),
2175                        at: Timestamp::now(),
2176                        conductor_rehold: Some("pending conductor decision".into()),
2177                        forced: true,
2178                        pinned_run: None,
2179                    });
2180                    queue.put(&mut t).unwrap();
2181                }
2182                "native-hold" | "missing-native" => {
2183                    crate::task_chat::sweep(
2184                        &queue,
2185                        &crate::talk::Talks::at(dir.path().join("talks")),
2186                        &questions,
2187                        dir.path(),
2188                    );
2189                    if kind == "native-hold" {
2190                        crate::task_inquiry::Outbox::at(dir.path())
2191                            .update_decision(&q.id, |d| d.accept("owner requested hold"))
2192                            .unwrap();
2193                    } else {
2194                        // Whether the sweep could route to a chat depends on the
2195                        // installed agents; record the delivery explicitly so the
2196                        // missing record means "delivered but lost", not "undelivered".
2197                        questions
2198                            .update(&q.id, |q| {
2199                                q.routed_chat = Some("delivered-chat".into());
2200                                Ok(())
2201                            })
2202                            .unwrap();
2203                        std::fs::remove_file(
2204                            dir.path()
2205                                .join("notifications/task-inquiries")
2206                                .join(format!("{}.json", q.id)),
2207                        )
2208                        .unwrap();
2209                    }
2210                }
2211                _ => unreachable!(),
2212            }
2213            let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2214            assert!(report.resumed.is_empty(), "{kind}");
2215            assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held, "{kind}");
2216            assert!(
2217                questions.read_history(&q.id).unwrap().status != QuestionStatus::Abandoned,
2218                "{kind}"
2219            );
2220        }
2221    }
2222
2223    #[test]
2224    fn startup_disk_wait_probes_the_task_override_and_does_not_pin_history() {
2225        use crate::config::BuildCache;
2226        // `disk_wait_eligible` reads the process home; without this the test
2227        // passes only when another test in the same process pinned it first.
2228        crate::run::pin_test_home();
2229        let (dir, queue, questions) = store();
2230        let shared = dir.path().join("shared");
2231        let isolated = crate::build_target::root(dir.path());
2232        let mut config = Config::default();
2233        config.disk.min_free_bytes = 0;
2234        config.graph.worktree_root = Some(dir.path().to_owned());
2235        config.verify.gate = vec![format!(
2236            "CARGO_TARGET_DIR='{}' cargo check",
2237            shared.display()
2238        )];
2239        let mut task = disk_task(dir.path().to_owned());
2240        task.mark_startup_disk_capacity();
2241        task.overrides = Some(crate::queue::RunOverrides {
2242            build_cache: Some(BuildCache::Isolated),
2243            ..Default::default()
2244        });
2245        let check = |task: &Task, config: &Config, blocked: &Path| {
2246            machine_cause_resolved_with_admission(task, config, dir.path(), |paths, _| {
2247                !paths.iter().any(|path| path == blocked)
2248            })
2249        };
2250        assert_eq!(check(&task, &config, &isolated), Some(false));
2251        assert_eq!(check(&task, &config, &shared), Some(true));
2252        config.verify.build_cache = BuildCache::Isolated;
2253        task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2254        assert_eq!(check(&task, &config, &shared), Some(false));
2255        assert_eq!(check(&task, &config, &isolated), Some(true));
2256        task.urgent = true;
2257        config.verify.build_cache = BuildCache::Shared;
2258        task.overrides.as_mut().unwrap().build_cache = None;
2259        assert_eq!(check(&task, &config, &isolated), Some(false));
2260        assert_eq!(check(&task, &config, &shared), Some(true));
2261        task.overrides.as_mut().unwrap().build_cache = Some(BuildCache::Shared);
2262
2263        task.runs.push("historical-execution".into());
2264        queue.put(&mut task).unwrap();
2265        let cfg = gate_disabled_config(dir.path());
2266        let report = run_once_with_probe(
2267            &queue,
2268            &questions,
2269            Some(&cfg),
2270            Timestamp::now(),
2271            true,
2272            |task, _| check(task, &config, &isolated),
2273        );
2274        assert_eq!(report.resumed, [task.id.clone()]);
2275        let saved = queue.get(&task.id).unwrap();
2276        assert_eq!(saved.attempts, task.attempts);
2277        assert_eq!(saved.runs, task.runs);
2278        assert!(saved.disk_resume_run.is_none());
2279    }
2280
2281    #[test]
2282    fn disk_wait_reuses_retained_execution_and_preserves_attempt_and_approval_evidence() {
2283        let (dir, queue, questions) = store();
2284        let cfg = gate_disabled_config(dir.path());
2285        let mut run = crate::run::RunState::new(
2286            dir.path().to_owned(),
2287            "main".into(),
2288            "base".into(),
2289            "capacity".into(),
2290            Config::default(),
2291        );
2292        run.status = crate::run::RunStatus::Blocked;
2293        run.driver_exited = true;
2294        run.save_under(dir.path()).unwrap();
2295        let mut t = disk_task(dir.path().to_owned());
2296        t.runs.push(run.id.clone());
2297        t.resume_override = Some(OperatorResume {
2298            question_id: "approved-recovery".into(),
2299            at: Timestamp::now(),
2300            conductor_rehold: None,
2301            forced: true,
2302            pinned_run: Some(run.id.clone()),
2303        });
2304        queue.put(&mut t).unwrap();
2305        let before = std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap();
2306        let report = run_once_with_probe(
2307            &queue,
2308            &questions,
2309            Some(&cfg),
2310            Timestamp::now(),
2311            true,
2312            |_, _| Some(true),
2313        );
2314        assert_eq!(report.resumed, [t.id.clone()]);
2315        let resumed = queue.get(&t.id).unwrap();
2316        assert_eq!(resumed.runs, t.runs);
2317        assert_eq!(resumed.disk_resume_run.as_deref(), Some(run.id.as_str()));
2318        assert_eq!(resumed.attempts, t.attempts);
2319        assert_eq!(resumed.resumption, t.resumption);
2320        assert_eq!(
2321            serde_json::to_value(&resumed.resume_override).unwrap(),
2322            serde_json::to_value(&t.resume_override).unwrap()
2323        );
2324        assert_eq!(
2325            std::fs::read(dir.path().join("runs").join(&run.id).join("run.json")).unwrap(),
2326            before
2327        );
2328        assert!(
2329            run_once_with_probe(
2330                &queue,
2331                &questions,
2332                Some(&cfg),
2333                Timestamp::now(),
2334                true,
2335                |_, _| panic!("no duplicate launch")
2336            )
2337            .is_empty()
2338        );
2339    }
2340
2341    #[test]
2342    fn disk_wait_interrupted_question_supersession_is_idempotent() {
2343        for abandoned in [false, true] {
2344            let (dir, queue, questions) = store();
2345            let cfg = gate_disabled_config(dir.path());
2346            let mut t = disk_task(dir.path().to_owned());
2347            queue.put(&mut t).unwrap();
2348            let q = file_question(
2349                &questions,
2350                &crate::task_chat::InquiryOwnership::default(),
2351                &t,
2352                Bucket::MachineUnknown,
2353                &EN,
2354                Timestamp::now(),
2355            )
2356            .unwrap();
2357            let outbox = crate::task_inquiry::Outbox::at(dir.path());
2358            outbox
2359                .enqueue(crate::task_chat::live_record(dir.path(), &t, &q))
2360                .unwrap();
2361            outbox
2362                .update_decision(&q.id, |d| d.settle(DISK_SUPERSEDED))
2363                .unwrap();
2364            if abandoned {
2365                questions
2366                    .update(&q.id, |q| {
2367                        q.abandon(DISK_SUPERSEDED);
2368                        Ok(())
2369                    })
2370                    .unwrap();
2371            }
2372            let report = monitor_disk_waits(&queue, &questions, Some(&cfg), Timestamp::now());
2373            assert_eq!(report.resumed, [t.id.clone()]);
2374            assert_eq!(queue.get(&t.id).unwrap().attempts, 3);
2375            assert!(questions.read_history(&q.id).unwrap().answer.is_none());
2376            assert_eq!(
2377                outbox.get(&q.id).unwrap().decision.unwrap().history.len(),
2378                1
2379            );
2380        }
2381    }
2382
2383    #[test]
2384    fn disk_wait_legacy_migration_requires_machine_provenance_and_exact_localized_format() {
2385        let (dir, queue, _) = store();
2386        for (language, source, suffix, expected) in [
2387            ("en", Some(HoldSource::Machine), "", true),
2388            ("ja", Some(HoldSource::Machine), "", true),
2389            ("ja", Some(HoldSource::Manual), "", false),
2390            ("ja", None, "", false),
2391            ("ja", Some(HoldSource::Machine), " owner hold", false),
2392        ] {
2393            let mut t = task("legacy", dir.path().to_owned());
2394            t.hold_machine(Some(format!(
2395                "{}{suffix}",
2396                crate::disk::gate_in(1477050368, 3221225472, language).unwrap()
2397            )));
2398            t.schema = 21;
2399            t.hold_source = source;
2400            queue.put(&mut t).unwrap();
2401            let loaded = queue.get(&t.id).unwrap();
2402            assert_eq!(loaded.machine_hold_cause.is_some(), expected);
2403            assert_eq!(disk_wait_eligible(&loaded), expected);
2404        }
2405    }
2406
2407    #[test]
2408    fn disk_wait_refreshes_stale_notice_wording_without_redelivery() {
2409        let (dir, queue, questions) = store();
2410        let cfg = gate_disabled_config(dir.path());
2411        let mut t = disk_task(dir.path().to_owned());
2412        queue.put(&mut t).unwrap();
2413        let notices = crate::notices::Notices::at(dir.path().join("notifications"));
2414        let key = format!("disk:{}", t.repo.display());
2415        let n = notices
2416            .raise(crate::notices::Notice::warn(
2417                &key,
2418                "Free some, then release it from the queue.",
2419            ))
2420            .unwrap();
2421        notices.mark_read(&n.id).unwrap();
2422        let before = notices.get(&n.id).unwrap();
2423        let report = run_once_with_probe(
2424            &queue,
2425            &questions,
2426            Some(&cfg),
2427            Timestamp::now(),
2428            true,
2429            |_, _| Some(false),
2430        );
2431        assert!(report.is_empty());
2432        let after = notices.get(&n.id).unwrap();
2433        assert!(after.message.contains("automatically"));
2434        assert_eq!(before.generation, after.generation);
2435        assert_eq!(before.count, after.count);
2436        assert_eq!(before.read_at, after.read_at);
2437    }
2438
2439    #[test]
2440    fn disk_wait_owner_discard_is_applied_without_automatic_resumption() {
2441        let (dir, queue, questions) = store();
2442        let cfg = gate_disabled_config(dir.path());
2443        let mut t = disk_task(dir.path().to_owned());
2444        queue.put(&mut t).unwrap();
2445        let q = file_question(
2446            &questions,
2447            &crate::task_chat::InquiryOwnership::default(),
2448            &t,
2449            Bucket::MachineUnknown,
2450            &EN,
2451            Timestamp::now(),
2452        )
2453        .unwrap();
2454        questions
2455            .update(&q.id, |q| q.answer(Answer::Choice(q.choices[2].clone())))
2456            .unwrap();
2457        let report = run_once(&queue, &questions, Some(&cfg), Timestamp::now());
2458        assert!(report.resumed.is_empty());
2459        assert!(queue.get(&t.id).is_err());
2460        assert!(questions.read_history(&q.id).unwrap().answer.is_some());
2461    }
2462
2463    #[test]
2464    fn disk_wait_commit_cannot_overwrite_a_concurrent_owner_hold() {
2465        let (dir, queue, questions) = store();
2466        let mut stale = disk_task(dir.path().to_owned());
2467        queue.put(&mut stale).unwrap();
2468        let mut current = queue.get(&stale.id).unwrap();
2469        current.hold_manual(Some("wait for owner".into()));
2470        queue.put(&mut current).unwrap();
2471        assert!(
2472            resume_disk_task(
2473                &queue,
2474                &questions,
2475                &mut stale,
2476                &crate::task_chat::InquiryOwnership::default()
2477            )
2478            .is_err()
2479        );
2480        assert_eq!(
2481            queue.get(&current.id).unwrap().hold_source,
2482            Some(HoldSource::Manual)
2483        );
2484    }
2485
2486    #[test]
2487    fn recovery_index_preserves_supersession_and_ambiguous_file_references() {
2488        let (dir, queue, questions) = store();
2489        let mut t = task("supersession", dir.path().join("repo"));
2490        t.id = "task-alpha-end".into();
2491        queue.put(&mut t).unwrap();
2492        let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2493        let mut all = Vec::new();
2494        for (i, run) in ["task-alpha-end", "task-alpha", "end"]
2495            .into_iter()
2496            .enumerate()
2497        {
2498            let mut q = Question::new(
2499                run.into(),
2500                NODE.into(),
2501                SEAT.into(),
2502                "superseded".into(),
2503                String::new(),
2504                EN.choices3(),
2505            );
2506            q.id = format!("superseded-{i}");
2507            q.asked_at = at;
2508            all.push(q);
2509        }
2510        let evidence: Vec<_> = all
2511            .iter()
2512            .map(|q| {
2513                (
2514                    q.id.clone(),
2515                    crate::repair_budget::reconcile::source(q).unwrap(),
2516                )
2517            })
2518            .collect();
2519        t.repair_reconciliations.push(
2520            serde_json::from_value(serde_json::json!({
2521                "request": {
2522                    "task": t.id, "run": "run", "head": "head", "expect_pass": 0,
2523                    "receipt": "grant", "question": "original", "answer_at": at,
2524                    "request": "reconcile", "reason": "fixture"
2525                },
2526                "grant": {
2527                    "request": {
2528                        "task": t.id, "run": "run", "kind": "review", "rounds": 1,
2529                        "head": "head", "expect_pass": 0, "request": "grant", "reason": "fixture"
2530                    },
2531                    "at": at, "decision": null, "contract": "fixture"
2532                },
2533                "source": "fixture", "application": "fixture", "decision": at,
2534                "superseded_questions": evidence
2535            }))
2536            .unwrap(),
2537        );
2538        queue.put(&mut t).unwrap();
2539        let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2540        assert!(index.latest.is_empty());
2541        // Unreadable filenames still make prefixes and suffixes ambiguous.
2542        std::fs::write(queue.path_of("task-alphabet-other"), "{").unwrap();
2543        std::fs::write(queue.path_of("broken-end"), "{").unwrap();
2544        let index = RecoveryIndex::from_scan(&queue, &[t.clone()], all.clone());
2545        assert!(index.latest(NODE, "end").is_some());
2546        assert!(index.latest(NODE, "task-alpha").is_some());
2547        assert!(index.latest(NODE, &t.id).is_none());
2548        all[0].detail.push_str("changed evidence");
2549        let index = RecoveryIndex::from_scan(&queue, &[t], all);
2550        assert!(index.latest(NODE, "task-alpha-end").is_some());
2551        assert_eq!(questions.list().len(), 0);
2552    }
2553
2554    #[test]
2555    fn ownership_index_requires_positive_foreground_provenance() {
2556        let (dir, queue, _) = store();
2557        let mut run = crate::run::RunState::new(
2558            dir.path().join("repo"),
2559            "main".into(),
2560            "origin".into(),
2561            "fixture".into(),
2562            Config::default(),
2563        );
2564        run.origin = Some(crate::run::Origin::operator());
2565        run.save_under(dir.path()).unwrap();
2566        let foreground = run.id.clone();
2567        run.id = "owned-run".into();
2568        run.origin = Some(crate::run::Origin::queue("missing-task"));
2569        run.save_under(dir.path()).unwrap();
2570        let mut task = task("owner", dir.path().join("repo"));
2571        task.runs = vec!["linked-run".into()];
2572        queue.put(&mut task).unwrap();
2573        let ownership = crate::task_chat::InquiryOwnership::default();
2574        for (run, cwd, node, seat, expected) in [
2575            (foreground.as_str(), true, "node", "seat", true),
2576            (foreground.as_str(), false, "node", "seat", false),
2577            ("owned-run", true, "ask", "operator", false),
2578            ("linked-run", true, "ask", "operator", false),
2579            ("missing-run", true, "node", "seat", false),
2580            ("missing-run", false, "ask", "operator", true),
2581        ] {
2582            let mut q = Question::new(
2583                run.into(),
2584                node.into(),
2585                seat.into(),
2586                "provenance".into(),
2587                String::new(),
2588                Vec::new(),
2589            );
2590            q.cwd = cwd.then(|| dir.path().join("repo").display().to_string());
2591            assert_eq!(standalone_by_scanning(dir.path(), &q), expected);
2592            assert_eq!(
2593                crate::task_chat::standalone_inquiry_in(dir.path(), &q, &ownership),
2594                expected
2595            );
2596        }
2597    }
2598
2599    // Deliberately retain the pre-index predicate as an independent oracle.
2600    fn standalone_by_scanning(home: &Path, q: &Question) -> bool {
2601        if q.routed_task.is_some()
2602            || (q.node == crate::bump::NOTICE_NODE && q.seat == "release-watch")
2603        {
2604            return false;
2605        }
2606        if q.legacy_foreground || q.run.is_empty() {
2607            return true;
2608        }
2609        if Queue::at(home.join("queue"))
2610            .list()
2611            .iter()
2612            .any(|task| task.id == q.run || task.runs.contains(&q.run))
2613        {
2614            return false;
2615        }
2616        let run = crate::run::RunState::load_under(&q.run, home).ok();
2617        let origin = run.as_ref().and_then(|run| run.origin.as_ref());
2618        if origin.is_some_and(|origin| origin.task.is_some()) {
2619            return false;
2620        }
2621        (q.node == "ask" && q.seat == "operator")
2622            || (q.cwd.is_some() && origin.is_some_and(|origin| origin.task.is_none()))
2623    }
2624
2625    fn scan_counts() -> (usize, usize, usize) {
2626        (
2627            crate::queue::LIST_READS.with(|c| c.replace(0)),
2628            crate::queue::TASK_READS.with(|c| c.replace(0)),
2629            crate::ask::QUESTION_SCANS.with(|c| c.replace(0)),
2630        )
2631    }
2632
2633    #[test]
2634    fn creating_and_updating_questions_share_one_queue_read() {
2635        let (dir, queue, questions) = store();
2636        let size = 200;
2637        let mut ids = Vec::new();
2638        for i in 0..size {
2639            let mut t = task("scan fixture", dir.path().join("repo"));
2640            t.id = format!("task-{i:04}");
2641            t.runs = vec![format!("run-{i:04}")];
2642            t.hold_manual(Some("held for scan fixture".into()));
2643            queue.put(&mut t).unwrap();
2644            ids.push(t.id);
2645        }
2646        let ownership = crate::task_chat::InquiryOwnership::default();
2647        scan_counts();
2648        let mut created = Vec::new();
2649        for id in &ids {
2650            let mut q = Question::new(
2651                id.clone(),
2652                NODE.into(),
2653                SEAT.into(),
2654                "scan fixture".into(),
2655                String::new(),
2656                EN.choices3(),
2657            );
2658            questions.put_executable_in(&mut q, &ownership).unwrap();
2659            assert_eq!(q.routed_task.as_deref(), Some(id.as_str()));
2660            created.push(q.id);
2661        }
2662        for id in &created {
2663            questions
2664                .update_in(id, &ownership, |q| {
2665                    q.answer_delivered = true;
2666                    Ok(())
2667                })
2668                .unwrap();
2669        }
2670        let (lists, _, _) = scan_counts();
2671        assert_eq!(lists, 1, "one queue read for {size} creations and updates");
2672    }
2673
2674    #[test]
2675    fn recovery_scans_are_linear_and_match_legacy_decisions() {
2676        let mut previous = None;
2677        for size in [150, 300] {
2678            let (dir, queue, questions) = store();
2679            let at: Timestamp = "2026-11-01T00:00:00Z".parse().unwrap();
2680            let mut sources = Vec::new();
2681            let mut expected_applied = std::collections::BTreeSet::new();
2682            for i in 0..size {
2683                let mut t = task("scan fixture", dir.path().join("repo"));
2684                t.id = format!("task-{i:04}");
2685                t.runs = vec![format!("run-{i:04}")];
2686                t.hold_manual(Some("held for scan fixture".into()));
2687                queue.put(&mut t).unwrap();
2688                let mut q = Question::new(
2689                    t.id.clone(),
2690                    NODE.into(),
2691                    SEAT.into(),
2692                    "scan fixture".into(),
2693                    String::new(),
2694                    EN.choices3(),
2695                );
2696                q.id = format!("question-{i:04}");
2697                q.asked_at = at;
2698                match i % 10 {
2699                    0 => {
2700                        q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
2701                        q.accepted_answer_at = q.answered_at;
2702                        expected_applied.insert(t.id.clone());
2703                    }
2704                    1 => q.node = DEPS_NODE.into(),
2705                    2 => {
2706                        q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2707                    }
2708                    3 => {
2709                        q.run = format!("missing-{i}");
2710                        q.legacy_foreground = true;
2711                    }
2712                    4 => {
2713                        q.run.clear();
2714                        q.node = crate::bump::NOTICE_NODE.into();
2715                        q.seat = "release-watch".into();
2716                    }
2717                    5 => {
2718                        q.run = format!("missing-{i}");
2719                        q.node = "ask".into();
2720                        q.seat = "operator".into();
2721                    }
2722                    6 => q.run = t.runs[0].clone(),
2723                    7 => q.run = format!("missing-{i}"),
2724                    8 => q.abandon("fixture"),
2725                    _ => {}
2726                }
2727                questions.put(&mut q).unwrap();
2728                sources.push(q.id.clone());
2729                if i % 10 == 9 {
2730                    q.id = format!("question-{i:04}-tie");
2731                    questions.put(&mut q).unwrap();
2732                    sources.push(q.id.clone());
2733                }
2734            }
2735            let migration = dir.path().join("notifications/task-chat-migration-v1");
2736            std::fs::create_dir_all(&migration).unwrap();
2737            std::fs::write(
2738                migration.join("state.json"),
2739                serde_json::to_vec(&serde_json::json!({
2740                    "schema": 1, "classification_revision": 1, "pending": [], "sources": sources
2741                }))
2742                .unwrap(),
2743            )
2744            .unwrap();
2745
2746            scan_counts();
2747            let all = questions.list_for_effects();
2748            let (lists, reads, scans) = scan_counts();
2749            assert_eq!((lists, reads, scans), (1, size, 1));
2750            let tasks = queue.list();
2751            let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
2752            for q in &all {
2753                assert_eq!(
2754                    crate::task_chat::standalone_inquiry_in(dir.path(), q, &ownership),
2755                    standalone_by_scanning(dir.path(), q),
2756                    "{}",
2757                    q.id,
2758                );
2759                if q.id.ends_with("0002") {
2760                    assert!(q.answer.is_none(), "saved consent remains fenced");
2761                }
2762            }
2763            let recovery = RecoveryIndex::from_scan(&queue, &tasks, all.clone());
2764            for task in &tasks {
2765                for node in [NODE, DEPS_NODE] {
2766                    let expected = all
2767                        .iter()
2768                        .filter(|q| {
2769                            q.node == node
2770                                && q.run == task.id
2771                                && !queue.get(&q.run).ok().is_some_and(|t| {
2772                                    crate::repair_budget::reconcile::superseded_question(&t, q)
2773                                })
2774                        })
2775                        .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
2776                    assert_eq!(
2777                        recovery.latest(node, &task.id).map(|q| q.id),
2778                        expected.map(|q| q.id.clone())
2779                    );
2780                }
2781            }
2782
2783            scan_counts();
2784            crate::daemon::apply_task_choice_actions(&queue, &questions, dir.path());
2785            assert_eq!(
2786                scan_counts(),
2787                (1, size, 1),
2788                "choice-action rechecks share ownership"
2789            );
2790
2791            scan_counts();
2792            let applied: std::collections::BTreeSet<_> =
2793                apply_answers(&queue, &questions).into_iter().collect();
2794            let counts = scan_counts();
2795            assert_eq!(applied, expected_applied);
2796            assert!(counts.0 <= 3, "queue scans: {counts:?}");
2797            assert!(counts.1 <= 4 * size, "task reads: {counts:?}");
2798            assert_eq!(counts.2, 2, "question scans: {counts:?}");
2799            if let Some((_, reads, scans)) = previous {
2800                assert!(counts.1 <= 2 * reads);
2801                assert_eq!(counts.2, scans);
2802            }
2803            previous = Some(counts);
2804
2805            let config = gate_disabled_config(dir.path());
2806            scan_counts();
2807            run_once(&queue, &questions, Some(&config), Timestamp::now());
2808            let lap = scan_counts();
2809            assert!(lap.0 <= 12, "triage queue scans: {lap:?}");
2810            assert!(lap.1 <= 14 * size, "triage task reads: {lap:?}");
2811            assert!(lap.2 <= 6, "triage question scans: {lap:?}");
2812        }
2813    }
2814
2815    #[test]
2816    fn run_once_filing_many_new_questions_reads_the_queue_a_constant_number_of_times() {
2817        let (dir, queue, questions) = store();
2818        let size = 200;
2819        for i in 0..size {
2820            let mut t = task("scan fixture", dir.path().join("repo"));
2821            t.id = format!("task-{i:04}");
2822            t.hold_machine(Some("gate red".to_owned()));
2823            queue.put(&mut t).unwrap();
2824        }
2825        scan_counts();
2826        let report = run_once(&queue, &questions, None, Timestamp::now());
2827        let (lists, _, _) = scan_counts();
2828        assert_eq!(report.asked.len(), size, "every held task is asked about");
2829        assert!(
2830            lists <= 12,
2831            "queue scans while filing {size} questions: {lists}"
2832        );
2833    }
2834
2835    #[test]
2836    fn base_recovery_stops_suppress_generic_and_dependency_resume_offers() {
2837        let (dir, queue, questions) = store();
2838        let mut root = task("base stop", dir.path().to_path_buf());
2839        let mut run = crate::run::RunState::new(
2840            dir.path().to_path_buf(),
2841            "main".into(),
2842            "base".into(),
2843            "retained implementation".into(),
2844            Config::default(),
2845        );
2846        run.status = crate::run::RunStatus::Voting;
2847        run.base_sync = Some(crate::run::BaseSync {
2848            tip: "tip".into(),
2849            behind: 3,
2850            attempts: 4,
2851            conflict: Some("persisted exhaustion".into()),
2852            already_in: None,
2853        });
2854        run.save_under(dir.path()).unwrap();
2855        root.link_run(&run.id);
2856        root.hold_machine(Some("base stop".into()));
2857        queue.put(&mut root).unwrap();
2858        let mut dependent = task("dependent", dir.path().to_path_buf());
2859        dependent.blocked_by = vec![root.id.clone()];
2860        dependent.status = TaskStatus::Blocked;
2861        queue.put(&mut dependent).unwrap();
2862        for _ in 0..2 {
2863            let report = run_once(&queue, &questions, None, Timestamp::now());
2864            assert!(report.asked.is_empty());
2865            assert!(report.resumed.is_empty());
2866        }
2867        // A generic question offered by an older launcher cannot release this
2868        // task into a replacement competition after the fix is installed.
2869        let q = file_question(
2870            &questions,
2871            &crate::task_chat::InquiryOwnership::default(),
2872            &root,
2873            Bucket::MachineUnknown,
2874            &EN,
2875            Timestamp::now(),
2876        )
2877        .unwrap();
2878        let mut q = q;
2879        q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
2880        questions.put_executable(&mut q).unwrap();
2881        apply_answers(&queue, &questions);
2882        let saved = queue.get(&root.id).unwrap();
2883        assert_eq!(saved.status, TaskStatus::Held);
2884        assert!(saved.triage_applied(&q.id));
2885        assert_eq!(saved.runs, vec![run.id]);
2886    }
2887
2888    #[test]
2889    fn resource_holds_only_auto_release_a_proven_cache_wait_timeout() {
2890        use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2891        let dir = tempfile::tempdir().unwrap();
2892        let cfg = Config::default(); // No configured cache means no busy lease.
2893        assert!(cfg.cache_dir().is_none());
2894        let mut state = RunState::new(
2895            dir.path().into(),
2896            "main".into(),
2897            "base".into(),
2898            "verify".into(),
2899            cfg.clone(),
2900        );
2901        let mut task = task("verify", dir.path().into());
2902        task.runs = vec![state.id.clone()];
2903        task.hold_machine(Some("[resource] cache operation stopped".into()));
2904        for cause in [
2905            ResourceBlockCause::Other,
2906            ResourceBlockCause::Unrecorded,
2907            ResourceBlockCause::Cancelled { park: None },
2908        ] {
2909            state.resource_block = Some(ResourceBlock {
2910                node: "gate".into(),
2911                kind: "shared build cache".into(),
2912                detail: "persistent metadata or manifest error".into(),
2913                cause,
2914                at: Timestamp::now(),
2915            });
2916            state.save_under(dir.path()).unwrap();
2917            // Repeated triage must retain the hold even though the lease is free.
2918            for _ in 0..3 {
2919                assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2920            }
2921        }
2922        let block = state.resource_block.as_mut().unwrap();
2923        block.cause = ResourceBlockCause::Timeout {
2924            waited_secs: 10,
2925            limit_secs: 10,
2926        };
2927        state.save_under(dir.path()).unwrap();
2928        assert_eq!(
2929            machine_cause_resolved_under(&task, &cfg, dir.path()),
2930            Some(true)
2931        );
2932        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
2933        state.save_under(dir.path()).unwrap();
2934        assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2935        task.runs = vec!["unreadable-run".into()];
2936        assert_eq!(machine_cause_resolved_under(&task, &cfg, dir.path()), None);
2937    }
2938
2939    #[cfg(unix)]
2940    #[test]
2941    fn disk_admission_holds_recheck_live_reservations_and_the_floor() {
2942        use crate::retention::OutputLease;
2943        use crate::run::{ResourceBlock, ResourceBlockCause, RunState};
2944        let temp = tempfile::tempdir().unwrap();
2945        let home = temp.path().canonicalize().unwrap();
2946        let mut cfg = Config::default();
2947        cfg.graph.worktree_root = Some(home.join("worktrees"));
2948        cfg.disk.min_free_bytes = 100;
2949        let cache = home.join("cache");
2950        cfg.verify.gate = vec![format!(
2951            "CARGO_TARGET_DIR='{}' cargo build",
2952            cache.display()
2953        )];
2954        let mut state = RunState::new(
2955            home.clone(),
2956            "main".into(),
2957            "base".into(),
2958            "verify".into(),
2959            cfg.clone(),
2960        );
2961        let saved_cache = home.join("saved-cache");
2962        state.config.verify.gate = vec![format!(
2963            "CARGO_TARGET_DIR='{}' cargo build",
2964            saved_cache.display()
2965        )];
2966        state.resource_block = Some(ResourceBlock {
2967            node: "gate".into(),
2968            kind: "disk admission".into(),
2969            detail: "writer headroom unavailable".into(),
2970            cause: ResourceBlockCause::Other,
2971            at: Timestamp::now(),
2972        });
2973        state.save_under(&home).unwrap();
2974        let mut task = task("verify", home.clone());
2975        task.runs = vec![state.id.clone()];
2976        task.hold_machine(Some(format!(
2977            "{}{}; no attempt was spent; resume to retry the affected operation",
2978            crate::cache::RESOURCE_HOLD,
2979            state.resource_block.as_ref().unwrap().description()
2980        )));
2981        task.schema = 21; // exact resource-block evidence migrates an older hold
2982        let gib = 1024 * 1024 * 1024;
2983        let free = std::cell::Cell::new(100 + gib - 1);
2984        let check = || {
2985            machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
2986                assert!(
2987                    paths.contains(&cache),
2988                    "the cache volume must also be checked"
2989                );
2990                assert!(
2991                    paths.contains(&saved_cache),
2992                    "saved and current cache locations both matter"
2993                );
2994                assert!(paths.contains(&state.worktree_root()));
2995                OutputLease::admit_with(&home, paths, floor, |_| Ok(free.get())).is_ok()
2996            })
2997        };
2998        assert_eq!(check(), Some(false), "the unchanged floor still applies");
2999        assert_eq!(
3000            machine_cause_resolved_with_admission(&task, &cfg, &home, |paths, floor| {
3001                OutputLease::admit_with(&home, paths, floor, |_| {
3002                    Err(anyhow::anyhow!("measurement unavailable"))
3003                })
3004                .is_ok()
3005            }),
3006            Some(false),
3007            "failed output-volume measurements must remain closed"
3008        );
3009        free.set(100 + gib);
3010        let writer = OutputLease::admit_with(
3011            &home,
3012            std::slice::from_ref(&home),
3013            cfg.disk.min_free_bytes,
3014            |_| Ok(free.get()),
3015        )
3016        .unwrap();
3017        assert_eq!(
3018            check(),
3019            Some(false),
3020            "df alone cannot resolve a live reservation"
3021        );
3022        drop(writer);
3023        assert_eq!(
3024            check(),
3025            Some(true),
3026            "releasing headroom resolves the machine hold"
3027        );
3028        assert_eq!(
3029            check(),
3030            Some(true),
3031            "the probe must release its temporary reservation"
3032        );
3033
3034        // A broken admission namespace still fails closed after free space recovers.
3035        let namespace = home.join("disk-admission");
3036        let saved = home.join("saved-admission");
3037        std::fs::rename(&namespace, &saved).unwrap();
3038        std::os::unix::fs::symlink(&saved, &namespace).unwrap();
3039        assert_eq!(check(), Some(false));
3040        std::fs::remove_file(&namespace).unwrap();
3041        std::fs::rename(saved, namespace).unwrap();
3042        assert_eq!(check(), Some(true));
3043
3044        state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Cancelled { park: None };
3045        state.save_under(&home).unwrap();
3046        assert_eq!(
3047            machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3048                "a cancelled operation must remain held"
3049            )),
3050            None
3051        );
3052        state.resource_block.as_mut().unwrap().kind = "incremental cache admission".into();
3053        state.resource_block.as_mut().unwrap().cause = ResourceBlockCause::Other;
3054        state.save_under(&home).unwrap();
3055        assert_eq!(
3056            machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3057                "unproven incremental caches must remain held"
3058            )),
3059            None
3060        );
3061        task.runs.push("unreadable-run".into());
3062        assert_eq!(
3063            machine_cause_resolved_with_admission(&task, &cfg, &home, |_, _| panic!(
3064                "missing evidence must not release a hold"
3065            )),
3066            None
3067        );
3068    }
3069
3070    /// `[disk] min_free_bytes = 0` written next to a fictional repo, so
3071    /// `machine_cause_resolved` never has to ask the real disk anything - the
3072    /// same fixture pattern `daemon`'s own idle-loop tests use.
3073    fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
3074        let config = dir.join("magi.toml");
3075        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
3076        config
3077    }
3078
3079    #[test]
3080    fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
3081        for source in ["cli", "web"] {
3082            for answer_after_release in [true, false] {
3083                let (dir, queue, questions) = store();
3084                let mut t = task("recovery", dir.path().join("repo"));
3085                t.hold_machine(Some("inspect remote first".into()));
3086                queue.put(&mut t).unwrap();
3087                let mut q = file_question(
3088                    &questions,
3089                    &crate::task_chat::InquiryOwnership::default(),
3090                    &t,
3091                    Bucket::MachineUnknown,
3092                    &JA,
3093                    Timestamp::now(),
3094                )
3095                .unwrap();
3096                if !answer_after_release {
3097                    q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3098                    questions.put(&mut q).unwrap();
3099                }
3100                t.release_operator(source, None);
3101                queue.put(&mut t).unwrap();
3102                if answer_after_release {
3103                    q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
3104                    questions.put(&mut q).unwrap();
3105                }
3106                apply_answers(&queue, &questions);
3107                let after = queue.get(&t.id).unwrap();
3108                assert!(after.triage_applied(&q.id));
3109                assert_eq!(after.operator_held(), answer_after_release);
3110                assert_eq!(
3111                    after.status,
3112                    if answer_after_release {
3113                        TaskStatus::Held
3114                    } else {
3115                        TaskStatus::Queued
3116                    }
3117                );
3118                assert!(apply_answers(&queue, &questions).is_empty());
3119            }
3120        }
3121    }
3122
3123    #[test]
3124    fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
3125        let (dir, queue, questions) = store();
3126        let mut t = task("recover", dir.path().join("repo"));
3127        t.hold_machine(Some("inspect first".into()));
3128        queue.put(&mut t).unwrap();
3129        let mut q = file_question(
3130            &questions,
3131            &crate::task_chat::InquiryOwnership::default(),
3132            &t,
3133            Bucket::MachineUnknown,
3134            &JA,
3135            Timestamp::now(),
3136        )
3137        .unwrap();
3138        assert!(q.actions.is_empty());
3139        q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3140        questions.put(&mut q).unwrap();
3141        // Older release paths queued the task without recording approval.
3142        t.release();
3143        t.instruction = "Reuse approved PR head".into();
3144        queue.put(&mut t).unwrap();
3145        assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
3146        let mut after = queue.get(&t.id).unwrap();
3147        assert_eq!(
3148            after.resumption.as_ref().unwrap().question_id.as_deref(),
3149            Some(q.id.as_str())
3150        );
3151        assert_eq!(
3152            after.resumption.as_ref().unwrap().instruction,
3153            t.instruction
3154        );
3155        assert_eq!(after.answers[0].answer, JA.resume);
3156        assert!(after.triage_applied(&q.id));
3157        assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
3158        after.hold_machine(Some("new blocker".into()));
3159        queue.put(&mut after).unwrap();
3160        let mut late = file_question(
3161            &questions,
3162            &crate::task_chat::InquiryOwnership::default(),
3163            &after,
3164            Bucket::MachineUnknown,
3165            &EN,
3166            Timestamp::now(),
3167        )
3168        .unwrap();
3169        after.hold_manual(Some("keep held now".into()));
3170        queue.put(&mut after).unwrap();
3171        late.answer(Answer::Choice(late.choices[0].clone()))
3172            .unwrap();
3173        questions.put(&mut late).unwrap();
3174        apply_answers(&queue, &questions);
3175        let held = queue.get(&t.id).unwrap();
3176        assert!(held.operator_held());
3177        assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
3178        assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
3179    }
3180
3181    #[test]
3182    fn a_resolved_machine_hold_is_requeued_automatically() {
3183        let (dir, q, questions) = store();
3184        let config = gate_disabled_config(dir.path());
3185        let mut t = task("disk pressure", dir.path().join("repo"));
3186        t.hold_machine(Some(
3187            "not enough free space to start a run: 10 bytes free, 100 required by \
3188             `[disk] min_free_bytes`"
3189                .to_owned(),
3190        ));
3191        t.schema = 21; // persisted admission hold from before typed causes
3192        q.put(&mut t).unwrap();
3193
3194        let report = run_once(&q, &questions, Some(&config), Timestamp::now());
3195        assert_eq!(report.resumed, [t.id.clone()]);
3196        assert!(report.asked.is_empty());
3197
3198        let back = q.get(&t.id).unwrap();
3199        assert_eq!(back.status, TaskStatus::Queued);
3200        assert!(back.hold_source.is_none());
3201        assert!(questions.list().is_empty(), "nothing needed asking");
3202    }
3203
3204    #[test]
3205    fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
3206        let (dir, q, questions) = store();
3207        let mut t = task("gate went red", dir.path().join("repo"));
3208        t.hold_machine(Some("gate red".to_owned()));
3209        q.put(&mut t).unwrap();
3210
3211        let first = run_once(&q, &questions, None, Timestamp::now());
3212        assert_eq!(first.asked, [t.id.clone()]);
3213        assert!(first.resumed.is_empty());
3214
3215        let open: Vec<_> = questions
3216            .list()
3217            .into_iter()
3218            .filter(|q| q.status.open())
3219            .collect();
3220        assert_eq!(open.len(), 1);
3221        assert_eq!(open[0].run, t.id);
3222        assert_eq!(open[0].node, NODE);
3223        assert_eq!(open[0].choices.len(), 3);
3224
3225        // A second pass with nothing new must not file a second question.
3226        let second = run_once(&q, &questions, None, Timestamp::now());
3227        assert!(second.asked.is_empty());
3228        assert_eq!(
3229            questions
3230                .list()
3231                .into_iter()
3232                .filter(|q| q.status.open())
3233                .count(),
3234            1
3235        );
3236    }
3237
3238    #[test]
3239    fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
3240        let (dir, q, questions) = store();
3241        let mut t = task("schema 1 record", dir.path().join("repo"));
3242        t.status = TaskStatus::Held;
3243        assert!(t.hold_source.is_none(), "the case this test is about");
3244        q.put(&mut t).unwrap();
3245
3246        let first = run_once(&q, &questions, None, Timestamp::now());
3247        assert_eq!(first.asked, [t.id.clone()]);
3248
3249        let second = run_once(&q, &questions, None, Timestamp::now());
3250        assert!(
3251            second.asked.is_empty(),
3252            "the same legacy hold must not be asked about twice"
3253        );
3254        assert_eq!(
3255            questions
3256                .list()
3257                .into_iter()
3258                .filter(|q| q.status.open())
3259                .count(),
3260            1
3261        );
3262    }
3263
3264    #[test]
3265    fn dependency_resolution_detaches_legacy_short_refs_without_dropping_other_waits() {
3266        let (dir, queue, questions) = store();
3267        let mut root = task("root", dir.path().join("repo"));
3268        root.id = "20261013-193611-ca5b".into();
3269        root.hold_machine(Some("needs owner decision".into()));
3270        queue.put(&mut root).unwrap();
3271        let mut other = task("other", dir.path().join("repo"));
3272        other.id = "20261013-192213-feb2".into();
3273        queue.put(&mut other).unwrap();
3274        let mut waiting = task("waiting", dir.path().join("repo"));
3275        waiting.block(vec!["ca5b".into(), other.id.clone()], None);
3276        queue.put(&mut waiting).unwrap();
3277        detach_dependants(&queue, &questions, &root.id);
3278        let after = queue.get(&waiting.id).unwrap();
3279        assert_eq!(after.status, TaskStatus::Blocked);
3280        assert_eq!(after.blocked_by, [other.id]);
3281    }
3282
3283    #[test]
3284    fn a_manual_hold_is_never_auto_resumed() {
3285        let (dir, q, questions) = store();
3286        let mut t = task("operator stopped this", dir.path().join("repo"));
3287        t.hold_manual(Some("waiting on a decision".to_owned()));
3288        q.put(&mut t).unwrap();
3289
3290        let report = run_once(&q, &questions, None, Timestamp::now());
3291        assert!(report.resumed.is_empty());
3292        // Fresh, not stale yet - no question either.
3293        assert!(report.asked.is_empty());
3294
3295        let back = q.get(&t.id).unwrap();
3296        assert_eq!(back.status, TaskStatus::Held);
3297        assert_eq!(back.hold_source, Some(HoldSource::Manual));
3298        assert!(questions.list().is_empty());
3299    }
3300
3301    #[test]
3302    fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
3303        // The five real tasks this whole change exists for are `blocked`, not
3304        // `held`, and no daemon has to be running for `magi task triage` alone
3305        // to reach them - `run_once` must both quarantine and ask in the same
3306        // call.
3307        let (dir, q, questions) = store();
3308        let mut still_going = task("still valid", dir.path().join("repo"));
3309        q.put(&mut still_going).unwrap();
3310
3311        let mut t = task("orphaned", dir.path().join("repo"));
3312        t.block(
3313            vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
3314            Some("waits on both".to_owned()),
3315        );
3316        q.put(&mut t).unwrap();
3317
3318        let report = run_once(&q, &questions, None, Timestamp::now());
3319        assert_eq!(report.quarantined, [t.id.clone()]);
3320        assert_eq!(
3321            report.asked,
3322            [t.id.clone()],
3323            "the fresh machine hold must earn a question in the same pass"
3324        );
3325
3326        let after = q.get(&t.id).unwrap();
3327        assert_eq!(after.status, TaskStatus::Held);
3328        assert_eq!(after.hold_source, Some(HoldSource::Machine));
3329        assert!(after.blocked_by.is_empty());
3330
3331        // The reason is not disk-pressure wording, so this must not be read
3332        // as a disk hold and silently auto-resumed.
3333        assert!(!is_disk_hold(&after));
3334
3335        let open: Vec<_> = questions
3336            .list()
3337            .into_iter()
3338            .filter(|q| q.status.open())
3339            .collect();
3340        assert_eq!(open.len(), 1);
3341        assert_eq!(open[0].run, t.id);
3342
3343        // A second pass with nothing new files no second question.
3344        let second = run_once(&q, &questions, None, Timestamp::now());
3345        assert!(second.quarantined.is_empty());
3346        assert!(second.asked.is_empty());
3347    }
3348
3349    /// A held root with a chain of dependants: 9db7 <- 4135 <- 6081, and a
3350    /// second direct dependant that also waits on a queued task.
3351    fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
3352        let mut root = task("root", dir.join("repo"));
3353        root.hold_manual(Some("waiting".to_owned()));
3354        q.put(&mut root).unwrap();
3355        let mut mid = task("mid", dir.join("repo"));
3356        mid.block(vec![root.id.clone()], None);
3357        q.put(&mut mid).unwrap();
3358        let mut leaf = task("leaf", dir.join("repo"));
3359        leaf.block(vec![mid.id.clone()], None);
3360        q.put(&mut leaf).unwrap();
3361        (root, mid, leaf)
3362    }
3363
3364    fn deps_questions(questions: &Questions) -> Vec<Question> {
3365        questions
3366            .list()
3367            .into_iter()
3368            .filter(|q| q.node == DEPS_NODE)
3369            .collect()
3370    }
3371
3372    fn answer_deps(questions: &Questions, choice: usize) {
3373        let mut asked = deps_questions(questions).remove(0);
3374        let c = asked.choices[choice].clone();
3375        asked.answer(Answer::Choice(c)).unwrap();
3376        questions.put(&mut asked).unwrap();
3377    }
3378
3379    #[test]
3380    fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
3381        let (dir, q, questions) = store();
3382        let (root, mid, leaf) = stuck_chain(&q, dir.path());
3383
3384        let first = run_once(&q, &questions, None, Timestamp::now());
3385        assert_eq!(first.asked, std::slice::from_ref(&root.id));
3386        let asked = deps_questions(&questions);
3387        assert_eq!(asked.len(), 1, "one question per root, not per dependant");
3388        assert_eq!(asked[0].run, root.id);
3389        assert_eq!(asked[0].choices.len(), 3);
3390        assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
3391        assert!(
3392            asked[0].detail.contains(leaf.short()),
3393            "{}",
3394            asked[0].detail
3395        );
3396
3397        let second = run_once(&q, &questions, None, Timestamp::now());
3398        assert!(second.asked.is_empty());
3399        assert_eq!(deps_questions(&questions).len(), 1);
3400        assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
3401    }
3402
3403    #[test]
3404    fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
3405        let (dir, q, questions) = store();
3406        let mut root = task("root", dir.path().join("repo"));
3407        root.hold_machine(Some("gate red".to_owned()));
3408        q.put(&mut root).unwrap();
3409        let mut dep = task("dep", dir.path().join("repo"));
3410        dep.block(vec![root.id.clone()], None);
3411        q.put(&mut dep).unwrap();
3412
3413        run_once(&q, &questions, None, Timestamp::now());
3414        run_once(&q, &questions, None, Timestamp::now());
3415        assert_eq!(deps_questions(&questions).len(), 1);
3416        assert_eq!(
3417            questions.list().len(),
3418            1,
3419            "no second question about the hold"
3420        );
3421    }
3422
3423    #[test]
3424    fn a_dependency_that_can_still_run_asks_nothing() {
3425        let (dir, q, questions) = store();
3426        let mut live = task("live", dir.path().join("repo"));
3427        q.put(&mut live).unwrap();
3428        let mut dep = task("dep", dir.path().join("repo"));
3429        dep.block(vec![live.id.clone()], None);
3430        q.put(&mut dep).unwrap();
3431        let report = run_once(&q, &questions, None, Timestamp::now());
3432        assert!(report.asked.is_empty());
3433        assert!(questions.list().is_empty());
3434    }
3435
3436    #[test]
3437    fn answering_release_requeues_the_root_and_is_not_reasked() {
3438        let (dir, q, questions) = store();
3439        let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
3440        run_once(&q, &questions, None, Timestamp::now());
3441        answer_deps(&questions, 0);
3442
3443        let report = run_once(&q, &questions, None, Timestamp::now());
3444        assert_eq!(report.answered, std::slice::from_ref(&root.id));
3445        assert!(report.asked.is_empty(), "applying must not re-ask");
3446        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
3447        let again = run_once(&q, &questions, None, Timestamp::now());
3448        assert!(again.asked.is_empty() && again.answered.is_empty());
3449        assert_eq!(deps_questions(&questions).len(), 1);
3450    }
3451
3452    #[test]
3453    fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
3454        let (dir, q, questions) = store();
3455        let (root, mid, leaf) = stuck_chain(&q, dir.path());
3456        run_once(&q, &questions, None, Timestamp::now());
3457        answer_deps(&questions, 2);
3458
3459        let report = run_once(&q, &questions, None, Timestamp::now());
3460        assert!(report.asked.is_empty());
3461        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3462        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3463        let leaf = q.get(&leaf.id).unwrap();
3464        assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
3465        assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
3466    }
3467
3468    #[test]
3469    fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
3470        let (dir, q, questions) = store();
3471        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3472        let mut live = task("live", dir.path().join("repo"));
3473        q.put(&mut live).unwrap();
3474        let mut both = q.get(&mid.id).unwrap();
3475        both.block(vec![root.id.clone(), live.id.clone()], None);
3476        q.put(&mut both).unwrap();
3477        // `mid` can still progress through `live`, so nothing is stuck yet.
3478        assert!(
3479            run_once(&q, &questions, None, Timestamp::now())
3480                .asked
3481                .is_empty()
3482        );
3483    }
3484
3485    #[test]
3486    fn answering_discard_detaches_then_removes_the_root() {
3487        let (dir, q, questions) = store();
3488        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3489        run_once(&q, &questions, None, Timestamp::now());
3490        answer_deps(&questions, 1);
3491
3492        let report = run_once(&q, &questions, None, Timestamp::now());
3493        assert!(q.get(&root.id).is_err());
3494        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
3495        assert!(
3496            report.asked.is_empty(),
3497            "no per-dependant quarantine question"
3498        );
3499        assert!(report.quarantined.is_empty());
3500    }
3501
3502    #[test]
3503    fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
3504        let (dir, q, questions) = store();
3505        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
3506        run_once(&q, &questions, None, Timestamp::now());
3507        let mut asked = deps_questions(&questions).remove(0);
3508        asked.choices.clear();
3509        asked.answer(Answer::Text("dunno".to_owned())).unwrap();
3510        questions.put(&mut asked).unwrap();
3511
3512        for _ in 0..2 {
3513            let report = run_once(&q, &questions, None, Timestamp::now());
3514            assert!(report.asked.is_empty() && report.answered.is_empty());
3515        }
3516        assert_eq!(deps_questions(&questions).len(), 1);
3517        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
3518        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
3519    }
3520
3521    #[test]
3522    fn a_dependency_cycle_terminates_and_is_asked_about_once() {
3523        let (dir, q, questions) = store();
3524        let mut a = task("a", dir.path().join("repo"));
3525        let mut b = task("b", dir.path().join("repo"));
3526        a.block(vec![b.id.clone()], None);
3527        b.block(vec![a.id.clone()], None);
3528        q.put(&mut a).unwrap();
3529        q.put(&mut b).unwrap();
3530
3531        let first = run_once(&q, &questions, None, Timestamp::now());
3532        assert_eq!(first.asked.len(), 1);
3533        let second = run_once(&q, &questions, None, Timestamp::now());
3534        assert!(second.asked.is_empty());
3535        assert_eq!(deps_questions(&questions).len(), 1);
3536    }
3537
3538    #[test]
3539    fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
3540        let (dir, q, questions) = store();
3541        let mut t = task("orphan", dir.path().join("repo"));
3542        t.block(vec!["20260101-000000-gone".to_owned()], None);
3543        q.put(&mut t).unwrap();
3544        let report = run_once(&q, &questions, None, Timestamp::now());
3545        assert_eq!(report.quarantined, [t.id.clone()]);
3546        assert!(deps_questions(&questions).is_empty());
3547    }
3548
3549    #[test]
3550    fn a_stale_manual_hold_can_be_discarded() {
3551        let (dir, q, questions) = store();
3552        let mut t = task("been sitting a while", dir.path().join("repo"));
3553        t.hold_manual(Some("waiting on a decision".to_owned()));
3554        q.put(&mut t).unwrap();
3555        // Back-date the hold past MANUAL_STALE_AFTER without waiting a week.
3556        let mut back = q.get(&t.id).unwrap();
3557        back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
3558        std::fs::write(
3559            q.path_of(&back.id),
3560            serde_json::to_string_pretty(&back).unwrap(),
3561        )
3562        .unwrap();
3563
3564        let report = run_once(&q, &questions, None, Timestamp::now());
3565        assert_eq!(report.asked, [t.id.clone()]);
3566        let open: Vec<_> = questions
3567            .list()
3568            .into_iter()
3569            .filter(|q| q.status.open())
3570            .collect();
3571        assert_eq!(open.len(), 1);
3572        let mut asked = open[0].clone();
3573        assert_eq!(asked.choices, ["resume it", "keep it held", "discard it"]);
3574        assert_eq!(
3575            JA.choices_manual(),
3576            ["再開する", "まだ止めておく", "捨ててよい"]
3577        );
3578        asked
3579            .answer(Answer::Choice(asked.choices[2].clone()))
3580            .unwrap();
3581        questions.put(&mut asked).unwrap();
3582        run_once(&q, &questions, None, Timestamp::now());
3583        assert!(q.get(&t.id).is_err());
3584    }
3585
3586    #[test]
3587    fn answering_resume_releases_the_task() {
3588        let (dir, q, questions) = store();
3589        let mut t = task("gate went red", dir.path().join("repo"));
3590        t.hold_machine(Some("gate red".to_owned()));
3591        q.put(&mut t).unwrap();
3592        run_once(&q, &questions, None, Timestamp::now());
3593
3594        let mut asked = questions
3595            .list()
3596            .into_iter()
3597            .find(|q| q.run == t.id)
3598            .unwrap();
3599        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3600        questions.put(&mut asked).unwrap();
3601
3602        let report = run_once(&q, &questions, None, Timestamp::now());
3603        assert_eq!(report.answered, [t.id.clone()]);
3604        let back = q.get(&t.id).unwrap();
3605        assert_eq!(back.status, TaskStatus::Queued);
3606        assert!(back.hold_source.is_none());
3607    }
3608
3609    /// A task released by a "resume" answer, run, and failed back to `held`.
3610    fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
3611        let mut t = task("gate went red", dir.join("repo"));
3612        t.hold_machine(Some("gate red".to_owned()));
3613        q.put(&mut t).unwrap();
3614        run_once(q, questions, None, Timestamp::now());
3615        let mut asked = questions
3616            .list()
3617            .into_iter()
3618            .find(|q| q.run == t.id)
3619            .unwrap();
3620        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3621        questions.put(&mut asked).unwrap();
3622
3623        let report = run_once(q, questions, None, Timestamp::now());
3624        assert_eq!(report.answered, [t.id.clone()]);
3625        let mut back = q.get(&t.id).unwrap();
3626        assert_eq!(back.status, TaskStatus::Queued);
3627        assert_eq!(back.attempts, 0);
3628
3629        back.start("run-1".to_owned());
3630        back.fail("rebase conflict", 1);
3631        assert_eq!(back.status, TaskStatus::Held);
3632        q.put(&mut back).unwrap();
3633        back
3634    }
3635
3636    #[test]
3637    fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
3638        let (dir, q, questions) = store();
3639        let t = resumed_then_failed(&q, &questions, dir.path());
3640
3641        let report = run_once(&q, &questions, None, Timestamp::now());
3642        assert!(report.answered.is_empty(), "the old answer must not replay");
3643        assert_eq!(report.asked, std::slice::from_ref(&t.id));
3644        let back = q.get(&t.id).unwrap();
3645        assert_eq!(back.status, TaskStatus::Held);
3646        assert_eq!(
3647            questions
3648                .list()
3649                .into_iter()
3650                .filter(|q| q.status.open())
3651                .count(),
3652            1
3653        );
3654    }
3655
3656    #[test]
3657    fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
3658        let (dir, q, questions) = store();
3659        let mut t = resumed_then_failed(&q, &questions, dir.path());
3660        t.hold_manual(Some("operator stopped this".to_owned()));
3661        q.put(&mut t).unwrap();
3662        let before = questions.list().len();
3663
3664        let report = run_once(&q, &questions, None, Timestamp::now());
3665        assert!(report.answered.is_empty());
3666        assert!(report.asked.is_empty());
3667        let back = q.get(&t.id).unwrap();
3668        assert_eq!(back.status, TaskStatus::Held);
3669        assert_eq!(back.hold_source, Some(HoldSource::Manual));
3670        assert_eq!(questions.list().len(), before);
3671    }
3672
3673    #[test]
3674    fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
3675        let (dir, q, questions) = store();
3676        let mut t = task("gate went red", dir.path().join("repo"));
3677        t.hold_machine(Some("gate red".to_owned()));
3678        q.put(&mut t).unwrap();
3679        run_once(&q, &questions, None, Timestamp::now());
3680
3681        let mut asked = questions
3682            .list()
3683            .into_iter()
3684            .find(|q| q.run == t.id)
3685            .unwrap();
3686        asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3687        questions.put(&mut asked).unwrap();
3688
3689        let report = run_once(&q, &questions, None, Timestamp::now());
3690        assert_eq!(report.answered, [t.id.clone()]);
3691        let back = q.get(&t.id).unwrap();
3692        assert_eq!(back.status, TaskStatus::Held);
3693        assert_eq!(back.hold_source, Some(HoldSource::Manual));
3694        assert!(
3695            back.hold_reason
3696                .as_deref()
3697                .is_some_and(|r| r.contains("gate red")),
3698            "the original cause must survive a \"not yet\" answer, not just the \
3699             triage marker: {:?}",
3700            back.hold_reason
3701        );
3702
3703        // A third pass, same instant: the manual hold is fresh (just
3704        // touched), so nothing more happens - in particular the already
3705        // answered question is not re-applied.
3706        let third = run_once(&q, &questions, None, Timestamp::now());
3707        assert!(third.answered.is_empty());
3708        assert!(third.asked.is_empty());
3709    }
3710
3711    #[test]
3712    fn answering_discard_removes_the_task_entirely() {
3713        let (dir, q, questions) = store();
3714        let mut t = task("gate went red", dir.path().join("repo"));
3715        t.hold_machine(Some("gate red".to_owned()));
3716        q.put(&mut t).unwrap();
3717        run_once(&q, &questions, None, Timestamp::now());
3718
3719        let mut asked = questions
3720            .list()
3721            .into_iter()
3722            .find(|q| q.run == t.id)
3723            .unwrap();
3724        asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
3725        questions.put(&mut asked).unwrap();
3726
3727        let report = run_once(&q, &questions, None, Timestamp::now());
3728        assert_eq!(report.answered, [t.id.clone()]);
3729        assert!(
3730            q.get(&t.id).is_err(),
3731            "\"discard it\" (捨ててよい) must actually discard the task, not \
3732             just leave it sitting held forever"
3733        );
3734    }
3735
3736    #[test]
3737    fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
3738        // Filed while the repo's config reads Japanese...
3739        let (dir, q, questions) = store();
3740        let ja_config = dir.path().join("ja.toml");
3741        std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
3742        let mut t = task("gate went red", dir.path().join("repo"));
3743        t.hold_machine(Some("gate red".to_owned()));
3744        q.put(&mut t).unwrap();
3745        run_once(&q, &questions, Some(&ja_config), Timestamp::now());
3746
3747        let mut asked = questions
3748            .list()
3749            .into_iter()
3750            .find(|q| q.run == t.id)
3751            .unwrap();
3752        assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
3753        asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
3754        questions.put(&mut asked).unwrap();
3755
3756        // ...but applied against an English config (a later `--config`, or an
3757        // edited repository config). The Japanese "再開してよい" answer must
3758        // still be read as a resume, not silently misread as "keep held"
3759        // because it fails a text comparison against the English wording.
3760        let en_config = dir.path().join("en.toml");
3761        std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
3762        let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
3763        assert_eq!(report.answered, [t.id.clone()]);
3764        let back = q.get(&t.id).unwrap();
3765        assert_eq!(
3766            back.status,
3767            TaskStatus::Queued,
3768            "a resume answer must resume the task regardless of which \
3769             language it is read back in"
3770        );
3771    }
3772
3773    #[test]
3774    fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
3775        // A record written before `Task::fail` started copying `why` into
3776        // `hold_reason` too (or one written by a still older build) carries
3777        // only `last_error`. The question detail must still name a cause
3778        // rather than reading "(none recorded)".
3779        let (dir, q, questions) = store();
3780        let mut t = task("kept failing the gate", dir.path().join("repo"));
3781        t.start("run-1".to_owned());
3782        t.fail("gate red three times running", 1);
3783        assert_eq!(t.status, TaskStatus::Held);
3784        t.hold_reason = None; // simulate a pre-fix or pre-schema record
3785        q.put(&mut t).unwrap();
3786
3787        run_once(&q, &questions, None, Timestamp::now());
3788        let asked = questions
3789            .list()
3790            .into_iter()
3791            .find(|q| q.run == t.id)
3792            .unwrap();
3793        assert!(
3794            asked.detail.contains("gate red three times running"),
3795            "the question must surface `last_error` when there is no \
3796             `hold_reason` to show instead: {}",
3797            asked.detail
3798        );
3799    }
3800
3801    #[test]
3802    fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
3803        let (dir, q, questions) = store();
3804        let mut t = task("gate went red", dir.path().join("repo"));
3805        t.hold_machine(Some("gate red".to_owned()));
3806        q.put(&mut t).unwrap();
3807
3808        assert!(open_question_for(&questions, &t.id).is_none());
3809        assert!(!open_task_ids(&questions).contains(&t.id));
3810
3811        run_once(&q, &questions, None, Timestamp::now());
3812        assert!(open_question_for(&questions, &t.id).is_some());
3813        assert!(open_task_ids(&questions).contains(&t.id));
3814
3815        let mut asked = questions
3816            .list()
3817            .into_iter()
3818            .find(|q| q.run == t.id)
3819            .unwrap();
3820        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
3821        questions.put(&mut asked).unwrap();
3822
3823        assert!(
3824            open_question_for(&questions, &t.id).is_none(),
3825            "an answered question is no longer open"
3826        );
3827        assert!(!open_task_ids(&questions).contains(&t.id));
3828    }
3829
3830    #[test]
3831    fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
3832        // `open_question_for` alone goes `None` the instant the operator
3833        // answers, well before `run_once` - idle-tick only - gets a turn to
3834        // actually apply that answer (see `already_applied`). `pending_for`
3835        // exists so a caller polling far more often than `run_once` does -
3836        // `crate::conduct::apply_one` - does not walk through that gap.
3837        let (dir, q, questions) = store();
3838        let mut t = task("gate went red", dir.path().join("repo"));
3839        t.hold_machine(Some("gate red".to_owned()));
3840        q.put(&mut t).unwrap();
3841
3842        assert!(!pending_for(&questions, &t));
3843
3844        run_once(&q, &questions, None, Timestamp::now());
3845        let held = q.get(&t.id).unwrap();
3846        assert!(pending_for(&questions, &held), "still waiting on an answer");
3847
3848        let mut asked = questions
3849            .list()
3850            .into_iter()
3851            .find(|q| q.run == t.id)
3852            .unwrap();
3853        asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
3854        questions.put(&mut asked).unwrap();
3855        assert!(!asked.status.open());
3856
3857        // The race window: answered, but `run_once` has not run again yet.
3858        let still_held = q.get(&t.id).unwrap();
3859        assert!(
3860            pending_for(&questions, &still_held),
3861            "answered but not yet applied is still pending"
3862        );
3863
3864        run_once(&q, &questions, None, Timestamp::now());
3865        let after = q.get(&t.id).unwrap();
3866        assert!(
3867            !pending_for(&questions, &after),
3868            "the answer is applied now, nothing left pending"
3869        );
3870    }
3871
3872    #[test]
3873    fn migrated_keep_held_is_consumed_but_can_be_reviewed_and_discarded_again() {
3874        let (dir, queue, questions) = store();
3875        let mut t = task("keep held", dir.path().join("repo"));
3876        t.hold_machine(Some("unresolved cause".into()));
3877        queue.put(&mut t).unwrap();
3878        run_once(&queue, &questions, None, Timestamp::now());
3879        let mut old = questions.list().remove(0);
3880        old.answer(Answer::Choice(old.choices[1].clone())).unwrap();
3881        questions.put(&mut old).unwrap();
3882        run_once(&queue, &questions, None, Timestamp::now());
3883        let held = queue.get(&t.id).unwrap();
3884        assert!(held.triage_applied(&old.id));
3885
3886        let migration = dir.path().join("notifications/task-chat-migration-v1");
3887        std::fs::create_dir_all(&migration).unwrap();
3888        std::fs::write(
3889            migration.join("state.json"),
3890            serde_json::to_vec(&serde_json::json!({
3891                "schema": 1, "classification_revision": 1, "pending": [], "sources": [old.id]
3892            }))
3893            .unwrap(),
3894        )
3895        .unwrap();
3896        assert!(questions.list_for_effects()[0].status.open());
3897        assert!(!pending_for(&questions, &held));
3898        assert!(open_question_for(&questions, &t.id).is_none());
3899        assert!(!open_task_ids(&questions).contains(&t.id));
3900        assert!(old.answer(Answer::Choice(old.choices[2].clone())).is_err());
3901        assert!(
3902            run_once(&queue, &questions, None, Timestamp::now())
3903                .answered
3904                .is_empty()
3905        );
3906
3907        let later = held.updated_at + SignedDuration::from_hours(24 * 8);
3908        assert_eq!(
3909            run_once(&queue, &questions, None, later).asked,
3910            [t.id.clone()]
3911        );
3912        let mut fresh = open_question_for(&questions, &t.id).unwrap();
3913        assert_ne!(fresh.id, old.id);
3914        assert_eq!(fresh.choices[2], EN.discard);
3915        fresh
3916            .answer(Answer::Choice(fresh.choices[2].clone()))
3917            .unwrap();
3918        questions.put(&mut fresh).unwrap();
3919        assert_eq!(
3920            run_once(&queue, &questions, None, later).answered,
3921            [t.id.clone()]
3922        );
3923        assert!(queue.get(&t.id).is_err());
3924        assert_eq!(
3925            questions.read_history(&old.id).unwrap().resolution(),
3926            Some(EN.wait.into())
3927        );
3928    }
3929
3930    #[test]
3931    fn migrated_unapplied_answers_remain_fenced_but_are_not_displayed_open() {
3932        for node in [NODE, DEPS_NODE] {
3933            let (dir, queue, questions) = store();
3934            let mut t = task("unapplied", dir.path().join("repo"));
3935            t.hold_manual(Some("waiting".into()));
3936            queue.put(&mut t).unwrap();
3937            let mut q = Question::new(
3938                t.id.clone(),
3939                node.into(),
3940                SEAT.into(),
3941                "unapplied".into(),
3942                String::new(),
3943                EN.choices3(),
3944            );
3945            q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
3946            questions.put(&mut q).unwrap();
3947            let migration = dir.path().join("notifications/task-chat-migration-v1");
3948            std::fs::create_dir_all(&migration).unwrap();
3949            std::fs::write(
3950                migration.join("state.json"),
3951                serde_json::to_vec(&serde_json::json!({
3952                    "schema": 1, "classification_revision": 1, "pending": [], "sources": [q.id]
3953                }))
3954                .unwrap(),
3955            )
3956            .unwrap();
3957            assert!(pending_for(&questions, &t));
3958            assert!(open_question_for(&questions, &t.id).is_none());
3959            assert!(!open_task_ids(&questions).contains(&t.id));
3960            assert!(apply_answers(&queue, &questions).is_empty());
3961            assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
3962            t.mark_triage_applied(&q.id);
3963            queue.put(&mut t).unwrap();
3964            assert!(!pending_for(&questions, &t));
3965            assert!(!deps_pending_in(&RecoveryIndex::load(&questions), &t));
3966        }
3967    }
3968}