magi-cli 0.239.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
//! Dependency inventory for `blocked` tasks.
//!
//! [`crate::daemon::resolve_blockers`] frees a task when its dependency is
//! `done` (or its question answered) and quarantines it when the dependency no
//! longer exists. It has nothing to say about a dependency that is alive but
//! *stuck*: a `held` task never becomes `done` on its own, so everything
//! waiting on it waits forever, and nothing shows why. [`Inventory`] answers
//! that from one snapshot of the queue and the questions:
//!
//! - [`Inventory::waits_on`] - what a blocked task waits on and each
//!   dependency's state, following a chain of blocked dependencies
//!   (`4135 (blocked → 9db7 held)`), for `magi task list` and the web UI.
//! - [`Inventory::stuck_roots`] - the tasks nothing in the loop will ever run
//!   that a blocked task is frozen behind. [`crate::triage`] asks about each
//!   such root once, naming everything it freezes.
//!
//! A blocked task is *stuck* when it has at least one unresolved dependency
//! and every one of them is either `held` or itself a stuck blocked task.
//! Anything that can still make progress - a queued, running or failed
//! (retried) task, an open question, a dependency that no longer exists (which
//! `resolve_blockers` quarantines) - makes it not stuck. A dependency cycle
//! terminates: its members are stuck, and the smallest id in the cycle is its
//! root.

use std::collections::{BTreeMap, BTreeSet};

use crate::ask::{Question, QuestionStatus};
use crate::queue::{Task, TaskStatus};

/// How many hops [`Inventory::waits_on`] follows before it stops describing.
const CHAIN_DEPTH: usize = 4;

/// One snapshot of the tasks and questions a `blocked_by` id can name.
#[derive(Debug, Clone, Default)]
pub struct Inventory {
    tasks: BTreeMap<String, Task>,
    questions: BTreeMap<String, DecisionRecord>,
    ids: Vec<String>,
    complete: bool,
}

// Keep only routing metadata, rather than duplicating decision transcripts,
// panels and answer payloads in a dependency inventory.
#[derive(Debug, Clone)]
struct DecisionRecord {
    id: String,
    status: QuestionStatus,
    summary: String,
    routed_task: Option<String>,
    routed_chat: Option<String>,
}

impl From<&Question> for DecisionRecord {
    fn from(q: &Question) -> Self {
        Self {
            id: q.id.clone(),
            status: q.status,
            summary: q.summary.clone(),
            routed_task: q.routed_task.clone(),
            routed_chat: q.routed_chat.clone(),
        }
    }
}

enum Dep<'a> {
    Task(&'a Task),
    Question(QuestionStatus),
    Missing,
    Unknown,
}

type Roots = Option<BTreeSet<String>>;

/// Read-only dependency presentation. Decision records are interpreted only
/// here, alongside the compatibility resolver; clients never infer ownership.
#[derive(Debug, serde::Serialize)]
pub struct BlockerView {
    /// Canonical id when readable, otherwise the stored reference.
    pub id: String,
    /// Task, decision, or unavailable record.
    pub kind: &'static str,
    /// Recorded status and bounded dependency chain.
    pub state: String,
    /// Task title or decision summary, when readable.
    pub reason: Option<String>,
    /// Explanation of the supported next step.
    pub next: String,
    /// True when progress or scheduler reconciliation needs no operator action.
    pub resolves_itself: bool,
    /// Existing read-only page route and record id; never a control endpoint.
    pub destination: Option<(&'static str, String)>,
}

/// The last dash-separated part of an id: what `Task::short` shows.
fn short(id: &str) -> &str {
    id.split('-').next_back().unwrap_or(id)
}

fn decision_view(q: &DecisionRecord) -> BlockerView {
    let mut view = BlockerView {
        id: q.id.clone(),
        kind: "decision",
        state: q.status.as_str().into(),
        reason: Some(q.summary.clone()),
        next: String::new(),
        resolves_itself: q.status == QuestionStatus::Answered,
        destination: None,
    };
    view.next = match q.status {
        QuestionStatus::Answered => "Decision recorded; waiting for the scheduler to reconcile this dependency.",
        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.",
        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.",
        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.",
        QuestionStatus::Open => "Open the existing decision to inspect its context and available controls. A historical or unavailable waiter may no longer accept an answer.",
    }.into();
    view.destination = if q.routed_task.is_some() {
        q.routed_chat.clone().map(|id| ("chat", id))
    } else if q.status == QuestionStatus::Open {
        Some(("questions", q.id.clone()))
    } else {
        None
    };
    view
}

impl Inventory {
    /// All direct blockers, including settled and unavailable records. Task
    /// links let the operator follow chains without hiding sibling blockers.
    pub fn blocker_views(&self, task: &Task) -> Vec<BlockerView> {
        if task.status != TaskStatus::Blocked {
            return Vec::new();
        }
        task.blocked_by.iter().map(|id| {
            let mut view = BlockerView {
                id: id.clone(), kind: "unavailable", state: self.chain(id, &mut vec![task.id.clone()]),
                reason: None, resolves_itself: false,
                next: "Inspect the dependency reference with magi task triage; unavailable or ambiguous records cannot safely be treated as resolved.".into(),
                destination: None,
            };
            match self.dep(id) {
                Dep::Task(t) => {
                    view.id = t.id.clone();
                    view.kind = "task";
                    view.reason = Some(t.title.clone());
                    view.resolves_itself = matches!(t.status, TaskStatus::Queued | TaskStatus::Running | TaskStatus::Failed | TaskStatus::Parked | TaskStatus::Done);
                    view.next = if t.status == TaskStatus::Done {
                        "Completed; waiting for the scheduler to reconcile this dependency."
                    } else if view.state.contains("cycle") {
                        "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."
                    } else if view.resolves_itself {
                        "This dependency is still progressing or awaiting scheduler retry. No operator action is needed for this blocker; wait for it to complete."
                    } else {
                        "Open the dependency task to inspect its status, blockers and recovery controls. It must complete before this dependency resolves."
                    }.into();
                    view.destination = Some(("tasks", t.id.clone()));
                }
                Dep::Question(_) => {
                    // Compatibility with existing decision outbox records;
                    // do not create a decision or derive a chat from ancestry.
                    let full = match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
                        crate::queue::Reference::Found(full) => full,
                        _ => id.clone(),
                    };
                    if let Some(q) = self.questions.get(&full) {
                        view = decision_view(q);
                    }
                }
                Dep::Missing => view.state = "missing".into(),
                Dep::Unknown => {},
            }
            view
        }).collect()
    }

    /// Pending held-task recovery decisions use the same compatibility
    /// navigation as dependencies, with triage's exact pending predicate.
    pub(crate) fn recovery_views(
        task: &Task,
        questions: &crate::ask::Questions,
    ) -> Vec<BlockerView> {
        crate::triage::pending_recovery_questions(questions, task).iter().map(|q| {
            let mut view = decision_view(&DecisionRecord::from(q));
            view.kind = "recovery decision";
            view.next = if q.status.open() {
                if q.routed_task.is_some() && q.routed_chat.is_none() {
                    "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."
                } else {
                    "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."
                }
            } else {
                "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."
            }.into();
            view.resolves_itself = q.status == QuestionStatus::Answered && q.routed_chat.is_none();
            view
        }).collect()
    }

    /// Build the snapshot. Callers take `queue.list()` and `questions.list()`
    /// once, so a listing over many tasks never rescans the disk per task.
    pub fn new(tasks: Vec<Task>, questions: &[Question]) -> Self {
        let ids = tasks
            .iter()
            .map(|t| t.id.clone())
            .chain(questions.iter().map(|q| q.id.clone()))
            .collect();
        Self {
            ids,
            complete: true,
            tasks: tasks.into_iter().map(|t| (t.id.clone(), t)).collect(),
            questions: questions
                .iter()
                .map(|q| (q.id.clone(), DecisionRecord::from(q)))
                .collect(),
        }
    }

    /// Include unreadable records and tombstones in id resolution; list()
    /// alone cannot prove uniqueness or absence.
    pub fn load(queue: &crate::queue::Queue, questions: &crate::ask::Questions) -> Self {
        Self::load_with_tasks(queue, questions, queue.list())
    }

    /// Reuse a listing already read by the caller. Still include tombstones
    /// and unreadable ids when resolving dependency ambiguity.
    pub fn load_with_tasks(
        queue: &crate::queue::Queue,
        questions: &crate::ask::Questions,
        tasks: Vec<Task>,
    ) -> Self {
        let mut inventory = Self::new(tasks, &questions.list_for_effects());
        let ids = (|| -> anyhow::Result<Vec<String>> {
            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
            ids.sort();
            ids.dedup();
            Ok(ids)
        })();
        match ids {
            Ok(ids) => inventory.ids = ids,
            Err(_) => inventory.complete = false,
        }
        inventory
    }

    /// Read only the dependency closure for a detail view. Names across both
    /// stores (including tombstones and corrupt records) still establish
    /// ambiguity, and unreadable records remain unknown rather than resolved.
    pub fn load_for(
        queue: &crate::queue::Queue,
        questions: &crate::ask::Questions,
        task: &Task,
    ) -> Self {
        Self::load_for_tasks(queue, questions, std::slice::from_ref(task))
    }

    /// Share id enumeration and dependency reads across one list page.
    pub fn load_for_tasks(
        queue: &crate::queue::Queue,
        questions: &crate::ask::Questions,
        tasks: &[Task],
    ) -> Self {
        let mut inventory = Self::new(tasks.to_vec(), &[]);
        if tasks.iter().all(|task| task.blocked_by.is_empty()) {
            return inventory;
        }
        let ids = (|| -> anyhow::Result<Vec<String>> {
            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
            ids.sort();
            ids.dedup();
            Ok(ids)
        })();
        match ids {
            Ok(ids) => inventory.ids = ids,
            Err(_) => inventory.complete = false,
        }
        let mut pending: Vec<_> = tasks
            .iter()
            .flat_map(|task| task.blocked_by.iter().cloned())
            .collect();
        let mut seen = BTreeSet::new();
        let ownership = crate::task_chat::InquiryOwnership::default();
        while let Some(reference) = pending.pop() {
            let full =
                if queue.path_of(&reference).is_file() || questions.path_of(&reference).is_file() {
                    reference
                } else if inventory.complete {
                    match crate::queue::resolve_reference(
                        &reference,
                        inventory.ids.iter().map(String::as_str),
                    ) {
                        crate::queue::Reference::Found(full) => full,
                        _ => continue,
                    }
                } else {
                    continue;
                };
            if !seen.insert(full.clone()) {
                continue;
            }
            if queue.path_of(&full).is_file()
                && let Ok(t) = queue.get(&full)
            {
                pending.extend(t.blocked_by.iter().cloned());
                inventory.tasks.insert(full.clone(), t);
            }
            if questions.path_of(&full).is_file()
                && let Ok(q) = questions.get_for_effects_in(&full, &ownership)
            {
                inventory.questions.insert(full, DecisionRecord::from(&q));
            }
        }
        inventory
    }

    fn dep(&self, id: &str) -> Dep<'_> {
        // A partial scan does not invalidate readable exact records. It does
        // prevent proving that a prefix/suffix is unique across both stores.
        if let Some(t) = self.tasks.get(id) {
            return Dep::Task(t);
        }
        if let Some(s) = self.questions.get(id) {
            return Dep::Question(s.status);
        }
        if !self.complete {
            return Dep::Unknown;
        }
        match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
            crate::queue::Reference::Found(full) => {
                if let Some(t) = self.tasks.get(&full) {
                    Dep::Task(t)
                } else if let Some(s) = self.questions.get(&full) {
                    Dep::Question(s.status)
                } else {
                    Dep::Unknown
                }
            }
            crate::queue::Reference::Missing => Dep::Missing,
            crate::queue::Reference::Ambiguous => Dep::Unknown,
        }
    }

    /// A dependency that has nothing left to wait for.
    fn resolved(&self, id: &str) -> bool {
        match self.dep(id) {
            Dep::Task(t) => t.status == TaskStatus::Done,
            Dep::Question(s) => s == QuestionStatus::Answered,
            Dep::Missing | Dep::Unknown => false,
        }
    }

    fn walk(
        &self,
        id: &str,
        path: &mut Vec<String>,
        memo: &mut BTreeMap<String, Roots>,
    ) -> (Roots, bool) {
        if let Some(v) = memo.get(id) {
            return (v.clone(), false);
        }
        let Some(task) = self.tasks.get(id) else {
            return (None, false);
        };
        path.push(id.to_owned());
        let mut roots = BTreeSet::new();
        let mut moving = false;
        let mut cyclic = false;
        for b in &task.blocked_by {
            match self.dep(b) {
                Dep::Task(t) => match t.status {
                    TaskStatus::Done => {}
                    TaskStatus::Held => {
                        roots.insert(t.id.clone());
                    }
                    TaskStatus::Blocked => {
                        if let Some(pos) = path.iter().position(|p| p == &t.id) {
                            // A cycle: its smallest id speaks for all of it, so
                            // every entry point names the same root.
                            if let Some(min) = path[pos..].iter().min() {
                                roots.insert(min.clone());
                            }
                            cyclic = true;
                        } else {
                            let (sub, c) = self.walk(&t.id, path, memo);
                            cyclic |= c;
                            match sub {
                                Some(r) => roots.extend(r),
                                None => moving = true,
                            }
                        }
                    }
                    TaskStatus::Queued
                    | TaskStatus::Running
                    | TaskStatus::Failed
                    | TaskStatus::Parked => {
                        moving = true;
                    }
                },
                Dep::Question(QuestionStatus::Answered) => {}
                Dep::Question(_) | Dep::Missing | Dep::Unknown => moving = true,
            }
        }
        path.pop();
        let verdict = (!moving && !roots.is_empty()).then_some(roots);
        if !cyclic {
            memo.insert(id.to_owned(), verdict.clone());
        }
        (verdict, cyclic)
    }

    /// Every stuck `blocked` task, with the root ids it is frozen behind.
    pub fn stuck(&self) -> BTreeMap<String, BTreeSet<String>> {
        let mut memo = BTreeMap::new();
        let mut out = BTreeMap::new();
        for (id, t) in &self.tasks {
            if t.status != TaskStatus::Blocked {
                continue;
            }
            let (verdict, _) = self.walk(id, &mut Vec::new(), &mut memo);
            if let Some(roots) = verdict {
                out.insert(id.clone(), roots);
            }
        }
        out
    }

    /// The roots `task` is frozen behind; empty when it is not stuck.
    pub fn stuck_roots(&self, task: &Task) -> BTreeSet<String> {
        if task.status != TaskStatus::Blocked {
            return BTreeSet::new();
        }
        self.walk(&task.id, &mut Vec::new(), &mut BTreeMap::new())
            .0
            .unwrap_or_default()
    }

    /// Each dependency of `task` with its state, e.g. `9db7 (held)` or
    /// `4135 (blocked → 9db7 held)`. Empty unless `task` is `blocked`.
    pub fn waits_on(&self, task: &Task) -> Vec<String> {
        if task.status != TaskStatus::Blocked {
            return Vec::new();
        }
        task.blocked_by
            .iter()
            .map(|b| {
                let chain = self.chain(b, &mut vec![task.id.clone()]);
                format!("{} ({chain})", short(b))
            })
            .collect()
    }

    fn chain(&self, id: &str, seen: &mut Vec<String>) -> String {
        match self.dep(id) {
            Dep::Missing => "missing".to_owned(),
            Dep::Unknown => "unavailable or ambiguous".to_owned(),
            Dep::Question(s) => format!("question {}", s.as_str()),
            Dep::Task(t) => {
                let mut out = t.status.as_str().to_owned();
                if t.status != TaskStatus::Blocked {
                    return out;
                }
                if seen.iter().any(|s| s == &t.id) {
                    return format!("{out}, cycle");
                }
                if seen.len() > CHAIN_DEPTH {
                    return format!("{out} → …");
                }
                seen.push(t.id.clone());
                if let Some(next) = t.blocked_by.iter().find(|b| !self.resolved(b)) {
                    out.push_str(&format!(" → {} {}", short(next), self.chain(next, seen)));
                }
                out
            }
        }
    }

    /// The task with this id, if it is one.
    pub fn task(&self, id: &str) -> Option<&Task> {
        match self.dep(id) {
            Dep::Task(t) => Some(t),
            _ => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::queue::Source;
    use std::path::PathBuf;

    fn t(id: &str, status: TaskStatus, blocked_by: &[&str]) -> Task {
        let mut t = Task::new(
            id.to_owned(),
            "x".to_owned(),
            PathBuf::from("/repo"),
            Source::Human,
        );
        t.id = format!("2026-{id}");
        t.status = status;
        t.blocked_by = blocked_by.iter().map(|b| format!("2026-{b}")).collect();
        t
    }

    fn inv(tasks: Vec<Task>) -> Inventory {
        Inventory::new(tasks, &[])
    }

    #[test]
    fn blocker_views_preserve_all_dependencies_and_decision_delivery_states() {
        let held = t("held", TaskStatus::Held, &[]);
        let done = t("done", TaskStatus::Done, &[]);
        let mut decision = Question::new(
            "run".into(),
            "node".into(),
            "seat".into(),
            "Choose recovery".into(),
            "Context".into(),
            vec![],
        );
        decision.routed_task = Some(held.id.clone());
        let mut waiting = t("waiting", TaskStatus::Blocked, &["held", "done", "missing"]);
        waiting.blocked_by.push(decision.id.clone());
        let inventory = Inventory::new(
            vec![held.clone(), done, waiting.clone()],
            std::slice::from_ref(&decision),
        );
        let views = inventory.blocker_views(&waiting);
        assert_eq!(views.len(), 4);
        assert_eq!(views[0].destination, Some(("tasks", held.id.clone())));
        assert!(!views[0].resolves_itself);
        assert!(views[1].resolves_itself);
        assert!(views[1].next.contains("reconcile"));
        assert_eq!(views[2].state, "missing");
        assert!(views[2].destination.is_none());
        assert!(!views[2].resolves_itself);
        assert!(!views[3].resolves_itself);
        assert!(views[3].next.contains("delivery"));
        assert!(views[3].destination.is_none());
        assert!(inventory.blocker_views(&held).is_empty());
        for status in [
            QuestionStatus::Open,
            QuestionStatus::Answered,
            QuestionStatus::Abandoned,
        ] {
            decision.status = status;
            decision.routed_chat = Some("owning-chat".into());
            let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
            let views = inventory.blocker_views(&waiting);
            assert_eq!(views[3].resolves_itself, status == QuestionStatus::Answered);
            assert_eq!(views[3].id, decision.id);
            assert_eq!(views[3].destination, Some(("chat", "owning-chat".into())));
            assert_eq!(views[3].reason.as_deref(), Some("Choose recovery"));
        }
        decision.routed_task = None;
        decision.routed_chat = None;
        decision.status = QuestionStatus::Open;
        let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
        assert_eq!(
            inventory.blocker_views(&waiting)[3].destination,
            Some(("questions", decision.id))
        );
    }

    #[test]
    fn blocker_views_distinguish_automatic_progress_from_operator_recovery() {
        for status in [
            TaskStatus::Queued,
            TaskStatus::Running,
            TaskStatus::Failed,
            TaskStatus::Parked,
            TaskStatus::Done,
            TaskStatus::Held,
            TaskStatus::Blocked,
        ] {
            let dependency = t("dependency", status, &[]);
            let waiting = t("waiting", TaskStatus::Blocked, &["dependency"]);
            let inventory = inv(vec![dependency, waiting.clone()]);
            let views = inventory.blocker_views(&waiting);
            assert_eq!(
                views[0].resolves_itself,
                !matches!(status, TaskStatus::Held | TaskStatus::Blocked),
                "{status:?}"
            );
            if status == TaskStatus::Running {
                assert!(views[0].next.contains("No operator action"));
            }
        }
        let waiting = t("waiting", TaskStatus::Blocked, &["waiting"]);
        let inventory = inv(vec![waiting.clone()]);
        let views = inventory.blocker_views(&waiting);
        assert!(!views[0].resolves_itself);
        assert!(views[0].next.contains("cycle"));
    }

    #[test]
    fn blocker_views_do_not_link_ambiguous_unreadable_or_removed_records() {
        let dir = tempfile::tempdir().unwrap();
        let queue = crate::queue::Queue::at(dir.path().join("queue"));
        let questions = crate::ask::Questions::at(dir.path().join("questions"));
        let mut waiting = t("waiting", TaskStatus::Blocked, &[]);
        waiting.blocked_by = vec!["collision".into(), "broken".into(), "removed".into()];
        queue.put(&mut waiting).unwrap();
        for name in [
            "a-collision.json",
            "b-collision.removed",
            "broken.json",
            "removed.removed",
        ] {
            std::fs::write(queue.root().join(name), "unreadable").unwrap();
        }
        let inventory = Inventory::load_for(&queue, &questions, &waiting);
        let views = inventory.blocker_views(&waiting);
        assert_eq!(views.len(), 3);
        assert!(
            views
                .iter()
                .all(|view| view.destination.is_none() && view.state == "unavailable or ambiguous")
        );
    }

    #[test]
    fn responsiveness_dependency_closure_matches_the_full_inventory() {
        let dir = tempfile::tempdir().unwrap();
        let queue = crate::queue::Queue::at(dir.path().join("queue"));
        let questions = crate::ask::Questions::at(dir.path().join("questions"));
        let mut held = t("held", TaskStatus::Held, &[]);
        let mut middle = t("middle", TaskStatus::Blocked, &["held"]);
        let mut waiting = t("waiting", TaskStatus::Blocked, &["middle"]);
        for task in [&mut held, &mut middle, &mut waiting] {
            queue.put(task).unwrap();
        }
        for n in 0..150 {
            let mut unrelated = t(&format!("noise{n}"), TaskStatus::Done, &[]);
            unrelated.instruction = "history ".repeat(4096);
            queue.put(&mut unrelated).unwrap();
        }
        for reference in ["2026-middle", "middle", "missing", "collision"] {
            waiting.blocked_by = vec![reference.into()];
            queue.put(&mut waiting).unwrap();
            std::fs::write(queue.root().join("a-collision.json"), "corrupt").unwrap();
            std::fs::write(queue.root().join("b-collision.removed"), "removed").unwrap();
            let full = Inventory::load(&queue, &questions);
            let small = Inventory::load_for(&queue, &questions, &waiting);
            assert_eq!(small.waits_on(&waiting), full.waits_on(&waiting));
            assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
            assert!(small.tasks.len() <= 3);
        }
        // A cycle uses the same recursion and root rules as the full inventory.
        held.status = TaskStatus::Blocked;
        held.blocked_by = vec![middle.id.clone()];
        queue.put(&mut held).unwrap();
        waiting.blocked_by = vec![middle.id.clone()];
        queue.put(&mut waiting).unwrap();
        let full = Inventory::load(&queue, &questions);
        let small = Inventory::load_for(&queue, &questions, &waiting);
        assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
    }

    #[test]
    fn dependency_resolution_partial_scan_keeps_readable_exact_records() {
        let dir = tempfile::tempdir().unwrap();
        let queue = crate::queue::Queue::at(dir.path().join("queue"));
        let questions = crate::ask::Questions::at(dir.path().join("questions"));
        let mut running = t("feb2", TaskStatus::Running, &[]);
        let mut middle = t("ca5b", TaskStatus::Blocked, &["feb2"]);
        let mut waiting = t("ee37", TaskStatus::Blocked, &["ca5b"]);
        let mut held = t("held", TaskStatus::Held, &[]);
        let mut short_wait = t("short", TaskStatus::Blocked, &[]);
        short_wait.blocked_by = vec!["held".into()];
        for task in [
            &mut running,
            &mut middle,
            &mut waiting,
            &mut held,
            &mut short_wait,
        ] {
            queue.put(task).unwrap();
        }
        // Reading the queue succeeds, while scanning the question store fails.
        std::fs::write(questions.root(), "not a directory").unwrap();
        let inventory = Inventory::load(&queue, &questions);
        assert!(!inventory.complete);
        assert!(inventory.ids.contains(&running.id));
        assert_eq!(
            inventory.task(&running.id).unwrap().status,
            TaskStatus::Running
        );
        assert_eq!(
            inventory.waits_on(&waiting),
            ["ca5b (blocked → feb2 running)"]
        );
        assert_eq!(
            inventory.waits_on(&short_wait),
            ["held (unavailable or ambiguous)"]
        );
        assert!(
            inventory.stuck().is_empty(),
            "partial scans cannot prove short-id uniqueness"
        );
        assert!(matches!(inventory.dep("not-seen"), Dep::Unknown));
    }

    #[test]
    fn a_chain_reads_at_a_glance_and_its_root_is_the_held_task() {
        let i = inv(vec![
            t("9db7", TaskStatus::Held, &[]),
            t("4135", TaskStatus::Blocked, &["9db7"]),
            t("6081", TaskStatus::Blocked, &["4135"]),
        ]);
        let six = i.task("2026-6081").unwrap();
        assert_eq!(i.waits_on(six), ["4135 (blocked → 9db7 held)"]);
        let four = i.task("2026-4135").unwrap();
        assert_eq!(i.waits_on(four), ["9db7 (held)"]);
        let stuck = i.stuck();
        assert_eq!(stuck.len(), 2);
        assert!(stuck.values().all(|r| r.iter().eq(["2026-9db7"].iter())));
    }

    #[test]
    fn a_dependency_that_can_still_run_is_not_stuck() {
        let i = inv(vec![
            t("aaaa", TaskStatus::Queued, &[]),
            t("bbbb", TaskStatus::Held, &[]),
            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
            t("dddd", TaskStatus::Blocked, &["missing1"]),
            t("eeee", TaskStatus::Blocked, &["cccc"]),
        ]);
        assert!(i.stuck().is_empty(), "{:?}", i.stuck());
    }

    #[test]
    fn a_done_dependency_does_not_hide_a_held_one() {
        let i = inv(vec![
            t("aaaa", TaskStatus::Done, &[]),
            t("bbbb", TaskStatus::Held, &[]),
            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
        ]);
        assert_eq!(i.stuck().len(), 1);
    }

    #[test]
    fn a_cycle_terminates_and_names_its_smallest_id_from_every_entry() {
        let i = inv(vec![
            t("bbbb", TaskStatus::Blocked, &["cccc"]),
            t("cccc", TaskStatus::Blocked, &["aaaa"]),
            t("aaaa", TaskStatus::Blocked, &["bbbb"]),
            t("dddd", TaskStatus::Blocked, &["cccc"]),
        ]);
        let stuck = i.stuck();
        assert_eq!(stuck.len(), 4);
        for roots in stuck.values() {
            assert!(roots.iter().eq(["2026-aaaa"].iter()), "{roots:?}");
        }
        let d = i.task("2026-dddd").unwrap();
        assert!(i.waits_on(d)[0].contains("cycle"), "{:?}", i.waits_on(d));
    }

    #[test]
    fn a_self_dependency_is_a_stuck_cycle_of_one() {
        let i = inv(vec![t("aaaa", TaskStatus::Blocked, &["aaaa"])]);
        assert_eq!(i.stuck().len(), 1);
    }

    #[test]
    fn an_open_question_keeps_a_task_alive_and_an_answered_one_resolves() {
        let mut open = Question::new(
            "r".into(),
            "n".into(),
            "s".into(),
            "?".into(),
            String::new(),
            vec![],
        );
        open.id = "2026-qqqq".into();
        let mut answered = open.clone();
        answered.id = "2026-rrrr".into();
        answered.status = QuestionStatus::Answered;
        let tasks = vec![
            t("bbbb", TaskStatus::Held, &[]),
            t("cccc", TaskStatus::Blocked, &["bbbb", "qqqq"]),
            t("dddd", TaskStatus::Blocked, &["bbbb", "rrrr"]),
        ];
        let i = Inventory::new(tasks, &[open, answered]);
        let stuck = i.stuck();
        assert!(!stuck.contains_key("2026-cccc"));
        assert!(stuck.contains_key("2026-dddd"));
        let c = i.task("2026-cccc").unwrap();
        assert_eq!(i.waits_on(c)[1], "qqqq (question open)");
    }
}