nornir 0.5.2

Companion to cargo: dependency tracking, release gating, deploy, benchmarks, and documentation assembly. Project-agnostic.
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
//! ⚒ The **Brokkr tab** — the CI/build-server, composed of five facett facets.
//!
//! A sub-view selector switches between the five brokkr facets, each a pure Elm
//! core in the `brokkr` leaf rendered here as an egui pane; every one contributes
//! a slice to `state_json` so the whole tab is drivable headless by a
//! `RobotSession` (see `tests/viz_brokkr_robot.rs`):
//!
//! - **Results** ([`dwarves::brokkr::elm::Brokkr`]) — Run buttons + run list with chips.
//! - **Tree** ([`dwarves::brokkr::facets::TreeFacet`]) — project→pipeline→stage→step chips.
//! - **DAG** ([`dwarves::brokkr::facets::DagFacet`]) — the stage/step graph via
//!   [`facett_graphview::MetroView`] (stations lit by run status).
//! - **Agents** ([`dwarves::brokkr::facets::AgentsFacet`]) — the agent pool (busy/idle).
//! - **Log** ([`dwarves::brokkr::facets::LogFacet`]) — the streaming step-log tail.
//!
//! Pressing **Run** (Results view) drives the pipeline through the injected
//! [`StepRunner`] seam (default [`crate::brokkr::DemoRunner`]) and folds the
//! historized result into every facet at once. The heavy cargo/bollard runner
//! backends plug in behind the same seam without touching this tab.

use std::sync::Arc;

use eframe::egui::{self};
use facett_core::Facet;
use facett_graphview::{MetroLine, MetroMap, MetroStation, MetroView, StationKind};

use ::dwarves::brokkr::PipelineDescriptor;
use ::dwarves::brokkr::dag::Dag;
use ::dwarves::brokkr::elm::{Brokkr, BrokkrEffect, BrokkrMsg};
use ::dwarves::brokkr::engine::RunRequest;
use ::dwarves::brokkr::facets::{AgentsFacet, DagFacet, LogFacet, TreeFacet};
use ::dwarves::brokkr::model::Pipeline;
use ::dwarves::brokkr::runner::StepRunner;

use super::facett_theme::Theme;
use super::facett_ui;

/// The five brokkr sub-views (facets).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BrokkrView {
    /// Run list + Run buttons.
    Results,
    /// Project→pipeline→stage→step hierarchy.
    Tree,
    /// The stage/step DAG (MetroView).
    Dag,
    /// The build-agent pool.
    Agents,
    /// The streaming step-log tail.
    Log,
    /// The pipeline BUILDER — author a `brokkr.toml` (text + click) and load it.
    Build,
}

impl BrokkrView {
    /// The exact AccessKit label the sub-view selector paints (robot click key).
    fn label(self) -> &'static str {
        match self {
            BrokkrView::Results => "Results",
            BrokkrView::Tree => "Tree",
            BrokkrView::Dag => "DAG",
            BrokkrView::Agents => "Agents",
            BrokkrView::Log => "Log",
            BrokkrView::Build => "Build",
        }
    }
    /// The `state_json["brokkr"]["view"]` name.
    fn id(self) -> &'static str {
        self.label()
    }
    const ALL: [BrokkrView; 6] = [
        BrokkrView::Results,
        BrokkrView::Tree,
        BrokkrView::Dag,
        BrokkrView::Agents,
        BrokkrView::Log,
        BrokkrView::Build,
    ];
}

/// A demo pipeline shipped with the tab so it is never blank.
const DEMO_PIPELINE: &str = r#"
[pipeline]
name = "nornir-ci"

[[pipeline.trigger]]
kind = "webhook"
events = ["push"]
branch = "main"

[[pipeline.stage]]
name = "build"
[[pipeline.stage.step]]
name = "compile"
run = { variant = "server" }
artifacts = ["target/release/nornir"]

[[pipeline.stage]]
name = "test"
[[pipeline.stage.step]]
name = "unit"
needs = ["compile"]
run = { container = { name = "rust:1.85", cmd = ["cargo", "test"] } }
report = "junit"
[[pipeline.stage.step]]
name = "lint"
needs = ["compile"]
run = { container = { name = "rust:1.85", cmd = ["cargo", "clippy"] } }

[[pipeline.stage]]
name = "ship"
[[pipeline.stage.step]]
name = "release"
needs = ["unit", "lint"]
run = { variant = "server" }
"#;

/// The never-blank fallback if the demo TOML ever fails to parse.
const FALLBACK: &str = r#"
[pipeline]
name = "brokkr"
[[pipeline.stage]]
name = "build"
[[pipeline.stage.step]]
name = "compile"
run = { variant = "server" }
"#;

/// The Brokkr tab: the five facets + the pipeline they render + the runner seam.
pub struct BrokkrTabState {
    /// The active sub-view.
    view: BrokkrView,
    /// Facet 1 — the results Elm core.
    results: Brokkr,
    /// Facet 2 — the project/pipeline/stage/step tree.
    tree: TreeFacet,
    /// Facet 3 — the stage/step DAG model.
    dag_facet: DagFacet,
    /// The MetroView that renders the DAG facet (transit lines = stages).
    metro: MetroView,
    /// Facet 4 — the agent pool.
    agents: AgentsFacet,
    /// Facet 5 — the step-log tail.
    log: LogFacet,
    /// The demo pipeline.
    pipeline: Pipeline,
    /// The pipeline's topo DAG.
    dag: Dag,
    /// The step-execution seam (default = [`crate::brokkr::DemoRunner`]).
    runner: Arc<dyn StepRunner>,
    /// Monotonic run counter for unique run ids.
    run_seq: u64,
    /// The active facett palette.
    palette: Theme,
    /// Facet 6 — the `brokkr.toml` pipeline BUILDER (author text + click → load).
    builder: facett_brokkr::PipelineBuilder,
    /// The last "Validate & Load" outcome shown under the builder.
    load_status: Option<Result<String, String>>,
}

impl Default for BrokkrTabState {
    fn default() -> Self {
        Self::from_toml(DEMO_PIPELINE, Arc::new(crate::brokkr::DemoRunner))
    }
}

impl BrokkrTabState {
    /// The tab seeded with the demo pipeline + the real (demo) runner.
    pub fn new() -> Self {
        Self::default()
    }

    /// Build the tab from a `brokkr.toml` document + an injected runner.
    pub fn from_toml(toml: &str, runner: Arc<dyn StepRunner>) -> Self {
        let desc = PipelineDescriptor::from_toml_str(toml)
            .unwrap_or_else(|_| PipelineDescriptor::from_toml_str(FALLBACK).expect("fallback parses"));
        let pipeline = desc.pipeline;
        let dag = Dag::build(&pipeline).unwrap_or_else(|_| Dag { order: Vec::new() });
        let results = Brokkr::new(vec![pipeline.name.clone()], &[]);
        let tree = TreeFacet::from_pipeline("nornir", &pipeline);
        let dag_facet = DagFacet::from_dag(&dag);
        let mut metro = MetroView::new("⚒ Brokkr DAG");
        metro.set_map(metro_map(&pipeline, &dag_facet));
        Self {
            view: BrokkrView::Results,
            results,
            tree,
            dag_facet,
            metro,
            agents: AgentsFacet::demo(),
            log: LogFacet::with_capacity(200),
            pipeline,
            dag,
            runner,
            run_seq: 0,
            palette: Theme::default(),
            builder: facett_brokkr::PipelineBuilder::from_toml_str("brokkr.toml", toml),
            load_status: None,
        }
    }

    /// Re-parse a `brokkr.toml` document (authored in the Build sub-view) with
    /// brokkr's REAL descriptor parser + validation and, on success, adopt it as
    /// the tab's live pipeline — Results / Tree / DAG all re-render the new
    /// pipeline. On a parse/validation failure the current pipeline is untouched
    /// and the error is returned for display. The runner + palette are preserved.
    pub fn apply_toml(&mut self, toml: &str) -> Result<String, String> {
        let desc = PipelineDescriptor::from_toml_str(toml).map_err(|e| format!("parse: {e}"))?;
        desc.validate().map_err(|e| format!("invalid: {e}"))?;
        let pipeline = desc.pipeline;
        let dag = Dag::build(&pipeline).map_err(|e| format!("dag: {e}"))?;
        self.results = Brokkr::new(vec![pipeline.name.clone()], &[]);
        self.tree = TreeFacet::from_pipeline("nornir", &pipeline);
        self.dag_facet = DagFacet::from_dag(&dag);
        self.metro.set_map(metro_map(&pipeline, &self.dag_facet));
        self.log = LogFacet::with_capacity(200);
        self.run_seq = 0;
        let msg = format!(
            "loaded '{}' — {} stage(s), {} step(s)",
            pipeline.name,
            pipeline.stages.len(),
            dag.order.len()
        );
        self.pipeline = pipeline;
        self.dag = dag;
        Ok(msg)
    }

    /// Test-only: swap the step-execution runner.
    #[doc(hidden)]
    pub fn set_runner_for_test(&mut self, runner: Arc<dyn StepRunner>) {
        self.runner = runner;
    }

    /// Adopt the app-wide palette (C8).
    pub fn set_palette(&mut self, palette: Theme) {
        self.palette = palette;
    }

    /// Host/watch control: run the demo pipeline (the SAME Elm path the Results
    /// "Run …" button drives). Used by the robotui **watch** entrypoint
    /// (`examples/brokkr_watch.rs`), whose driver clicks its own recorded control
    /// row rather than the internal buttons — this lets that row light the DAG.
    pub fn run_demo(&mut self) {
        let name = self.pipeline.name.clone();
        self.dispatch(BrokkrMsg::Run(name));
    }

    /// Host/watch control: switch the active sub-view by its selector label
    /// (`"Results"`, `"Tree"`, `"DAG"`, `"Agents"`, `"Log"`). No-op on an unknown
    /// label. The watch entrypoint uses this to flip to the DAG facet so the
    /// station-lighting is visible.
    pub fn set_view_by_label(&mut self, label: &str) {
        if let Some(v) = BrokkrView::ALL.into_iter().find(|v| v.label() == label) {
            self.view = v;
        }
    }

    /// The observable state a headless test / operator reads — one slice per facet.
    pub fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "surface": "brokkr",
            "pipeline": self.pipeline.name,
            "pipelines": self.results.state().pipelines,
            "stages": self.pipeline.stages.len(),
            "steps": self.dag.order.len(),
            "view": self.view.id(),
            "green_count": self.results.green_count(),
            // The results facet's Elm model (back-compat key for the run list).
            "model": self.results.state_json(),
            // One slice per facet.
            "results": self.results.state_json(),
            "tree": self.tree.state_json(),
            "dag": self.dag_facet.state_json(),
            "agents": self.agents.state_json(),
            "log": self.log.state_json(),
            // Facet 6 — the pipeline builder's own introspection blob.
            "build": self.builder.state_json(),
        })
    }

    /// Apply a results-facet message and run its effects.
    fn dispatch(&mut self, msg: BrokkrMsg) {
        let effects = self.results.update(msg);
        for effect in effects {
            match effect {
                BrokkrEffect::RunPipeline(name) => self.run_pipeline(&name),
            }
        }
    }

    /// Run the named pipeline synchronously through the seam and fold the result
    /// into every facet (results/tree/dag/log), assigning + releasing an agent.
    fn run_pipeline(&mut self, name: &str) {
        if name != self.pipeline.name {
            return;
        }
        self.run_seq += 1;
        let run_id = format!("run-{}", self.run_seq);

        // Pick a capable idle agent for the run (agent-status transition).
        let agent_name = self
            .agents
            .pool
            .pick(&["cargo".to_string()])
            .map(|a| a.name.clone());
        if let Some(a) = &agent_name {
            self.agents.set_busy(a, &run_id);
        }

        let req = RunRequest {
            project: "nornir".to_string(),
            trigger: "manual".to_string(),
            sha: None,
            matrix: Default::default(),
            branch: Some("main".to_string()),
            event: Some("push".to_string()),
        };
        if let Ok(report) =
            ::dwarves::brokkr::run_pipeline(&self.pipeline, &self.dag, self.runner.as_ref(), &req, &run_id)
        {
            self.tree.apply_run(&report);
            self.dag_facet.apply_run(&report);
            self.log.apply_run(&report);
            self.metro.set_map(metro_map(&self.pipeline, &self.dag_facet));
            self.results.update(BrokkrMsg::RunFinished(report.run));
        }

        // The run is synchronous, so release the agent back to idle.
        if let Some(a) = &agent_name {
            self.agents.set_idle(a);
        }
    }

    /// Draw the tab.
    pub fn draw(&mut self, ui: &mut egui::Ui) {
        ui.push_id("Brokkr", |ui| {
            ui.heading("⚒ Brokkr — CI / build pipelines");
            ui.label(format!(
                "Pipeline '{}' — {} stage(s), {} step(s).",
                self.pipeline.name,
                self.pipeline.stages.len(),
                self.dag.order.len()
            ));

            // ── Sub-view selector (facet switcher) ──────────────────────────
            ui.horizontal(|ui| {
                for v in BrokkrView::ALL {
                    ui.selectable_value(&mut self.view, v, v.label());
                }
            });
            ui.separator();

            match self.view {
                BrokkrView::Results => self.draw_results(ui),
                BrokkrView::Tree => self.draw_tree(ui),
                BrokkrView::Dag => self.draw_dag(ui),
                BrokkrView::Agents => self.draw_agents(ui),
                BrokkrView::Log => self.draw_log(ui),
                BrokkrView::Build => self.draw_build(ui),
            }
        });
    }

    /// The pipeline BUILDER sub-view: the embedded `facett_brokkr` builder (author
    /// a `brokkr.toml` by text or click, with a DAG preview) plus a
    /// "✓ Validate & Load" button that parses the emitted TOML with brokkr's REAL
    /// descriptor parser and adopts it as the tab's live pipeline.
    fn draw_build(&mut self, ui: &mut egui::Ui) {
        ui.label("Author a brokkr.toml here — by raw text or by click — then load it as the live pipeline.");
        ui.horizontal(|ui| {
            if ui.button("✓ Validate & Load").clicked() {
                let toml = self.builder.pipeline_toml();
                self.load_status = Some(self.apply_toml(&toml));
            }
            match &self.load_status {
                Some(Ok(msg)) => {
                    ui.label(egui::RichText::new(format!("{msg}")).color(super::facett_theme::GREEN));
                }
                Some(Err(e)) => {
                    ui.label(egui::RichText::new(format!("{e}")).color(super::facett_theme::RED));
                }
                None => {}
            }
        });
        ui.separator();
        self.builder.ui(ui);
    }

    fn draw_results(&mut self, ui: &mut egui::Ui) {
        let theme = self.palette;
        let pipelines = self.results.state().pipelines.clone();
        let mut to_run: Option<String> = None;
        ui.horizontal(|ui| {
            for name in &pipelines {
                if ui.button(format!("Run {name}")).clicked() {
                    to_run = Some(name.clone());
                }
            }
        });
        if let Some(name) = to_run {
            self.dispatch(BrokkrMsg::Run(name));
        }

        ui.add_space(6.0);
        ui.label(egui::RichText::new("Runs").strong());
        let runs = self.results.state().runs.clone();
        if runs.is_empty() {
            ui.label("No runs yet — press a Run button to start the pipeline.");
        } else {
            egui::Grid::new("brokkr_runs").striped(true).num_columns(5).show(ui, |ui| {
                for h in ["status", "pipeline", "trigger", "steps", "duration"] {
                    ui.label(egui::RichText::new(h).strong());
                }
                ui.end_row();
                for r in &runs {
                    let (chip, color) = facett_ui::status_chip(&theme, r.status.label());
                    ui.label(egui::RichText::new(chip).color(color));
                    ui.label(&r.pipeline);
                    ui.label(&r.trigger);
                    ui.label(&r.steps);
                    ui.label(&r.duration);
                    ui.end_row();
                }
            });
        }
    }

    fn draw_tree(&mut self, ui: &mut egui::Ui) {
        let theme = self.palette;
        ui.label(egui::RichText::new(format!("{} / {}", self.tree.project, self.tree.pipeline)).strong());
        for stage in &self.tree.stages {
            ui.label(egui::RichText::new(format!("{}", stage.name)).strong());
            for step in &stage.steps {
                let (chip, color) = facett_ui::status_chip(&theme, &step.status);
                ui.horizontal(|ui| {
                    ui.add_space(16.0);
                    ui.label(egui::RichText::new(chip).color(color));
                    ui.label(&step.name);
                });
            }
        }
    }

    fn draw_dag(&mut self, ui: &mut egui::Ui) {
        ui.label(format!(
            "{} node(s), {} edge(s) — {}",
            self.dag_facet.nodes.len(),
            self.dag_facet.edges.len(),
            if self.dag_facet.all_green() { "all green ✓" } else { "not yet all green" }
        ));
        ui.separator();
        Facet::ui(&mut self.metro, ui);
    }

    fn draw_agents(&mut self, ui: &mut egui::Ui) {
        let theme = self.palette;
        ui.label(format!("{} idle, {} busy", self.agents.idle_count(), self.agents.busy_count()));
        let mut toggle: Option<String> = None;
        egui::Grid::new("brokkr_agents").striped(true).num_columns(4).show(ui, |ui| {
            for h in ["agent", "tags", "state", ""] {
                ui.label(egui::RichText::new(h).strong());
            }
            ui.end_row();
            for a in &self.agents.pool.agents {
                let state = if a.busy { "busy" } else { "idle" };
                let (chip, color) = facett_ui::status_chip(&theme, if a.busy { "running" } else { "passed" });
                ui.label(&a.name);
                ui.label(a.tags.iter().cloned().collect::<Vec<_>>().join(", "));
                ui.horizontal(|ui| {
                    ui.label(egui::RichText::new(chip).color(color));
                    ui.label(state);
                });
                if ui.button(format!("Toggle {}", a.name)).clicked() {
                    toggle = Some(a.name.clone());
                }
                ui.end_row();
            }
        });
        if let Some(name) = toggle {
            self.agents.toggle(&name);
        }
    }

    fn draw_log(&mut self, ui: &mut egui::Ui) {
        ui.label(format!("{} line(s)", self.log.count()));
        ui.separator();
        egui::ScrollArea::vertical().max_height(360.0).show(ui, |ui| {
            for line in self.log.lines() {
                let red = line.contains("[failed]");
                let mut txt = egui::RichText::new(line).monospace();
                if red {
                    txt = txt.color(super::facett_theme::RED);
                }
                ui.label(txt);
            }
        });
    }
}

/// Build a [`MetroMap`] from the DAG facet: one transit line per stage, its
/// stations the stage's steps, each station green iff its step passed.
fn metro_map(pipeline: &Pipeline, dag: &DagFacet) -> MetroMap {
    let status_of = |step: &str| {
        dag.nodes.iter().find(|n| n.step == step).map(|n| n.status.as_str()).unwrap_or("pending")
    };
    let mut lines = Vec::new();
    for stage in &pipeline.stages {
        let steps: Vec<_> = stage.steps.iter().collect();
        if steps.is_empty() {
            continue;
        }
        let last = steps.len() - 1;
        let stations: Vec<MetroStation> = steps
            .iter()
            .enumerate()
            .map(|(i, st)| {
                let kind = if i == 0 {
                    StationKind::Start
                } else if i == last {
                    StationKind::Terminus
                } else {
                    StationKind::Emitter
                };
                let green = status_of(&st.name) == "passed";
                MetroStation::new(
                    format!("{}::{}", stage.name, st.name),
                    st.name.clone(),
                    kind,
                    green,
                )
            })
            .collect();
        lines.push(MetroLine::new(stage.name.clone(), stage.name.clone(), stations));
    }
    MetroMap::new(lines)
}