Skip to main content

magi/
blockers.rs

1//! Dependency inventory for `blocked` tasks.
2//!
3//! [`crate::daemon::resolve_blockers`] frees a task when its dependency is
4//! `done` (or its question answered) and quarantines it when the dependency no
5//! longer exists. It has nothing to say about a dependency that is alive but
6//! *stuck*: a `held` task never becomes `done` on its own, so everything
7//! waiting on it waits forever, and nothing shows why. [`Inventory`] answers
8//! that from one snapshot of the queue and the questions:
9//!
10//! - [`Inventory::waits_on`] - what a blocked task waits on and each
11//!   dependency's state, following a chain of blocked dependencies
12//!   (`4135 (blocked → 9db7 held)`), for `magi task list` and the web UI.
13//! - [`Inventory::stuck_roots`] - the tasks nothing in the loop will ever run
14//!   that a blocked task is frozen behind. [`crate::triage`] asks about each
15//!   such root once, naming everything it freezes.
16//!
17//! A blocked task is *stuck* when it has at least one unresolved dependency
18//! and every one of them is either `held` or itself a stuck blocked task.
19//! Anything that can still make progress - a queued, running or failed
20//! (retried) task, an open question, a dependency that no longer exists (which
21//! `resolve_blockers` quarantines) - makes it not stuck. A dependency cycle
22//! terminates: its members are stuck, and the smallest id in the cycle is its
23//! root.
24
25use std::collections::{BTreeMap, BTreeSet};
26
27use crate::ask::{Question, QuestionStatus};
28use crate::queue::{Task, TaskStatus};
29
30/// How many hops [`Inventory::waits_on`] follows before it stops describing.
31const CHAIN_DEPTH: usize = 4;
32
33/// One snapshot of the tasks and questions a `blocked_by` id can name.
34#[derive(Debug, Clone, Default)]
35pub struct Inventory {
36    tasks: BTreeMap<String, Task>,
37    questions: BTreeMap<String, DecisionRecord>,
38    ids: Vec<String>,
39    complete: bool,
40}
41
42// Keep only routing metadata, rather than duplicating decision transcripts,
43// panels and answer payloads in a dependency inventory.
44#[derive(Debug, Clone)]
45struct DecisionRecord {
46    id: String,
47    status: QuestionStatus,
48    summary: String,
49    routed_task: Option<String>,
50    routed_chat: Option<String>,
51}
52
53impl From<&Question> for DecisionRecord {
54    fn from(q: &Question) -> Self {
55        Self {
56            id: q.id.clone(),
57            status: q.status,
58            summary: q.summary.clone(),
59            routed_task: q.routed_task.clone(),
60            routed_chat: q.routed_chat.clone(),
61        }
62    }
63}
64
65enum Dep<'a> {
66    Task(&'a Task),
67    Question(QuestionStatus),
68    Missing,
69    Unknown,
70}
71
72#[derive(Debug)]
73pub(crate) struct ResolvedDecision {
74    pub(crate) id: String,
75    pub(crate) status: QuestionStatus,
76    pub(crate) summary: String,
77    pub(crate) routed_task: Option<String>,
78    pub(crate) routed_chat: Option<String>,
79    pub(crate) view: BlockerView,
80}
81
82/// Read-only resolution result used by the web Dependencies projection so it
83/// shares [`Inventory`]'s exact reference-resolution and decision-routing rules
84/// without duplicating them.
85#[derive(Debug)]
86pub(crate) enum ResolvedBlocker<'a> {
87    Task(&'a Task),
88    Decision(Box<ResolvedDecision>),
89    Missing,
90    Ambiguous,
91    Unavailable,
92}
93
94type Roots = Option<BTreeSet<String>>;
95
96/// Read-only dependency presentation. Decision records are interpreted only
97/// here, alongside the compatibility resolver; clients never infer ownership.
98#[derive(Debug, serde::Serialize)]
99pub struct BlockerView {
100    /// Canonical id when readable, otherwise the stored reference.
101    pub id: String,
102    /// Task, decision, or unavailable record.
103    pub kind: &'static str,
104    /// Recorded status and bounded dependency chain.
105    pub state: String,
106    /// Task title or decision summary, when readable.
107    pub reason: Option<String>,
108    /// Explanation of the supported next step.
109    pub next: String,
110    /// True when progress or scheduler reconciliation needs no operator action.
111    pub resolves_itself: bool,
112    /// Existing read-only page route and record id; never a control endpoint.
113    pub destination: Option<(&'static str, String)>,
114}
115
116/// The last dash-separated part of an id: what `Task::short` shows.
117fn short(id: &str) -> &str {
118    id.split('-').next_back().unwrap_or(id)
119}
120
121fn decision_view(q: &DecisionRecord) -> BlockerView {
122    let mut view = BlockerView {
123        id: q.id.clone(),
124        kind: "decision",
125        state: q.status.as_str().into(),
126        reason: Some(q.summary.clone()),
127        next: String::new(),
128        resolves_itself: q.status == QuestionStatus::Answered,
129        destination: None,
130    };
131    view.next = match q.status {
132        QuestionStatus::Answered => "Decision recorded; waiting for the scheduler to reconcile this dependency.",
133        QuestionStatus::Abandoned => "This record no longer accepts answers. If forwarded, continue in its owning task chat; otherwise inspect magi task triage for recovery. The record does not prove the dependency completed.",
134        QuestionStatus::Open if q.routed_task.is_some() && q.routed_chat.is_none() => "Waiting for delivery to the owning task chat. The scheduler must deliver the decision before it can be handled there.",
135        QuestionStatus::Open if q.routed_task.is_some() => "Open the owning task chat to review and resolve this decision through its existing controls. Availability and approval are checked there.",
136        QuestionStatus::Open => "Open the existing decision to inspect its context and available controls. A historical or unavailable waiter may no longer accept an answer.",
137    }.into();
138    view.destination = if q.routed_task.is_some() {
139        q.routed_chat.clone().map(|id| ("chat", id))
140    } else if q.status == QuestionStatus::Open {
141        Some(("questions", q.id.clone()))
142    } else {
143        None
144    };
145    view
146}
147
148impl Inventory {
149    /// All direct blockers, including settled and unavailable records. Task
150    /// links let the operator follow chains without hiding sibling blockers.
151    pub fn blocker_views(&self, task: &Task) -> Vec<BlockerView> {
152        if task.status != TaskStatus::Blocked {
153            return Vec::new();
154        }
155        task.blocked_by.iter().map(|id| {
156            let mut view = BlockerView {
157                id: id.clone(), kind: "unavailable", state: self.chain(id, &mut vec![task.id.clone()]),
158                reason: None, resolves_itself: false,
159                next: "Inspect the dependency reference with magi task triage; unavailable or ambiguous records cannot safely be treated as resolved.".into(),
160                destination: None,
161            };
162            match self.dep(id) {
163                Dep::Task(t) => {
164                    view.id = t.id.clone();
165                    view.kind = "task";
166                    view.reason = Some(t.title.clone());
167                    view.resolves_itself = matches!(t.status, TaskStatus::Queued | TaskStatus::Running | TaskStatus::Failed | TaskStatus::Parked | TaskStatus::Done);
168                    view.next = if t.status == TaskStatus::Done {
169                        "Completed; waiting for the scheduler to reconcile this dependency."
170                    } else if view.state.contains("cycle") {
171                        "Dependency cycle: inspect the linked task and use task triage or its owning chat to correct the wait. A cycle cannot complete on its own."
172                    } else if view.resolves_itself {
173                        "This dependency is still progressing or awaiting scheduler retry. No operator action is needed for this blocker; wait for it to complete."
174                    } else {
175                        "Open the dependency task to inspect its status, blockers and recovery controls. It must complete before this dependency resolves."
176                    }.into();
177                    view.destination = Some(("tasks", t.id.clone()));
178                }
179                Dep::Question(_) => {
180                    // Compatibility with existing decision outbox records;
181                    // do not create a decision or derive a chat from ancestry.
182                    let full = match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
183                        crate::queue::Reference::Found(full) => full,
184                        _ => id.clone(),
185                    };
186                    if let Some(q) = self.questions.get(&full) {
187                        view = decision_view(q);
188                    }
189                }
190                Dep::Missing => view.state = "missing".into(),
191                Dep::Unknown => {},
192            }
193            view
194        }).collect()
195    }
196
197    /// Pending held-task recovery decisions use the same compatibility
198    /// navigation as dependencies, with triage's exact pending predicate.
199    pub(crate) fn recovery_views(
200        task: &Task,
201        recovery: &crate::triage::RecoveryIndex,
202    ) -> Vec<BlockerView> {
203        recovery.pending(task).iter().map(|q| {
204            let mut view = decision_view(&DecisionRecord::from(q));
205            view.kind = "recovery decision";
206            view.next = if q.status.open() {
207                if q.routed_task.is_some() && q.routed_chat.is_none() {
208                    "Recovery decision pending delivery to the owning task chat. Disk recovery alone will not resume this task; wait for delivery and resolve the decision there."
209                } else {
210                    "Recovery decision pending. Open its existing controls to review and resolve it. Disk recovery alone will not resume this task while the decision remains pending."
211                }
212            } else {
213                "Recovery decision recorded but not yet applied. Its existing task-chat controls or triage must apply it before recovery can proceed; disk recovery alone will not resume this task."
214            }.into();
215            view.resolves_itself = q.status == QuestionStatus::Answered && q.routed_chat.is_none();
216            view
217        }).collect()
218    }
219
220    /// Build the snapshot. Callers take `queue.list()` and `questions.list()`
221    /// once, so a listing over many tasks never rescans the disk per task.
222    pub fn new(tasks: Vec<Task>, questions: &[Question]) -> Self {
223        let ids = tasks
224            .iter()
225            .map(|t| t.id.clone())
226            .chain(questions.iter().map(|q| q.id.clone()))
227            .collect();
228        Self {
229            ids,
230            complete: true,
231            tasks: tasks.into_iter().map(|t| (t.id.clone(), t)).collect(),
232            questions: questions
233                .iter()
234                .map(|q| (q.id.clone(), DecisionRecord::from(q)))
235                .collect(),
236        }
237    }
238
239    /// Include unreadable records and tombstones in id resolution; list()
240    /// alone cannot prove uniqueness or absence.
241    pub fn load(queue: &crate::queue::Queue, questions: &crate::ask::Questions) -> Self {
242        Self::load_with_tasks(queue, questions, queue.list())
243    }
244
245    /// Reuse a listing already read by the caller. Still include tombstones
246    /// and unreadable ids when resolving dependency ambiguity.
247    pub fn load_with_tasks(
248        queue: &crate::queue::Queue,
249        questions: &crate::ask::Questions,
250        tasks: Vec<Task>,
251    ) -> Self {
252        let mut inventory = Self::new(tasks, &questions.list_for_effects());
253        let ids = (|| -> anyhow::Result<Vec<String>> {
254            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
255            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
256            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
257            ids.sort();
258            ids.dedup();
259            Ok(ids)
260        })();
261        match ids {
262            Ok(ids) => inventory.ids = ids,
263            Err(_) => inventory.complete = false,
264        }
265        inventory
266    }
267
268    /// Enumeration failure is fatal to the overview; unreadable records are
269    /// counted separately without changing reference resolution or scheduling.
270    pub(crate) fn overview_unreadable(
271        &self,
272        queue: &crate::queue::Queue,
273        questions: &crate::ask::Questions,
274    ) -> anyhow::Result<usize> {
275        anyhow::ensure!(self.complete, "Dependency store enumeration failed");
276        let tasks = crate::queue::record_ids(queue.root(), "json")?
277            .into_iter()
278            .filter(|id| !self.tasks.contains_key(id))
279            .count();
280        let decisions = crate::queue::record_ids(questions.root(), "json")?
281            .into_iter()
282            .filter(|id| !self.questions.contains_key(id))
283            .count();
284        Ok(tasks + decisions)
285    }
286
287    /// Read only the dependency closure for a detail view. Names across both
288    /// stores (including tombstones and corrupt records) still establish
289    /// ambiguity, and unreadable records remain unknown rather than resolved.
290    pub fn load_for(
291        queue: &crate::queue::Queue,
292        questions: &crate::ask::Questions,
293        task: &Task,
294    ) -> Self {
295        Self::load_for_tasks(queue, questions, std::slice::from_ref(task))
296    }
297
298    /// Share id enumeration and dependency reads across one list page.
299    pub fn load_for_tasks(
300        queue: &crate::queue::Queue,
301        questions: &crate::ask::Questions,
302        tasks: &[Task],
303    ) -> Self {
304        let mut inventory = Self::new(tasks.to_vec(), &[]);
305        if tasks.iter().all(|task| task.blocked_by.is_empty()) {
306            return inventory;
307        }
308        let ids = (|| -> anyhow::Result<Vec<String>> {
309            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
310            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
311            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
312            ids.sort();
313            ids.dedup();
314            Ok(ids)
315        })();
316        match ids {
317            Ok(ids) => inventory.ids = ids,
318            Err(_) => inventory.complete = false,
319        }
320        let mut pending: Vec<_> = tasks
321            .iter()
322            .flat_map(|task| task.blocked_by.iter().cloned())
323            .collect();
324        let mut seen = BTreeSet::new();
325        let ownership = crate::task_chat::InquiryOwnership::default();
326        while let Some(reference) = pending.pop() {
327            let full =
328                if queue.path_of(&reference).is_file() || questions.path_of(&reference).is_file() {
329                    reference
330                } else if inventory.complete {
331                    match crate::queue::resolve_reference(
332                        &reference,
333                        inventory.ids.iter().map(String::as_str),
334                    ) {
335                        crate::queue::Reference::Found(full) => full,
336                        _ => continue,
337                    }
338                } else {
339                    continue;
340                };
341            if !seen.insert(full.clone()) {
342                continue;
343            }
344            if queue.path_of(&full).is_file()
345                && let Ok(t) = queue.get(&full)
346            {
347                pending.extend(t.blocked_by.iter().cloned());
348                inventory.tasks.insert(full.clone(), t);
349            }
350            if questions.path_of(&full).is_file()
351                && let Ok(q) = questions.get_for_effects_in(&full, &ownership)
352            {
353                inventory.questions.insert(full, DecisionRecord::from(&q));
354            }
355        }
356        inventory
357    }
358
359    fn dep(&self, id: &str) -> Dep<'_> {
360        // A partial scan does not invalidate readable exact records. It does
361        // prevent proving that a prefix/suffix is unique across both stores.
362        if let Some(t) = self.tasks.get(id) {
363            return Dep::Task(t);
364        }
365        if let Some(s) = self.questions.get(id) {
366            return Dep::Question(s.status);
367        }
368        if !self.complete {
369            return Dep::Unknown;
370        }
371        match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
372            crate::queue::Reference::Found(full) => {
373                if let Some(t) = self.tasks.get(&full) {
374                    Dep::Task(t)
375                } else if let Some(s) = self.questions.get(&full) {
376                    Dep::Question(s.status)
377                } else {
378                    Dep::Unknown
379                }
380            }
381            crate::queue::Reference::Missing => Dep::Missing,
382            crate::queue::Reference::Ambiguous => Dep::Unknown,
383        }
384    }
385
386    /// A dependency that has nothing left to wait for.
387    fn resolved(&self, id: &str) -> bool {
388        match self.dep(id) {
389            Dep::Task(t) => t.status == TaskStatus::Done,
390            Dep::Question(s) => s == QuestionStatus::Answered,
391            Dep::Missing | Dep::Unknown => false,
392        }
393    }
394
395    fn walk(
396        &self,
397        id: &str,
398        path: &mut Vec<String>,
399        memo: &mut BTreeMap<String, Roots>,
400    ) -> (Roots, bool) {
401        if let Some(v) = memo.get(id) {
402            return (v.clone(), false);
403        }
404        let Some(task) = self.tasks.get(id) else {
405            return (None, false);
406        };
407        path.push(id.to_owned());
408        let mut roots = BTreeSet::new();
409        let mut moving = false;
410        let mut cyclic = false;
411        for b in &task.blocked_by {
412            match self.dep(b) {
413                Dep::Task(t) => match t.status {
414                    TaskStatus::Done => {}
415                    TaskStatus::Held => {
416                        roots.insert(t.id.clone());
417                    }
418                    TaskStatus::Blocked => {
419                        if let Some(pos) = path.iter().position(|p| p == &t.id) {
420                            // A cycle: its smallest id speaks for all of it, so
421                            // every entry point names the same root.
422                            if let Some(min) = path[pos..].iter().min() {
423                                roots.insert(min.clone());
424                            }
425                            cyclic = true;
426                        } else {
427                            let (sub, c) = self.walk(&t.id, path, memo);
428                            cyclic |= c;
429                            match sub {
430                                Some(r) => roots.extend(r),
431                                None => moving = true,
432                            }
433                        }
434                    }
435                    TaskStatus::Queued
436                    | TaskStatus::Running
437                    | TaskStatus::Failed
438                    | TaskStatus::Parked => {
439                        moving = true;
440                    }
441                },
442                Dep::Question(QuestionStatus::Answered) => {}
443                Dep::Question(_) | Dep::Missing | Dep::Unknown => moving = true,
444            }
445        }
446        path.pop();
447        let verdict = (!moving && !roots.is_empty()).then_some(roots);
448        if !cyclic {
449            memo.insert(id.to_owned(), verdict.clone());
450        }
451        (verdict, cyclic)
452    }
453
454    /// Every stuck `blocked` task, with the root ids it is frozen behind.
455    pub fn stuck(&self) -> BTreeMap<String, BTreeSet<String>> {
456        let mut memo = BTreeMap::new();
457        let mut out = BTreeMap::new();
458        for (id, t) in &self.tasks {
459            if t.status != TaskStatus::Blocked {
460                continue;
461            }
462            let (verdict, _) = self.walk(id, &mut Vec::new(), &mut memo);
463            if let Some(roots) = verdict {
464                out.insert(id.clone(), roots);
465            }
466        }
467        out
468    }
469
470    /// The roots `task` is frozen behind; empty when it is not stuck.
471    pub fn stuck_roots(&self, task: &Task) -> BTreeSet<String> {
472        if task.status != TaskStatus::Blocked {
473            return BTreeSet::new();
474        }
475        self.walk(&task.id, &mut Vec::new(), &mut BTreeMap::new())
476            .0
477            .unwrap_or_default()
478    }
479
480    /// Each dependency of `task` with its state, e.g. `9db7 (held)` or
481    /// `4135 (blocked → 9db7 held)`. Empty unless `task` is `blocked`.
482    pub fn waits_on(&self, task: &Task) -> Vec<String> {
483        if task.status != TaskStatus::Blocked {
484            return Vec::new();
485        }
486        task.blocked_by
487            .iter()
488            .map(|b| {
489                let chain = self.chain(b, &mut vec![task.id.clone()]);
490                format!("{} ({chain})", short(b))
491            })
492            .collect()
493    }
494
495    fn chain(&self, id: &str, seen: &mut Vec<String>) -> String {
496        match self.dep(id) {
497            Dep::Missing => "missing".to_owned(),
498            Dep::Unknown => "unavailable or ambiguous".to_owned(),
499            Dep::Question(s) => format!("question {}", s.as_str()),
500            Dep::Task(t) => {
501                let mut out = t.status.as_str().to_owned();
502                if t.status != TaskStatus::Blocked {
503                    return out;
504                }
505                if seen.iter().any(|s| s == &t.id) {
506                    return format!("{out}, cycle");
507                }
508                if seen.len() > CHAIN_DEPTH {
509                    return format!("{out} → …");
510                }
511                seen.push(t.id.clone());
512                if let Some(next) = t.blocked_by.iter().find(|b| !self.resolved(b)) {
513                    out.push_str(&format!(" → {} {}", short(next), self.chain(next, seen)));
514                }
515                out
516            }
517        }
518    }
519
520    /// The task with this id, if it is one.
521    pub fn task(&self, id: &str) -> Option<&Task> {
522        match self.dep(id) {
523            Dep::Task(t) => Some(t),
524            _ => None,
525        }
526    }
527
528    pub(crate) fn is_complete(&self) -> bool {
529        self.complete
530    }
531
532    pub(crate) fn tasks(&self) -> &BTreeMap<String, Task> {
533        &self.tasks
534    }
535
536    pub(crate) fn resolve_blocker(&self, id: &str) -> ResolvedBlocker<'_> {
537        let to_decision = |q: &DecisionRecord| {
538            ResolvedBlocker::Decision(Box::new(ResolvedDecision {
539                id: q.id.clone(),
540                status: q.status,
541                summary: q.summary.clone(),
542                routed_task: q.routed_task.clone(),
543                routed_chat: q.routed_chat.clone(),
544                view: decision_view(q),
545            }))
546        };
547        if let Some(t) = self.tasks.get(id) {
548            return ResolvedBlocker::Task(t);
549        }
550        if let Some(q) = self.questions.get(id) {
551            return to_decision(q);
552        }
553        if !self.complete {
554            return ResolvedBlocker::Unavailable;
555        }
556        match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
557            crate::queue::Reference::Found(full) => {
558                if let Some(t) = self.tasks.get(&full) {
559                    ResolvedBlocker::Task(t)
560                } else if let Some(q) = self.questions.get(&full) {
561                    to_decision(q)
562                } else {
563                    ResolvedBlocker::Unavailable
564                }
565            }
566            crate::queue::Reference::Missing => ResolvedBlocker::Missing,
567            crate::queue::Reference::Ambiguous => ResolvedBlocker::Ambiguous,
568        }
569    }
570}
571
572#[cfg(test)]
573mod tests {
574    use super::*;
575    use crate::queue::Source;
576    use std::path::PathBuf;
577
578    fn t(id: &str, status: TaskStatus, blocked_by: &[&str]) -> Task {
579        let mut t = Task::new(
580            id.to_owned(),
581            "x".to_owned(),
582            PathBuf::from("/repo"),
583            Source::Human,
584        );
585        t.id = format!("2026-{id}");
586        t.status = status;
587        t.blocked_by = blocked_by.iter().map(|b| format!("2026-{b}")).collect();
588        t
589    }
590
591    fn inv(tasks: Vec<Task>) -> Inventory {
592        Inventory::new(tasks, &[])
593    }
594
595    #[test]
596    fn blocker_views_preserve_all_dependencies_and_decision_delivery_states() {
597        let held = t("held", TaskStatus::Held, &[]);
598        let done = t("done", TaskStatus::Done, &[]);
599        let mut decision = Question::new(
600            "run".into(),
601            "node".into(),
602            "seat".into(),
603            "Choose recovery".into(),
604            "Context".into(),
605            vec![],
606        );
607        decision.routed_task = Some(held.id.clone());
608        let mut waiting = t("waiting", TaskStatus::Blocked, &["held", "done", "missing"]);
609        waiting.blocked_by.push(decision.id.clone());
610        let inventory = Inventory::new(
611            vec![held.clone(), done, waiting.clone()],
612            std::slice::from_ref(&decision),
613        );
614        let views = inventory.blocker_views(&waiting);
615        assert_eq!(views.len(), 4);
616        assert_eq!(views[0].destination, Some(("tasks", held.id.clone())));
617        assert!(!views[0].resolves_itself);
618        assert!(views[1].resolves_itself);
619        assert!(views[1].next.contains("reconcile"));
620        assert_eq!(views[2].state, "missing");
621        assert!(views[2].destination.is_none());
622        assert!(!views[2].resolves_itself);
623        assert!(!views[3].resolves_itself);
624        assert!(views[3].next.contains("delivery"));
625        assert!(views[3].destination.is_none());
626        assert!(inventory.blocker_views(&held).is_empty());
627        for status in [
628            QuestionStatus::Open,
629            QuestionStatus::Answered,
630            QuestionStatus::Abandoned,
631        ] {
632            decision.status = status;
633            decision.routed_chat = Some("owning-chat".into());
634            let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
635            let views = inventory.blocker_views(&waiting);
636            assert_eq!(views[3].resolves_itself, status == QuestionStatus::Answered);
637            assert_eq!(views[3].id, decision.id);
638            assert_eq!(views[3].destination, Some(("chat", "owning-chat".into())));
639            assert_eq!(views[3].reason.as_deref(), Some("Choose recovery"));
640        }
641        decision.routed_task = None;
642        decision.routed_chat = None;
643        decision.status = QuestionStatus::Open;
644        let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
645        assert_eq!(
646            inventory.blocker_views(&waiting)[3].destination,
647            Some(("questions", decision.id))
648        );
649    }
650
651    #[test]
652    fn blocker_views_distinguish_automatic_progress_from_operator_recovery() {
653        for status in [
654            TaskStatus::Queued,
655            TaskStatus::Running,
656            TaskStatus::Failed,
657            TaskStatus::Parked,
658            TaskStatus::Done,
659            TaskStatus::Held,
660            TaskStatus::Blocked,
661        ] {
662            let dependency = t("dependency", status, &[]);
663            let waiting = t("waiting", TaskStatus::Blocked, &["dependency"]);
664            let inventory = inv(vec![dependency, waiting.clone()]);
665            let views = inventory.blocker_views(&waiting);
666            assert_eq!(
667                views[0].resolves_itself,
668                !matches!(status, TaskStatus::Held | TaskStatus::Blocked),
669                "{status:?}"
670            );
671            if status == TaskStatus::Running {
672                assert!(views[0].next.contains("No operator action"));
673            }
674        }
675        let waiting = t("waiting", TaskStatus::Blocked, &["waiting"]);
676        let inventory = inv(vec![waiting.clone()]);
677        let views = inventory.blocker_views(&waiting);
678        assert!(!views[0].resolves_itself);
679        assert!(views[0].next.contains("cycle"));
680    }
681
682    #[test]
683    fn blocker_views_do_not_link_ambiguous_unreadable_or_removed_records() {
684        let dir = tempfile::tempdir().unwrap();
685        let queue = crate::queue::Queue::at(dir.path().join("queue"));
686        let questions = crate::ask::Questions::at(dir.path().join("questions"));
687        let mut waiting = t("waiting", TaskStatus::Blocked, &[]);
688        waiting.blocked_by = vec!["collision".into(), "broken".into(), "removed".into()];
689        queue.put(&mut waiting).unwrap();
690        for name in [
691            "a-collision.json",
692            "b-collision.removed",
693            "broken.json",
694            "removed.removed",
695        ] {
696            std::fs::write(queue.root().join(name), "unreadable").unwrap();
697        }
698        let inventory = Inventory::load_for(&queue, &questions, &waiting);
699        let views = inventory.blocker_views(&waiting);
700        assert_eq!(views.len(), 3);
701        assert!(
702            views
703                .iter()
704                .all(|view| view.destination.is_none() && view.state == "unavailable or ambiguous")
705        );
706    }
707
708    #[test]
709    fn responsiveness_dependency_closure_matches_the_full_inventory() {
710        let dir = tempfile::tempdir().unwrap();
711        let queue = crate::queue::Queue::at(dir.path().join("queue"));
712        let questions = crate::ask::Questions::at(dir.path().join("questions"));
713        let mut held = t("held", TaskStatus::Held, &[]);
714        let mut middle = t("middle", TaskStatus::Blocked, &["held"]);
715        let mut waiting = t("waiting", TaskStatus::Blocked, &["middle"]);
716        for task in [&mut held, &mut middle, &mut waiting] {
717            queue.put(task).unwrap();
718        }
719        for n in 0..150 {
720            let mut unrelated = t(&format!("noise{n}"), TaskStatus::Done, &[]);
721            unrelated.instruction = "history ".repeat(4096);
722            queue.put(&mut unrelated).unwrap();
723        }
724        for reference in ["2026-middle", "middle", "missing", "collision"] {
725            waiting.blocked_by = vec![reference.into()];
726            queue.put(&mut waiting).unwrap();
727            std::fs::write(queue.root().join("a-collision.json"), "corrupt").unwrap();
728            std::fs::write(queue.root().join("b-collision.removed"), "removed").unwrap();
729            let full = Inventory::load(&queue, &questions);
730            let small = Inventory::load_for(&queue, &questions, &waiting);
731            assert_eq!(small.waits_on(&waiting), full.waits_on(&waiting));
732            assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
733            assert!(small.tasks.len() <= 3);
734        }
735        // A cycle uses the same recursion and root rules as the full inventory.
736        held.status = TaskStatus::Blocked;
737        held.blocked_by = vec![middle.id.clone()];
738        queue.put(&mut held).unwrap();
739        waiting.blocked_by = vec![middle.id.clone()];
740        queue.put(&mut waiting).unwrap();
741        let full = Inventory::load(&queue, &questions);
742        let small = Inventory::load_for(&queue, &questions, &waiting);
743        assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
744    }
745
746    #[test]
747    fn dependency_resolution_partial_scan_keeps_readable_exact_records() {
748        let dir = tempfile::tempdir().unwrap();
749        let queue = crate::queue::Queue::at(dir.path().join("queue"));
750        let questions = crate::ask::Questions::at(dir.path().join("questions"));
751        let mut running = t("feb2", TaskStatus::Running, &[]);
752        let mut middle = t("ca5b", TaskStatus::Blocked, &["feb2"]);
753        let mut waiting = t("ee37", TaskStatus::Blocked, &["ca5b"]);
754        let mut held = t("held", TaskStatus::Held, &[]);
755        let mut short_wait = t("short", TaskStatus::Blocked, &[]);
756        short_wait.blocked_by = vec!["held".into()];
757        for task in [
758            &mut running,
759            &mut middle,
760            &mut waiting,
761            &mut held,
762            &mut short_wait,
763        ] {
764            queue.put(task).unwrap();
765        }
766        // Reading the queue succeeds, while scanning the question store fails.
767        std::fs::write(questions.root(), "not a directory").unwrap();
768        let inventory = Inventory::load(&queue, &questions);
769        assert!(!inventory.complete);
770        assert!(inventory.ids.contains(&running.id));
771        assert_eq!(
772            inventory.task(&running.id).unwrap().status,
773            TaskStatus::Running
774        );
775        assert_eq!(
776            inventory.waits_on(&waiting),
777            ["ca5b (blocked → feb2 running)"]
778        );
779        assert_eq!(
780            inventory.waits_on(&short_wait),
781            ["held (unavailable or ambiguous)"]
782        );
783        assert!(
784            inventory.stuck().is_empty(),
785            "partial scans cannot prove short-id uniqueness"
786        );
787        assert!(matches!(inventory.dep("not-seen"), Dep::Unknown));
788    }
789
790    #[test]
791    fn a_chain_reads_at_a_glance_and_its_root_is_the_held_task() {
792        let i = inv(vec![
793            t("9db7", TaskStatus::Held, &[]),
794            t("4135", TaskStatus::Blocked, &["9db7"]),
795            t("6081", TaskStatus::Blocked, &["4135"]),
796        ]);
797        let six = i.task("2026-6081").unwrap();
798        assert_eq!(i.waits_on(six), ["4135 (blocked → 9db7 held)"]);
799        let four = i.task("2026-4135").unwrap();
800        assert_eq!(i.waits_on(four), ["9db7 (held)"]);
801        let stuck = i.stuck();
802        assert_eq!(stuck.len(), 2);
803        assert!(stuck.values().all(|r| r.iter().eq(["2026-9db7"].iter())));
804    }
805
806    #[test]
807    fn a_dependency_that_can_still_run_is_not_stuck() {
808        let i = inv(vec![
809            t("aaaa", TaskStatus::Queued, &[]),
810            t("bbbb", TaskStatus::Held, &[]),
811            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
812            t("dddd", TaskStatus::Blocked, &["missing1"]),
813            t("eeee", TaskStatus::Blocked, &["cccc"]),
814        ]);
815        assert!(i.stuck().is_empty(), "{:?}", i.stuck());
816    }
817
818    #[test]
819    fn a_done_dependency_does_not_hide_a_held_one() {
820        let i = inv(vec![
821            t("aaaa", TaskStatus::Done, &[]),
822            t("bbbb", TaskStatus::Held, &[]),
823            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
824        ]);
825        assert_eq!(i.stuck().len(), 1);
826    }
827
828    #[test]
829    fn a_cycle_terminates_and_names_its_smallest_id_from_every_entry() {
830        let i = inv(vec![
831            t("bbbb", TaskStatus::Blocked, &["cccc"]),
832            t("cccc", TaskStatus::Blocked, &["aaaa"]),
833            t("aaaa", TaskStatus::Blocked, &["bbbb"]),
834            t("dddd", TaskStatus::Blocked, &["cccc"]),
835        ]);
836        let stuck = i.stuck();
837        assert_eq!(stuck.len(), 4);
838        for roots in stuck.values() {
839            assert!(roots.iter().eq(["2026-aaaa"].iter()), "{roots:?}");
840        }
841        let d = i.task("2026-dddd").unwrap();
842        assert!(i.waits_on(d)[0].contains("cycle"), "{:?}", i.waits_on(d));
843    }
844
845    #[test]
846    fn a_self_dependency_is_a_stuck_cycle_of_one() {
847        let i = inv(vec![t("aaaa", TaskStatus::Blocked, &["aaaa"])]);
848        assert_eq!(i.stuck().len(), 1);
849    }
850
851    #[test]
852    fn an_open_question_keeps_a_task_alive_and_an_answered_one_resolves() {
853        let mut open = Question::new(
854            "r".into(),
855            "n".into(),
856            "s".into(),
857            "?".into(),
858            String::new(),
859            vec![],
860        );
861        open.id = "2026-qqqq".into();
862        let mut answered = open.clone();
863        answered.id = "2026-rrrr".into();
864        answered.status = QuestionStatus::Answered;
865        let tasks = vec![
866            t("bbbb", TaskStatus::Held, &[]),
867            t("cccc", TaskStatus::Blocked, &["bbbb", "qqqq"]),
868            t("dddd", TaskStatus::Blocked, &["bbbb", "rrrr"]),
869        ];
870        let i = Inventory::new(tasks, &[open, answered]);
871        let stuck = i.stuck();
872        assert!(!stuck.contains_key("2026-cccc"));
873        assert!(stuck.contains_key("2026-dddd"));
874        let c = i.task("2026-cccc").unwrap();
875        assert_eq!(i.waits_on(c)[1], "qqqq (question open)");
876    }
877}