nornir 0.4.20

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! πŸ—‚ **Funnel** tab β€” the ideaβ†’plan DAG (DAG 2) as an interactive
//! [`egui_snarl`] node graph.
//!
//! A plan is literally a DAG: nodes carrying a `kind` + `status`, wired by
//! dependency edges. We lay it out **topologically** (longest-path layering β†’
//! one column per rank, deps strictly left of dependents) and render it with
//! egui-snarl, so it pans/zooms/drags like a modern node editor while the
//! topology stays readable. Node + pin tint encode lifecycle
//! (pending/ready/in-progress/done/blocked/failed).
//!
//! Data is read **embedded** (open the funnel `Store` locally) or **remote**
//! (the `Funnel.Show` gRPC RPC), collapsing into [`FunnelView`] β€” exactly the
//! local-or-remote split the call-graph + warehouse tabs use. Writing the
//! funnel stays where it belongs: the `nornir funnel` CLI and the `funnel_*`
//! MCP tools. This tab is the read/observe surface.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::path::PathBuf;

use eframe::egui::{self, Pos2};
use egui_snarl::ui::{PinInfo, SnarlStyle, SnarlViewer};
use egui_snarl::{InPin, InPinId, NodeId, OutPin, OutPinId, Snarl};

use super::facett_theme::{Theme, RED};
use super::funnel_view::{FunnelView, NodeStat, PlanView};

/// Horizontal gap between topological ranks, vertical gap between siblings.
const X_SPACING: f32 = 250.0;
const Y_SPACING: f32 = 120.0;

enum Src {
    Local(PathBuf),
    Remote { endpoint: String, token: String },
}

/// One snarl node = one plan node (the bits the viewer renders).
struct FunnelNode {
    id: String,
    kind: String,
    title: String,
    status: NodeStat,
    targets: Vec<String>,
}

pub struct FunnelTabState {
    src: Src,
    /// Selected workspace (the `nornir-workspace` gRPC header); empty for local.
    workspace: String,
    loaded: bool,
    error: Option<String>,
    view: Option<FunnelView>,
    sel_plan: Option<String>,
    /// The laid-out graph for `built_for`.
    snarl: Snarl<FunnelNode>,
    built_for: Option<String>,
    style: SnarlStyle,
    /// E1 demo control: `--size N` for `🌱 Run demo` (local mode only).
    demo_size: usize,
    /// Two-click confirm guard for `πŸ—‘ Nuke disk`: `true` after the first click,
    /// reset on the second (which actually nukes) or when leaving the tab.
    nuke_confirm_pending: bool,
    /// Last demo/nuke outcome line, surfaced in the panel + `state_json`.
    demo_status: Option<String>,
    /// Active facett palette (broadcast from the picker).
    theme: Theme,
}

impl FunnelTabState {
    pub fn local(root: PathBuf) -> Self {
        Self::with(Src::Local(root), String::new())
    }
    pub fn remote(endpoint: String, token: String, workspace: String) -> Self {
        Self::with(Src::Remote { endpoint, token }, workspace)
    }
    fn with(src: Src, workspace: String) -> Self {
        Self {
            src,
            workspace,
            loaded: false,
            error: None,
            view: None,
            sel_plan: None,
            snarl: Snarl::new(),
            built_for: None,
            style: SnarlStyle::new(),
            demo_size: 1,
            nuke_confirm_pending: false,
            demo_status: None,
            theme: Theme::default(),
        }
    }

    /// Re-skin this pane with a facett palette (broadcast from the picker).
    pub fn set_palette(&mut self, t: Theme) {
        self.theme = t;
    }

    /// Local warehouse root this tab reads (and the demo writes to), or `None`
    /// in remote mode (where the demo controls are disabled).
    fn local_root(&self) -> Option<PathBuf> {
        match &self.src {
            Src::Local(root) => Some(root.clone()),
            Src::Remote { .. } => None,
        }
    }

    /// Force a re-read of the funnel on the next frame (after a demo/nuke wrote
    /// to the warehouse).
    fn invalidate(&mut self) {
        self.loaded = false;
        self.view = None;
        self.built_for = None;
    }

    /// Re-scope to a different workspace (the picker switched).
    pub(crate) fn set_workspace(&mut self, workspace: String) {
        self.workspace = workspace;
        self.loaded = false;
        self.error = None;
        self.view = None;
        self.sel_plan = None;
        self.built_for = None;
        self.snarl = Snarl::new();
        self.nuke_confirm_pending = false;
        self.demo_status = None;
    }

    fn load_view(&self) -> Result<FunnelView, String> {
        match &self.src {
            Src::Local(root) => crate::funnel::Store::open(root)
                .map(|mut store| {
                    // Derive the Pending→Ready frontier so the rendered DAG shows
                    // the same readiness the CLI's `next`/`show` compute (the
                    // persisted status is always Pending β€” readiness is a derived
                    // projection, never stored).
                    store.funnel.promote_ready();
                    FunnelView::from_funnel(&store.funnel)
                })
                .map_err(|e| format!("{e:#}")),
            Src::Remote { endpoint, token } => {
                super::remote::funnel_show(endpoint, token, &self.workspace)
                    .map_err(|e| format!("{e:#}"))
            }
        }
    }

    fn ensure_loaded(&mut self, log: &super::action_log::ActionLog) {
        if self.loaded {
            return;
        }
        self.loaded = true;
        match self.load_view() {
            Ok(v) => {
                if self.sel_plan.is_none() {
                    self.sel_plan = v.plans.first().map(|p| p.id.clone());
                }
                self.view = Some(v);
            }
            Err(e) => {
                // Surface the load failure into the 🐞 action-trail + stderr
                // (Kind::Error already writes stderr) β€” only on the transition
                // into error (this runs once per load, not every frame), so the
                // funnel red text is never invisible again.
                log.push(
                    super::action_log::Kind::Error,
                    format!("funnel load failed (workspace={}): {e}", self.workspace),
                );
                self.error = Some(e);
            }
        }
    }

    pub fn draw(&mut self, ui: &mut egui::Ui, log: &super::action_log::ActionLog) {
        let theme = self.theme;
        self.ensure_loaded(log);

        if let Some(err) = self.error.clone() {
            ui.colored_label(RED, err);
            return;
        }
        let plans_empty = match self.view.as_ref() {
            Some(v) => v.plans.is_empty(),
            None => {
                ui.label("loading funnel…");
                return;
            }
        };
        if plans_empty {
            // Demo controls still show in the empty state (the whole point of
            // 🌱 Run demo is to fill an empty funnel), then the CLI hint.
            egui::TopBottomPanel::top("funnel_demo_controls").show_inside(ui, |ui| {
                self.demo_panel(ui, log);
            });
            ui.vertical_centered(|ui| {
                ui.add_space(40.0);
                ui.heading("πŸ—‚ Funnel β€” no plans yet");
                ui.label("Feed the funnel from the CLI, then it appears here:");
                ui.monospace("nornir funnel submit \"<krav / prompt>\"");
                ui.monospace("nornir funnel plan <idea-id> \"<summary>\"");
                ui.monospace("nornir funnel node <plan-id> --kind … --needs …");
                ui.add_space(8.0);
                ui.label("…or click 🌱 Run demo above to inject a fake dep-graph plan.");
            });
            return;
        }
        let view = self.view.as_ref().expect("view present (checked above)");

        // Decide the selected plan, then (re)build the snarl graph if it changed.
        let sel = self
            .sel_plan
            .clone()
            .filter(|s| view.plans.iter().any(|p| &p.id == s))
            .unwrap_or_else(|| view.plans[0].id.clone());
        let to_build = if self.built_for.as_deref() != Some(sel.as_str()) {
            view.plans.iter().find(|p| p.id == sel).cloned()
        } else {
            None
        };
        if let Some(plan) = to_build {
            self.snarl = build_snarl(&plan);
            self.built_for = Some(plan.id.clone());
        }
        self.sel_plan = Some(sel.clone());

        egui::TopBottomPanel::top("funnel_controls").show_inside(ui, |ui| {
            ui.horizontal_wrapped(|ui| {
                ui.label("plan:");
                let cur = self
                    .view
                    .as_ref()
                    .and_then(|v| v.plans.iter().find(|p| p.id == sel))
                    .map(|p| format!("{} Β· {}", p.id, p.status))
                    .unwrap_or_else(|| sel.clone());
                egui::ComboBox::from_id_salt("funnel_plan")
                    .selected_text(cur)
                    .show_ui(ui, |ui| {
                        let plans: Vec<(String, String)> = self
                            .view
                            .as_ref()
                            .map(|v| v.plans.iter().map(|p| (p.id.clone(), p.status.clone())).collect())
                            .unwrap_or_default();
                        for (id, status) in plans {
                            if ui
                                .selectable_label(
                                    self.sel_plan.as_deref() == Some(&id),
                                    format!("{id} Β· {status}"),
                                )
                                .clicked()
                            {
                                self.sel_plan = Some(id);
                            }
                        }
                    });
                if ui.button("↻ reload").on_hover_text("re-read the funnel").clicked() {
                    self.loaded = false;
                    self.view = None;
                    self.built_for = None;
                }
                ui.separator();
                legend(ui, &theme);
            });
            self.demo_panel(ui, log);
        });

        egui::CentralPanel::default().show_inside(ui, |ui| {
            // Plan header: summary + originating idea + DAG size.
            if let Some(plan) = self.view.as_ref().and_then(|v| v.plans.iter().find(|p| p.id == sel)) {
                let edges: usize = plan.nodes.iter().map(|n| n.deps.len()).sum();
                ui.horizontal(|ui| {
                    ui.strong(&plan.summary);
                    ui.weak(format!("Β· {} nodes, {} deps", plan.nodes.len(), edges));
                });
                if !plan.idea_text.is_empty() {
                    ui.label(
                        egui::RichText::new(format!("πŸ’‘ {}", plan.idea_text))
                            .italics()
                            .size(11.0)
                            .color(theme.text_dim),
                    );
                }
                ui.add_space(2.0);
            }
            // The DAG. egui-snarl owns pan/zoom/drag; topology is preset by
            // the layered insert positions.
            let mut viewer = FunnelViewer { theme };
            self.snarl.show(&mut viewer, &self.style, "funnel_snarl_canvas", ui);
        });
    }

    /// E1 demo control strip: `🌱 Run demo` (+ size) and a two-click
    /// confirm-guarded `πŸ—‘ Nuke disk`. Local mode only β€” in remote mode the
    /// buttons are disabled with an explanatory tooltip (the warehouse the demo
    /// writes to lives on the server, not the viz host).
    fn demo_panel(&mut self, ui: &mut egui::Ui, log: &super::action_log::ActionLog) {
        let theme = self.theme;
        let root = self.local_root();
        // `NORNIR_FUNNEL_DEMO_DISABLED` lets the headless crash-hunt click the
        // demo buttons without performing real disk/warehouse I/O on the live
        // workspaces β€” the buttons render + respond but are disabled.
        let demo_disabled = std::env::var_os("NORNIR_FUNNEL_DEMO_DISABLED").is_some();
        let is_local = root.is_some();
        let enabled = is_local && !demo_disabled;
        ui.horizontal_wrapped(|ui| {
            ui.label("demo:");
            ui.add_enabled_ui(enabled, |ui| {
                let run = ui
                    .button("🌱 Run demo")
                    .on_hover_text("Inject a fake dep-graph plan into the funnel + create fake repos on disk")
                    .on_disabled_hover_text("Demo is local-mode only (remote warehouse lives on the server)");
                ui.add(
                    egui::DragValue::new(&mut self.demo_size)
                        .range(1..=64)
                        .prefix("size "),
                );
                if run.clicked() {
                    if let Some(root) = &root {
                        match crate::funnel::demo::run_demo(root, self.demo_size) {
                            Ok(m) => {
                                let msg = format!(
                                    "🌱 demo ran: {} fake repo(s), funnel DAG injected",
                                    m.repos.len()
                                );
                                log.push(super::action_log::Kind::Click, msg.clone());
                                self.demo_status = Some(msg);
                                self.invalidate();
                            }
                            Err(e) => {
                                let msg = format!("demo failed: {e:#}");
                                log.push(super::action_log::Kind::Error, msg.clone());
                                self.demo_status = Some(msg);
                            }
                        }
                    }
                    self.nuke_confirm_pending = false;
                }

                ui.separator();

                // Two-click nuke guard: first click arms, second click fires.
                if self.nuke_confirm_pending {
                    let confirm = ui
                        .button(egui::RichText::new("⚠ Confirm nuke (disk only)").color(RED))
                        .on_hover_text("Click again to delete the fake repos on disk");
                    let cancel = ui.button("βœ– cancel").clicked();
                    if confirm.clicked() {
                        if let Some(root) = &root {
                            match crate::funnel::demo::nuke_disk(root) {
                                Ok(removed) => {
                                    let msg = format!(
                                        "πŸ—‘ nuked {} fake repo(s) on disk (warehouse funnel kept)",
                                        removed.len()
                                    );
                                    log.push(super::action_log::Kind::Click, msg.clone());
                                    self.demo_status = Some(msg);
                                }
                                Err(e) => {
                                    let msg = format!("nuke failed: {e:#}");
                                    log.push(super::action_log::Kind::Error, msg.clone());
                                    self.demo_status = Some(msg);
                                }
                            }
                        }
                        self.nuke_confirm_pending = false;
                    } else if cancel {
                        self.nuke_confirm_pending = false;
                    }
                } else if ui
                    .button("πŸ—‘ Nuke disk")
                    .on_hover_text("Delete the fake demo repos on disk (two-click confirm)")
                    .on_disabled_hover_text("Demo is local-mode only")
                    .clicked()
                {
                    self.nuke_confirm_pending = true;
                }
            });
        });
        ui.label(
            egui::RichText::new("Deletes fake repos on disk only β€” warehouse funnel data is kept.")
                .size(10.0)
                .color(theme.text_dim),
        );
        if let Some(status) = &self.demo_status {
            ui.label(egui::RichText::new(status).size(10.0).color(theme.text_dim));
        }
    }

    /// LAW 6 β€” the Funnel tab's readable state for `app.rs::state_json()`:
    /// selected plan, per-plan node/edge/ready counts, and a `demo` block
    /// (size, confirm-pending, last status). "See what the user sees" as data.
    pub fn state_json(&self) -> serde_json::Value {
        let plans: Vec<serde_json::Value> = self
            .view
            .as_ref()
            .map(|v| {
                v.plans
                    .iter()
                    .map(|p| {
                        let edges: usize = p.nodes.iter().map(|n| n.deps.len()).sum();
                        let ready = p
                            .nodes
                            .iter()
                            .filter(|n| n.status == NodeStat::Ready)
                            .count();
                        serde_json::json!({
                            "id": p.id,
                            "status": p.status,
                            "nodes": p.nodes.len(),
                            "edges": edges,
                            "ready_count": ready,
                        })
                    })
                    .collect()
            })
            .unwrap_or_default();
        let is_local = matches!(self.src, Src::Local(_));
        serde_json::json!({
            "palette": self.theme.name,
            "selected_plan": self.sel_plan,
            "plan_count": plans.len(),
            "plans": plans,
            "error": self.error,
            "demo": {
                "available": is_local,
                "size": self.demo_size,
                "confirm_pending": self.nuke_confirm_pending,
                "status": self.demo_status,
            },
        })
    }

    /// Test hook: run the demo exactly as the `🌱 Run demo` button does (inject
    /// the funnel DAG + materialise fake repos), then invalidate so the next
    /// `state_json`/`draw` re-reads the warehouse. Local mode only.
    pub fn run_demo_for_test(&mut self, size: usize) -> anyhow::Result<()> {
        let root = self.local_root().ok_or_else(|| anyhow::anyhow!("not local"))?;
        self.demo_size = size;
        crate::funnel::demo::run_demo(&root, size)?;
        // Re-read the warehouse now so the caller can assert state_json() at
        // once (mirrors what the next draw frame would do after invalidate()).
        self.reload_now();
        Ok(())
    }

    /// Re-read the funnel view from its source immediately (no draw frame
    /// needed). Used by the test hooks so `state_json()` reflects fresh data.
    fn reload_now(&mut self) {
        self.built_for = None;
        match self.load_view() {
            Ok(v) => {
                if self.sel_plan.is_none() {
                    self.sel_plan = v.plans.first().map(|p| p.id.clone());
                }
                self.view = Some(v);
                self.loaded = true;
                self.error = None;
            }
            Err(e) => {
                self.error = Some(e);
            }
        }
    }

    /// Test hook: first click on `πŸ—‘ Nuke disk` (arms the two-click guard).
    pub fn arm_nuke_for_test(&mut self) {
        self.nuke_confirm_pending = true;
    }

    /// Test hook: the confirming second click β€” actually nukes the disk repos.
    pub fn confirm_nuke_for_test(&mut self) -> anyhow::Result<Vec<std::path::PathBuf>> {
        let root = self.local_root().ok_or_else(|| anyhow::anyhow!("not local"))?;
        let removed = crate::funnel::demo::nuke_disk(&root)?;
        self.nuke_confirm_pending = false;
        Ok(removed)
    }

    /// Test hook: whether the two-click nuke guard is currently armed.
    pub fn nuke_confirm_pending(&self) -> bool {
        self.nuke_confirm_pending
    }

    /// Test hook: re-read the funnel from the warehouse now (so `state_json()`
    /// immediately reflects it).
    pub fn reload_for_test(&mut self) {
        self.reload_now();
    }
}

/// Longest-path layering (Kahn): `layer[n] = 0` for roots, else
/// `1 + max(layer[dep])`. Returns a layer per node, index-aligned with
/// `plan.nodes`. A cycle (shouldn't happen β€” `apply` rejects them) leaves the
/// unreached nodes at layer 0, which is still drawable.
fn topo_layers(plan: &PlanView) -> Vec<usize> {
    let n = plan.nodes.len();
    let idx: HashMap<&str, usize> =
        plan.nodes.iter().enumerate().map(|(i, nd)| (nd.id.as_str(), i)).collect();

    // dependents[u] = nodes that depend on u; indeg[v] = #known deps of v.
    let mut dependents: Vec<Vec<usize>> = vec![Vec::new(); n];
    let mut indeg = vec![0usize; n];
    for (v, node) in plan.nodes.iter().enumerate() {
        for dep in &node.deps {
            if let Some(&u) = idx.get(dep.as_str()) {
                dependents[u].push(v);
                indeg[v] += 1;
            }
        }
    }

    let mut layer = vec![0usize; n];
    let mut queue: VecDeque<usize> = (0..n).filter(|&i| indeg[i] == 0).collect();
    while let Some(u) = queue.pop_front() {
        for &v in &dependents[u] {
            layer[v] = layer[v].max(layer[u] + 1);
            indeg[v] -= 1;
            if indeg[v] == 0 {
                queue.push_back(v);
            }
        }
    }
    layer
}

/// Lay the plan out as a left→right topological DAG and wire its edges.
fn build_snarl(plan: &PlanView) -> Snarl<FunnelNode> {
    let mut snarl = Snarl::new();
    let layers = topo_layers(plan);

    // Group node indices by layer, preserving id order within a layer.
    let mut by_layer: BTreeMap<usize, Vec<usize>> = BTreeMap::new();
    for (i, &l) in layers.iter().enumerate() {
        by_layer.entry(l).or_default().push(i);
    }
    let max_rows = by_layer.values().map(|v| v.len()).max().unwrap_or(1) as f32;
    let mid = (max_rows - 1.0) * 0.5 * Y_SPACING;

    let mut sid: HashMap<String, NodeId> = HashMap::new();
    for (layer, members) in &by_layer {
        let count = members.len() as f32;
        for (row, &ni) in members.iter().enumerate() {
            let node = &plan.nodes[ni];
            let x = 40.0 + *layer as f32 * X_SPACING;
            // Center each column around the canvas mid-line.
            let y = 40.0 + mid + (row as f32 - (count - 1.0) * 0.5) * Y_SPACING;
            let id = snarl.insert_node(
                Pos2::new(x, y),
                FunnelNode {
                    id: node.id.clone(),
                    kind: node.kind.clone(),
                    title: node.title.clone(),
                    status: node.status,
                    targets: node.targets.clone(),
                },
            );
            sid.insert(node.id.clone(), id);
        }
    }

    // Edge dep -> node: wire dep's single output into node's single input.
    for node in &plan.nodes {
        let Some(&to) = sid.get(&node.id) else { continue };
        for dep in &node.deps {
            if let Some(&from) = sid.get(dep) {
                snarl.connect(OutPinId { node: from, output: 0 }, InPinId { node: to, input: 0 });
            }
        }
    }
    snarl
}

/// Status legend row.
fn legend(ui: &mut egui::Ui, theme: &Theme) {
    for st in [
        NodeStat::Pending,
        NodeStat::Ready,
        NodeStat::InProgress,
        NodeStat::Done,
        NodeStat::Blocked,
        NodeStat::Failed,
    ] {
        ui.colored_label(st.color_themed(theme), st.glyph());
        ui.weak(st.label());
        ui.add_space(4.0);
    }
}

/// egui-snarl renderer for funnel nodes. One input pin (incoming deps) and one
/// output pin (dependents); both tinted by status so the wire colours read as
/// progress. Read-only: editing is the CLI/MCP's job, so `connect`/`disconnect`
/// are left as no-ops (the default trait impls would mutate the graph).
struct FunnelViewer {
    theme: Theme,
}

impl SnarlViewer<FunnelNode> for FunnelViewer {
    fn title(&mut self, node: &FunnelNode) -> String {
        node.id.clone()
    }

    fn inputs(&mut self, _node: &FunnelNode) -> usize {
        1
    }
    fn outputs(&mut self, _node: &FunnelNode) -> usize {
        1
    }

    fn show_header(
        &mut self,
        node: NodeId,
        _inputs: &[InPin],
        _outputs: &[OutPin],
        ui: &mut egui::Ui,
        snarl: &mut Snarl<FunnelNode>,
    ) {
        let n = &snarl[node];
        ui.horizontal(|ui| {
            ui.colored_label(n.status.color_themed(&self.theme), n.status.glyph());
            ui.strong(&n.id);
            if !n.kind.is_empty() {
                ui.label(egui::RichText::new(&n.kind).monospace().size(11.0).color(self.theme.text_dim));
            }
        });
    }

    fn has_body(&mut self, node: &FunnelNode) -> bool {
        !node.title.is_empty() || !node.targets.is_empty()
    }

    fn show_body(
        &mut self,
        node: NodeId,
        _inputs: &[InPin],
        _outputs: &[OutPin],
        ui: &mut egui::Ui,
        snarl: &mut Snarl<FunnelNode>,
    ) {
        let n = &snarl[node];
        ui.vertical(|ui| {
            ui.set_max_width(190.0);
            if !n.title.is_empty() {
                ui.label(egui::RichText::new(&n.title).size(11.0));
            }
            if !n.targets.is_empty() {
                ui.label(
                    egui::RichText::new(format!("β†’ {}", n.targets.join(", ")))
                        .size(10.0)
                        .color(self.theme.text_dim),
                );
            }
            ui.colored_label(n.status.color_themed(&self.theme), n.status.label());
        });
    }

    fn show_input(
        &mut self,
        pin: &InPin,
        _ui: &mut egui::Ui,
        snarl: &mut Snarl<FunnelNode>,
    ) -> impl egui_snarl::ui::SnarlPin + 'static {
        let color = snarl.get_node(pin.id.node).map(|n| n.status.color_themed(&self.theme)).unwrap_or(self.theme.text_dim);
        PinInfo::circle().with_fill(color)
    }

    fn show_output(
        &mut self,
        pin: &OutPin,
        _ui: &mut egui::Ui,
        snarl: &mut Snarl<FunnelNode>,
    ) -> impl egui_snarl::ui::SnarlPin + 'static {
        let color = snarl.get_node(pin.id.node).map(|n| n.status.color_themed(&self.theme)).unwrap_or(self.theme.text_dim);
        PinInfo::triangle().with_fill(color)
    }

    // Read-only canvas: ignore user-drawn wires.
    fn connect(&mut self, _from: &OutPin, _to: &InPin, _snarl: &mut Snarl<FunnelNode>) {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use super::super::funnel_view::NodeView;

    fn node(id: &str, deps: &[&str]) -> NodeView {
        NodeView {
            id: id.into(),
            kind: "test".into(),
            title: String::new(),
            status: NodeStat::Pending,
            targets: Vec::new(),
            deps: deps.iter().map(|s| s.to_string()).collect(),
        }
    }

    /// Longest-path layering: a dependent sits one rank past its deepest dep.
    #[test]
    fn topo_layers_longest_path() {
        // n1,n2 roots; n3←n1; n4←n2; n5←{n3,n2} (so n5 = max(1,0)+1 = 2).
        let plan = PlanView {
            id: "p-001".into(),
            summary: String::new(),
            status: "active".into(),
            idea_text: String::new(),
            nodes: vec![
                node("n-1", &[]),
                node("n-2", &[]),
                node("n-3", &["n-1"]),
                node("n-4", &["n-2"]),
                node("n-5", &["n-3", "n-2"]),
            ],
        };
        let layers = topo_layers(&plan);
        assert_eq!(layers, vec![0, 0, 1, 1, 2]);
    }

    /// Unknown dep ids are ignored (never panic, treated as no edge).
    #[test]
    fn topo_layers_tolerates_dangling_dep() {
        let plan = PlanView {
            id: "p-002".into(),
            summary: String::new(),
            status: "draft".into(),
            idea_text: String::new(),
            nodes: vec![node("n-1", &["nope"]), node("n-2", &["n-1"])],
        };
        let layers = topo_layers(&plan);
        assert_eq!(layers, vec![0, 1]);

        // And the graph builds with the right node + wire counts.
        let snarl = build_snarl(&plan);
        assert_eq!(snarl.nodes().count(), 2);
        assert_eq!(snarl.wires().count(), 1);
    }
}