nornir 0.4.6

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
//! ๐Ÿ—‚ **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, Color32, Pos2};
use egui_snarl::ui::{PinInfo, SnarlStyle, SnarlViewer};
use egui_snarl::{InPin, InPinId, NodeId, OutPin, OutPinId, Snarl};

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,
}

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(),
        }
    }

    /// 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();
    }

    fn load_view(&self) -> Result<FunnelView, String> {
        match &self.src {
            Src::Local(root) => crate::funnel::Store::open(root)
                .map(|store| 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) {
        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) => self.error = Some(e),
        }
    }

    pub fn draw(&mut self, ui: &mut egui::Ui) {
        self.ensure_loaded();

        if let Some(err) = self.error.clone() {
            ui.colored_label(Color32::RED, err);
            return;
        }
        let Some(view) = self.view.as_ref() else {
            ui.label("loading funnelโ€ฆ");
            return;
        };
        if view.plans.is_empty() {
            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 โ€ฆ");
            });
            return;
        }

        // 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_source("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);
            });
        });

        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(Color32::from_gray(160)),
                    );
                }
                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;
            self.snarl.show(&mut viewer, &self.style, "funnel_snarl_canvas", ui);
        });
    }
}

/// 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) {
    for st in [
        NodeStat::Pending,
        NodeStat::Ready,
        NodeStat::InProgress,
        NodeStat::Done,
        NodeStat::Blocked,
        NodeStat::Failed,
    ] {
        ui.colored_label(st.color(), 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;

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,
        _scale: f32,
        snarl: &mut Snarl<FunnelNode>,
    ) {
        let n = &snarl[node];
        ui.horizontal(|ui| {
            ui.colored_label(n.status.color(), n.status.glyph());
            ui.strong(&n.id);
            if !n.kind.is_empty() {
                ui.label(egui::RichText::new(&n.kind).monospace().size(11.0).color(Color32::from_gray(170)));
            }
        });
    }

    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,
        _scale: f32,
        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(Color32::from_gray(150)),
                );
            }
            ui.colored_label(n.status.color(), n.status.label());
        });
    }

    fn show_input(
        &mut self,
        pin: &InPin,
        _ui: &mut egui::Ui,
        _scale: f32,
        snarl: &mut Snarl<FunnelNode>,
    ) -> PinInfo {
        let color = snarl.get_node(pin.id.node).map(|n| n.status.color()).unwrap_or(Color32::GRAY);
        PinInfo::circle().with_fill(color)
    }

    fn show_output(
        &mut self,
        pin: &OutPin,
        _ui: &mut egui::Ui,
        _scale: f32,
        snarl: &mut Snarl<FunnelNode>,
    ) -> PinInfo {
        let color = snarl.get_node(pin.id.node).map(|n| n.status.color()).unwrap_or(Color32::GRAY);
        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);
    }
}