holger-ui 0.1.4

Operator/admin UI for holger over the HolgerObject core API — egui via facett, embedded (LocalHolger, direct core calls) or remote (RemoteHolger gRPC).
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
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
//! holger-ui **real robot-UI** cell — drives the *actual egui app* through
//! `egui_kittest` (AccessKit clicks) with the reusable `nornir-robotui`
//! framework, and asserts the app's observable `state_json()` after each click.
//! Each `(action → expected)` step becomes a `nornir-testmatrix` row, so a robot
//! run auto-clicks the holger UI and **fills the nornir test matrix** — nornir
//! sees holger's UI tests.
//!
//! Gated behind `gui` (the egui app only compiles there). Run:
//! `cargo test -p holger-ui --features gui --test robot_ui_app`.
//!
//! LAW 1 (inject+assert) + LAW 2 (no empty data): the app is seeded with REAL
//! repositories, so the Repos count and the 3D graph carry populated data — an
//! empty graph would go RED, not green.
#![cfg(feature = "gui")]

use std::sync::Arc;

use egui_kittest::Harness;
use holger_ui::app::HolgerUiApp;
use holger_ui::data::UiData;
use nornir_robotui::{status, Action, Assert, Observable, RobotSession, Scenario, Step};
use serde_json::{json, Value};
use server_lib::exposed::fast_routes::FastRoutes;
use server_lib::LocalHolger;
use traits::{
    ArchiveInfo, ArtifactEntry, ArtifactFormat, ArtifactId, HolgerObject, RepositoryBackendTrait,
};

/// A present-but-empty repository backend — enough that the UI lists real repos
/// (so `repo_count > 0`, LAW 2) without depending on any ecosystem's on-disk
/// format. The surface under test is the egui app + its `state_json`.
struct StubRepo {
    name: &'static str,
    writable: bool,
}

impl StubRepo {
    /// A read-only stub repo.
    fn ro(name: &'static str) -> Self {
        Self { name, writable: false }
    }
    /// A writable stub repo (so the server's derived profile is dynamic).
    fn rw(name: &'static str) -> Self {
        Self { name, writable: true }
    }
}

impl RepositoryBackendTrait for StubRepo {
    fn name(&self) -> &str {
        self.name
    }
    fn format(&self) -> ArtifactFormat {
        ArtifactFormat::Rust
    }
    fn is_writable(&self) -> bool {
        self.writable
    }
    fn fetch(&self, _id: &ArtifactId) -> anyhow::Result<Option<Vec<u8>>> {
        Ok(None)
    }
    fn put(&self, _id: &ArtifactId, _data: &[u8]) -> anyhow::Result<()> {
        Ok(())
    }
    fn list(&self, _name_filter: Option<&str>, _limit: usize) -> anyhow::Result<Vec<ArtifactEntry>> {
        Ok(Vec::new())
    }
    fn archive_files(&self, _prefix: Option<&str>) -> anyhow::Result<Vec<String>> {
        Ok(Vec::new())
    }
    fn archive_info(&self) -> anyhow::Result<ArchiveInfo> {
        Ok(ArchiveInfo {
            file_count: 0,
            total_uncompressed_bytes: 0,
            archive_path: self.name.to_string(),
        })
    }
    fn handle_http2_request(
        &self,
        _method: &str,
        _suburl: &str,
        _body: &[u8],
    ) -> anyhow::Result<(u16, Vec<(String, String)>, Vec<u8>)> {
        Ok((404, Vec::new(), Vec::new()))
    }
}

/// A data-returning repository backend: real artifact listings, an archive with
/// stats + files, and a `fetch` that resolves `serde 1.0.0`. Writable so the
/// derived profile is dynamic. `vuln` swaps in a corpus carrying the demo
/// openssl advisory so the security scan blocks.
struct DataRepo {
    name: &'static str,
    vuln: bool,
}

impl RepositoryBackendTrait for DataRepo {
    fn name(&self) -> &str {
        self.name
    }
    fn format(&self) -> ArtifactFormat {
        ArtifactFormat::Rust
    }
    fn is_writable(&self) -> bool {
        true
    }
    fn fetch(&self, id: &ArtifactId) -> anyhow::Result<Option<Vec<u8>>> {
        if id.name == "serde" && id.version == "1.0.0" {
            Ok(Some(b"SERDE_CRATE_BYTES".to_vec()))
        } else {
            Ok(None)
        }
    }
    fn put(&self, _id: &ArtifactId, _data: &[u8]) -> anyhow::Result<()> {
        Ok(())
    }
    fn list(&self, name_filter: Option<&str>, _limit: usize) -> anyhow::Result<Vec<ArtifactEntry>> {
        let all = vec![
            ArtifactEntry {
                id: ArtifactId { namespace: None, name: "serde".into(), version: "1.0.0".into() },
                size_bytes: 17,
                content_type: "application/octet-stream".into(),
            },
            ArtifactEntry {
                id: ArtifactId { namespace: None, name: "tokio".into(), version: "1.2.0".into() },
                size_bytes: 9,
                content_type: "application/octet-stream".into(),
            },
        ];
        Ok(match name_filter {
            Some(f) => all.into_iter().filter(|e| e.id.name.contains(f)).collect(),
            None => all,
        })
    }
    fn archive_files(&self, prefix: Option<&str>) -> anyhow::Result<Vec<String>> {
        let files = if self.vuln {
            vec![
                "crates/serde-1.0.0.crate".to_string(),
                "crates/openssl-0.10.55.crate".to_string(),
                "index/config.json".to_string(),
            ]
        } else {
            vec![
                "crates/serde-1.0.0.crate".to_string(),
                "crates/tokio-1.2.0.crate".to_string(),
                "index/config.json".to_string(),
            ]
        };
        Ok(match prefix {
            Some(p) => files.into_iter().filter(|f| f.starts_with(p)).collect(),
            None => files,
        })
    }
    fn archive_info(&self) -> anyhow::Result<ArchiveInfo> {
        Ok(ArchiveInfo {
            file_count: 3,
            total_uncompressed_bytes: 4242,
            archive_path: self.name.to_string(),
        })
    }
    fn handle_http2_request(
        &self,
        _method: &str,
        _suburl: &str,
        _body: &[u8],
    ) -> anyhow::Result<(u16, Vec<(String, String)>, Vec<u8>)> {
        Ok((404, Vec::new(), Vec::new()))
    }
}

/// An app over a single data-returning repo (Browse/Archive/Artifact/Security
/// have real data to render).
fn data_app(vuln: bool) -> HolgerUiApp {
    let repos: Vec<(String, Arc<dyn RepositoryBackendTrait>)> =
        vec![("rust-data".to_string(), Arc::new(DataRepo { name: "rust-data", vuln }))];
    app_over(repos)
}

/// A real holger-ui app over a LocalHolger seeded with three repositories, with
/// the splash skipped so the robot starts on the tabs.
fn seeded_app() -> HolgerUiApp {
    // rust-dev is writable so the server's derived profile is *dynamic* (the
    // default the tool-driving tests exercise); cache + sparring are read-only
    // (so the Upload / static-mode tests have read-only repos to select).
    let repos: Vec<(String, Arc<dyn RepositoryBackendTrait>)> = vec![
        ("rust-dev".to_string(), Arc::new(StubRepo::rw("rust-dev"))),
        ("cache".to_string(), Arc::new(StubRepo::ro("cache"))),
        ("sparring".to_string(), Arc::new(StubRepo::ro("sparring"))),
    ];
    app_over(repos)
}

/// Build a real holger-ui app over a `LocalHolger` backed by the given repos,
/// with the splash skipped so the robot starts on the tabs. The server-derived
/// profile (read-only iff no repo is writable) drives the initial static mode.
fn app_over(repos: Vec<(String, Arc<dyn RepositoryBackendTrait>)>) -> HolgerUiApp {
    let holger: Arc<dyn HolgerObject> = Arc::new(LocalHolger::new(FastRoutes::new(repos)));
    let data = UiData::new(holger).expect("runtime");
    let mut app = HolgerUiApp::new(data);
    app.skip_splash();
    app
}

/// Newtype so we can implement the foreign `Observable` trait (orphan rule); a
/// one-line delegate to the app's own `state_json()`.
struct UiApp(HolgerUiApp);

impl Observable for UiApp {
    fn state_json(&self) -> Value {
        self.0.state_json()
    }
}

/// The robot auto-clicks the holger UI: Graph tab (3D graph builds from real
/// repos), Tools menu (selects the Skíðblaðnir deploy function), and the static
/// "rigged for silent running" toggle (writes disabled) — every step asserted
/// against the live `state_json` and emitted as a matrix row.
#[test]
fn robot_drives_tabs_tools_and_static_mode() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    let scenario = Scenario::new("holger-ui-robot")
        .step(
            Step::new("repos populated (LAW2: no empty data)").assert(Assert::State {
                pointer: "/repo_count".into(),
                expected: json!(3),
            }),
        )
        .step(
            Step::new("click Graph → tab == graph")
                .action(Action::ClickLabel("Graph".into()))
                .assert(Assert::State {
                    pointer: "/tab".into(),
                    expected: json!("graph"),
                }),
        )
        .step(
            Step::new("3D graph built from real repos (LAW2)").assert(Assert::State {
                pointer: "/graph_built".into(),
                expected: json!(true),
            }),
        )
        .step(Step::new("graph drew widgets").assert(Assert::Drew))
        .step(
            Step::new("click Tools → tab == tools")
                .action(Action::ClickLabel("Tools".into()))
                .assert(Assert::State {
                    pointer: "/tab".into(),
                    expected: json!("tools"),
                }),
        )
        .step(
            Step::new("select Deploy (Skíðblaðnir) → tool == deploy")
                .action(Action::ClickLabel("4 · deploy · Skíðblaðnir".into()))
                .assert(Assert::State {
                    pointer: "/tool".into(),
                    expected: json!("deploy"),
                }),
        )
        .step(
            Step::new("engage static silent-running → static_mode == true")
                .action(Action::ClickLabel("⚓ static".into()))
                .assert(Assert::State {
                    pointer: "/static_mode".into(),
                    expected: json!(true),
                }),
        )
        .step(
            Step::new("writes disabled in static → write_enabled == false").assert(Assert::State {
                pointer: "/write_enabled".into(),
                expected: json!(false),
            }),
        );

    // Run the scenario: each step is driven on the real app and becomes a matrix row.
    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 8, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(
            r.status,
            status::PASS,
            "robot step {:?} should pass; message: {}",
            r.test_name,
            r.message
        );
    }
}

/// The robot drives the NEW **Lineage** tab (the live proxy-cache-filling facet):
/// open it (3D fill renders + the demo backlog begins dripping through the live
/// feed), assert it drew, toggle to the time-helix companion and back, and assert
/// the render mode each step — every assertion against the live `state_json`, and
/// the growing lineage graph observed as DATA (`/lineage/total_events` climbs as
/// the cache fills).
#[test]
fn robot_drives_lineage_tab() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    let scenario = Scenario::new("holger-ui-lineage-robot")
        .step(
            Step::new("open Lineage → tab == lineage")
                .action(Action::ClickLabel("Lineage".into()))
                .assert(Assert::State { pointer: "/tab".into(), expected: json!("lineage") }),
        )
        .step(
            Step::new("default mode is the rotating 3D fill")
                .assert(Assert::State { pointer: "/lineage_mode".into(), expected: json!("graph3d") }),
        )
        .step(Step::new("3D cache-fill graph drew").assert(Assert::Drew))
        .step(
            Step::new("toggle time-helix companion → mode == helix")
                .action(Action::ClickLabel("🌀 time helix".into()))
                .assert(Assert::State { pointer: "/lineage_mode".into(), expected: json!("helix") }),
        )
        .step(Step::new("time-helix drew").assert(Assert::Drew))
        .step(
            Step::new("back to 3D fill → mode == graph3d")
                .action(Action::ClickLabel("◉ 3D fill".into()))
                .assert(Assert::State { pointer: "/lineage_mode".into(), expected: json!("graph3d") }),
        )
        .step(Step::new("cache kept filling (drew again)").assert(Assert::Drew));

    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 7, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(r.status, status::PASS, "robot step {:?} should pass; message: {}", r.test_name, r.message);
    }

    // The cache filled as the tab ran: the live feed drip grew the lineage graph.
    let filled = robot.app().0.state_json();
    let events = filled["lineage"]["total_events"].as_u64().unwrap_or(0);
    let artifacts = filled["lineage"]["nodes"]
        .as_array()
        .map(|a| a.iter().filter(|n| n["kind"] == "artifact").count())
        .unwrap_or(0);
    assert!(events >= 1, "the live cache-fill produced arrivals: total_events={events}");
    assert!(artifacts >= 1, "cached artifact nodes popped in: {artifacts}");
}

/// The robot drives the NEW operator Tools panes wired this round: Tool #1
/// holger-ds (scale slider), Tool #3 Móðguðr security (scan the selected repo →
/// a real Pass verdict over an empty corpus), and Tool #5 airgap populate (the
/// 5th menu item). Every step asserts the live `state_json` — the panes as DATA.
#[test]
fn robot_drives_tools_1_3_5_panes() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    let scenario = Scenario::new("holger-ui-tools-robot")
        .step(
            Step::new("open Tools")
                .action(Action::ClickLabel("Tools".into()))
                .assert(Assert::State { pointer: "/tab".into(), expected: json!("tools") }),
        )
        .step(
            Step::new("select Tool #1 holger-ds → tool == holger-ds")
                .action(Action::ClickLabel("1 · holger-ds".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("holger-ds") }),
        )
        .step(
            Step::new("holger-ds default scale == micro")
                .assert(Assert::State { pointer: "/holger_ds/scale".into(), expected: json!("micro") }),
        )
        .step(
            Step::new("select Tool #3 security → tool == security")
                .action(Action::ClickLabel("3 · security · Móðguðr".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("security") }),
        )
        .step(
            Step::new("scan selected repo → Pass verdict over the empty corpus")
                .action(Action::ClickLabel("Scan selected repo".into()))
                .assert(Assert::State { pointer: "/security/decision".into(), expected: json!("pass") }),
        )
        .step(
            Step::new("select Tool #5 airgap → tool == airgap")
                .action(Action::ClickLabel("5 · airgap populate".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("airgap") }),
        )
        .step(
            Step::new("airgap default target == holger")
                .assert(Assert::State { pointer: "/airgap/target".into(), expected: json!("holger") }),
        )
        .step(
            Step::new("select Tool #2 migrate → tool == migrate")
                .action(Action::ClickLabel("2 · migrate / suck".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("migrate") }),
        )
        .step(
            Step::new("migrate default source == nexus")
                .assert(Assert::State { pointer: "/migrate/source".into(), expected: json!("nexus") }),
        );

    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 9, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(r.status, status::PASS, "robot step {:?}: {}", r.test_name, r.message);
    }
}

/// The buttons now WORK: the robot clicks each operator tool's run button and
/// asserts its REAL action ran (as DATA in `state_json`) — Tool #1 holger-ds
/// produced a throughput result over the package protocol, Tool #2 migrate was
/// invoked (and surfaced its clear "url required" validation for the empty demo
/// url), Tool #3 security produced a Pass verdict, Tool #5 airgap produced a
/// dry-run plan/result — plus the splash carries a version string.
#[test]
fn robot_runs_each_tool_real_action_and_sees_version() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    // The version string is presented (under the splash wordmark + in the header).
    let v = json!(holger_ui::app::HOLGER_UI_VERSION);
    assert!(
        holger_ui::app::HOLGER_UI_VERSION.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false),
        "version looks like a version: {}",
        holger_ui::app::HOLGER_UI_VERSION
    );

    let scenario = Scenario::new("holger-ui-run-tools")
        .step(
            Step::new("splash carries a version string")
                .assert(Assert::State { pointer: "/version".into(), expected: v }),
        )
        .step(
            Step::new("open Tools")
                .action(Action::ClickLabel("Tools".into()))
                .assert(Assert::State { pointer: "/tab".into(), expected: json!("tools") }),
        )
        // Tool #1 holger-ds — RUN the benchmark over the package protocol.
        .step(
            Step::new("select holger-ds")
                .action(Action::ClickLabel("1 · holger-ds".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("holger-ds") }),
        )
        .step(
            Step::new("Run benchmark → a REAL throughput result")
                .action(Action::ClickLabel("Run benchmark… (over the package protocol)".into()))
                .assert(Assert::State { pointer: "/holger_ds/result/ran".into(), expected: json!(true) }),
        )
        // Tool #2 migrate — RUN invokes the connector; empty demo url → clear msg.
        .step(
            Step::new("select migrate")
                .action(Action::ClickLabel("2 · migrate / suck".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("migrate") }),
        )
        .step(
            Step::new("Run migrate → connector invoked, clear url validation")
                .action(Action::ClickLabel("Run migrate… (via holger-agent)".into()))
                .assert(Assert::State { pointer: "/migrate/result/ran".into(), expected: json!(false) }),
        )
        // Tool #3 security — scan the selected repo → Pass verdict.
        .step(
            Step::new("select security")
                .action(Action::ClickLabel("3 · security · Móðguðr".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("security") }),
        )
        .step(
            Step::new("Scan → Pass verdict over the empty corpus")
                .action(Action::ClickLabel("Scan selected repo".into()))
                .assert(Assert::State { pointer: "/security/decision".into(), expected: json!("pass") }),
        )
        // Tool #5 airgap — the runnable demo default is a dry-run plan.
        .step(
            Step::new("select airgap")
                .action(Action::ClickLabel("5 · airgap populate".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("airgap") }),
        )
        .step(
            Step::new("Run populate (dry-run) → a real plan/result")
                .action(Action::ClickLabel("Run populate… (dry-run plan)".into()))
                .assert(Assert::State { pointer: "/airgap/run/ran".into(), expected: json!(true) }),
        );

    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 10, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(r.status, status::PASS, "robot step {:?}: {}", r.test_name, r.message);
    }

    // The migrate run carried a clear url validation (not a silent no-op).
    let s = robot.state();
    assert!(
        s["migrate"]["result"]["error"].as_str().unwrap_or("").contains("url"),
        "migrate surfaced a clear url-required message: {s}"
    );
    // The holger-ds result is real throughput over the protocol.
    assert!(
        s["holger_ds"]["result"]["ops"].as_u64().unwrap_or(0) > 0,
        "holger-ds completed GETs over the package protocol: {s}"
    );
    // The airgap dry-run plan lists the populate driver invocation.
    assert!(
        s["airgap"]["run"]["plan"].as_str().unwrap_or("").contains("airgap populate"),
        "airgap produced a real plan: {s}"
    );
}

/// The DEMO SELLPOINT: the robot drives the neon 3D graph. Navigating to the
/// Graph tab builds the holger graph (server → repositories → upstream/artifact
/// nodes) under `DecorPolicy::Full` (neon glow/shockwave/dim); then clicking a
/// repository node lights its subgraph and dims the rest. Every claim is asserted
/// against the live `state_json["graph"]` — the lit subgraph as DATA, not pixels
/// (LAW 2: real populated data, an empty subgraph would go RED).
#[test]
fn robot_clicks_repo_node_and_lights_its_subgraph() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    // Navigate to the Graph tab and let the neon graph build from real repos.
    robot.click_label("Graph").expect("Graph tab is clickable");
    robot.step();

    // The graph is built, neon-lit (Full effects), with the server + 3 repos at
    // least (LAW 2: populated). Nothing selected yet ⇒ nothing dimmed.
    let s = robot.state();
    assert_eq!(s["graph_built"], json!(true), "graph built from real repos: {s}");
    assert_eq!(
        s["graph"]["effects_policy"],
        json!("full"),
        "the beauty is ON — DecorPolicy::Full: {s}"
    );
    assert_eq!(s["graph"]["palette"], json!("neon"), "neon palette active: {s}");
    let nodes = s["graph"]["nodes"].as_u64().unwrap_or(0);
    assert!(nodes >= 4, "server + 3 repositories (≥4 nodes): {s}");
    // The HOLGER NEON PALETTE maps every node to a kind (server/repository/…).
    let kinds = s["graph"]["kinds"].as_array().expect("per-node kind palette");
    assert_eq!(kinds.len() as u64, nodes, "one kind per node: {s}");
    assert_eq!(kinds[0], json!("server"), "node 0 is the holger server anchor: {s}");
    assert!(
        s["graph"]["selected_node"].is_null(),
        "no selection yet → calm default: {s}"
    );
    assert_eq!(s["graph"]["highlighted_count"], json!(0), "nothing lit yet: {s}");
    assert_eq!(s["graph"]["dimmed_alpha"], json!(1.0), "nothing dimmed yet: {s}");

    // Click (select) the first repository node — index 1, since node 0 is the
    // server. This is the same path the in-view 3D click drives (Graph3D::select);
    // the facett kernel lights its subgraph and dims the rest.
    robot.app_mut().0.select_graph_node(1);
    robot.step();

    let s = robot.state();
    assert_eq!(s["graph"]["selected_node"], json!(1), "the repo node is selected: {s}");
    // The selected node is one of the seeded repositories (node 0 is the server).
    let sel_label = s["graph"]["selected_label"].as_str().unwrap_or("");
    assert!(
        ["rust-dev", "cache", "sparring"].contains(&sel_label),
        "the selected node is a seeded repository, got {sel_label:?}: {s}"
    );
    assert!(
        s["graph"]["selected_kind"].is_string(),
        "the selected node carries a neon-palette kind: {s}"
    );
    // The lit subgraph is REAL and non-empty (the repo's neighbours light up).
    let lit = s["graph"]["highlighted_neighbours"]
        .as_array()
        .expect("the lit subgraph is an array");
    assert!(!lit.is_empty(), "clicking a repo lights a NON-EMPTY subgraph: {s}");
    assert!(
        s["graph"]["highlighted_count"].as_u64().unwrap_or(0) >= 1,
        "≥1 neighbour lit: {s}"
    );
    // The dim is real: unrelated nodes/edges drop below full alpha.
    assert!(
        s["graph"]["dimmed_alpha"].as_f64().unwrap_or(1.0) < 1.0,
        "selecting a repo dims the unrelated rest: {s}"
    );
}

/// T5 (lands WITH B5/P5): the static "silent running" mode is driven off the
/// server-reported profile (`AdminService.ServerProfile`), NOT a local toggle.
/// (a) A server with ONLY read-only repos derives a static/read-only profile, so
/// the app starts static WITHOUT anyone clicking the toggle. (b) A server with a
/// writable repo derives a dynamic profile, so the app starts non-static.
#[test]
fn robot_static_mode_reflects_server_profile() {
    // (a) all read-only → server profile is static/read-only → static by default.
    let ro: Vec<(String, Arc<dyn RepositoryBackendTrait>)> = vec![
        ("locked-a".to_string(), Arc::new(StubRepo::ro("locked-a"))),
        ("locked-b".to_string(), Arc::new(StubRepo::ro("locked-b"))),
    ];
    let app = app_over(ro);
    let s = app.state_json();
    assert_eq!(s["static_mode"], json!(true), "all-read-only server starts static: {s}");
    assert_eq!(s["profile"]["read_only"], json!(true), "server profile is read-only: {s}");
    assert_eq!(s["profile"]["loaded"], json!(true), "profile was fetched: {s}");
    assert!(
        s["profile"]["label"].as_str().unwrap_or("").contains("SILENT RUNNING"),
        "profile carries the silent-running label: {s}"
    );
    assert_eq!(s["profile"]["writable_repo_count"], json!(0), "no writable repos: {s}");
    // The badge / look follow the static profile.
    assert_eq!(s["look"], json!("skade_vinter"), "static look engaged from the profile: {s}");

    // (b) ≥1 writable repo → dynamic profile → NOT static by default.
    let rw: Vec<(String, Arc<dyn RepositoryBackendTrait>)> = vec![
        ("live".to_string(), Arc::new(StubRepo::rw("live"))),
        ("locked".to_string(), Arc::new(StubRepo::ro("locked"))),
    ];
    let app = app_over(rw);
    let s = app.state_json();
    assert_eq!(s["static_mode"], json!(false), "a writable server starts dynamic: {s}");
    assert_eq!(s["profile"]["read_only"], json!(false), "server profile is dynamic: {s}");
    assert_eq!(s["profile"]["writable_repo_count"], json!(1), "one writable repo: {s}");
}

/// T3: Tools #2-#5 (and, after B6, #1 holger-ds) are disabled — non-clickable —
/// in static read-only mode. Direct-drive style (app_mut) so a swallowed click
/// can be asserted as "no change from the prior value". seeded_app starts
/// dynamic (it has a writable repo), so the operator can first select holger-ds,
/// then engage static and watch the other tools stop responding.
#[test]
fn robot_static_mode_disables_other_tools() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Tools").expect("Tools tab");
    robot.step();
    robot.click_label("1 · holger-ds").expect("holger-ds selectable (dynamic)");
    robot.step();
    assert_eq!(robot.state()["tool"], json!("holger-ds"), "tool == holger-ds");

    // Engage static silent-running.
    robot.click_label("⚓ static").expect("static toggle");
    robot.step();
    assert_eq!(robot.state()["static_mode"], json!(true), "static engaged");
    assert_eq!(robot.state()["look"], json!("skade_vinter"), "winter look engaged");

    // #2-#5 selectables are now disabled: clicking them is swallowed, the tool
    // stays holger-ds. (click_label may not even find an enabled target; either
    // way the tool must not change.)
    for label in ["2 · migrate / suck", "3 · security · Móðguðr", "4 · deploy · Skíðblaðnir", "5 · airgap populate"] {
        let _ = robot.click_label(label);
        robot.step();
        assert_eq!(
            robot.state()["tool"],
            json!("holger-ds"),
            "tool unchanged after swallowed click on disabled {label:?}"
        );
    }

    // Toggle static back off → #2 migrate becomes selectable again.
    robot.click_label("⚓ static").expect("static toggle off");
    robot.step();
    assert_eq!(robot.state()["static_mode"], json!(false), "static disengaged");
    robot.click_label("2 · migrate / suck").expect("migrate selectable again (dynamic)");
    robot.step();
    assert_eq!(robot.state()["tool"], json!("migrate"), "migrate selectable once dynamic");
}

/// T6: clicking a repository row drives selection (the flow every other tab
/// depends on), and the selection propagates downstream (the security scan
/// targets the selected repo). Needs T1 (`/repos` in state_json).
#[test]
fn robot_repo_row_selection_propagates() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Repos").expect("Repos tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("repos"));
    // FastRoutes sorts the repos to [cache, rust-dev, sparring]; first selected.
    assert_eq!(robot.state()["repos"]["selected"], json!(0), "first repo selected by default");

    // Drive the row selection (the row name collides with the facett Table cell,
    // so a label-addressed click is ambiguous; select_repo runs the same path).
    robot.app_mut().0.select_repo(2);
    robot.step();
    assert_eq!(robot.state()["repos"]["selected"], json!(2), "selecting sparring → index 2");
    assert_eq!(robot.state()["repos"]["repos"][2]["name"], json!("sparring"), "index 2 is sparring");

    // Propagates downstream: the security scan targets the selected repo.
    robot.click_label("Tools").expect("Tools");
    robot.step();
    robot.click_label("3 · security · Móðguðr").expect("security");
    robot.step();
    robot.click_label("Scan selected repo").expect("scan");
    robot.step();
    assert_eq!(
        robot.state()["security"]["repository"],
        json!("sparring"),
        "the scan targets the row the operator selected"
    );
}

/// T13: the Status tab is reachable by nav, its refresh button loads health, and
/// the status grid carries real values. Needs T1 (`/status` in state_json).
#[test]
fn robot_status_tab_nav_and_refresh() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Graph").expect("Graph tab");
    robot.step();
    robot.click_label("Status").expect("Status tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("status"));

    robot.click_label("⟳ refresh").expect("refresh button");
    robot.step();
    let s = robot.state();
    assert_eq!(s["status"]["loaded"], json!(true), "health loaded: {s}");
    assert!(s["status"]["version"].as_str().map(|v| !v.is_empty()).unwrap_or(false), "version present: {s}");
    assert_eq!(s["status"]["error"], json!(null), "no error on a healthy server: {s}");
    assert_eq!(s["status"]["status"], json!("ok"), "status ok: {s}");
}

/// T19: the Upload flow reflects the selected repo's writability. seeded_app has
/// a writable repo (rust-dev) and read-only repos (cache/sparring). Needs T1
/// (`/upload` section).
#[test]
fn robot_upload_writable_reflects_selected_repo() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    // FastRoutes sorts to [cache(ro), rust-dev(rw), sparring(ro)]; the default
    // selection is cache (read-only) → upload disabled.
    robot.click_label("Upload").expect("Upload tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("upload"));
    assert_eq!(robot.state()["upload"]["writable"], json!(false), "read-only repo → upload disabled");

    // Select the writable repo (rust-dev, index 1) → upload enabled, warning gone.
    robot.app_mut().0.select_repo(1);
    robot.step();
    let s = robot.state();
    assert_eq!(s["repos"]["repos"][1]["name"], json!("rust-dev"), "index 1 is rust-dev");
    assert_eq!(s["upload"]["writable"], json!(true), "writable repo → upload enabled: {s}");
}

/// T4: in static read-only mode the Upload tab is unreachable — selecting it
/// while static redirects to Status, and the disabled Upload nav stays inert.
#[test]
fn robot_static_mode_redirects_upload_to_status() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    // Dynamic by default: Upload is reachable.
    robot.click_label("Upload").expect("Upload tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("upload"));

    // Engage static → the next frame redirects Upload to Status.
    robot.click_label("⚓ static").expect("static toggle");
    robot.step();
    assert_eq!(robot.state()["static_mode"], json!(true));
    assert_eq!(robot.state()["tab"], json!("status"), "static mode forces Upload → Status");

    // The disabled (strikethrough) Upload nav is inert: clicking leaves Status.
    let _ = robot.click_label("Upload");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("status"), "disabled Upload nav stays on Status");
}

/// T18: the look-preset switcher is driven by real clicks (not just the direct
/// setter), and the static override wins while engaged then restores the
/// operator's manual preset.
#[test]
fn robot_look_preset_switcher_and_static_override() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    // Default look (collapsed roster — dark/light/device).
    assert_eq!(robot.state()["look"], json!("dark"), "default look");

    robot.click_label("device").expect("device preset label");
    robot.step();
    assert_eq!(robot.state()["look"], json!("device"), "clicking device switches the look");

    // Static override wins.
    robot.click_label("⚓ static").expect("static toggle");
    robot.step();
    assert_eq!(robot.state()["look"], json!("skade_vinter"), "static overrides the preset");

    // Disengage → the manual preset (device) is restored.
    robot.click_label("⚓ static").expect("static toggle off");
    robot.step();
    assert_eq!(robot.state()["look"], json!("device"), "manual preset restored after static");
}

/// T15: the Tool #1/#2/#5 config selectables drive real state changes (the egui
/// widget binding, not just the data-layer defaults).
#[test]
fn robot_tool_config_selectables_change_state() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Tools").expect("Tools");
    robot.step();

    // Tool #1 holger-ds scale.
    robot.click_label("1 · holger-ds").expect("holger-ds");
    robot.step();
    robot.click_label("large").expect("large scale");
    robot.step();
    assert_eq!(robot.state()["holger_ds"]["scale"], json!("large"), "scale → large");

    // Tool #2 migrate source.
    robot.click_label("2 · migrate / suck").expect("migrate");
    robot.step();
    robot.click_label("artifactory").expect("artifactory source");
    robot.step();
    assert_eq!(robot.state()["migrate"]["source"], json!("artifactory"), "source → artifactory");

    // Tool #5 airgap target + auth.
    robot.click_label("5 · airgap populate").expect("airgap");
    robot.step();
    robot.click_label("nexus").expect("nexus target");
    robot.step();
    assert_eq!(robot.state()["airgap"]["target"], json!("nexus"), "target → nexus");
    robot.click_label("oidc").expect("oidc auth");
    robot.step();
    assert_eq!(robot.state()["airgap"]["auth"], json!("oidc"), "auth → oidc");
}

/// T16 (lands WITH B2): the airgap validate() result is a pure state pointer.
/// The runnable demo default is a dry-run plan, so `can_run` is true by default;
/// a push with no creds drives it back to the red "cannot run" branch.
#[test]
fn robot_airgap_validate_can_run_state() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Tools").expect("Tools");
    robot.step();
    robot.click_label("5 · airgap populate").expect("airgap");
    robot.step();
    // Default is dry-run → validates → can_run true, no error.
    let s = robot.state();
    assert_eq!(s["airgap"]["dry_run"], json!(true), "demo default is dry-run: {s}");
    assert_eq!(s["airgap"]["can_run"], json!(true), "dry-run plan can run: {s}");
    assert_eq!(s["airgap"]["validate_error"], json!(null), "no validation error by default: {s}");

    // Drive it into the red branch: a real push (dry_run off) with no creds.
    {
        let app = robot.app_mut();
        app.0.airgap_set_dry_run(false);
    }
    robot.step();
    let s = robot.state();
    assert_eq!(s["airgap"]["can_run"], json!(false), "push with no creds cannot run: {s}");
    assert!(
        s["airgap"]["validate_error"].as_str().map(|e| !e.is_empty()).unwrap_or(false),
        "the red branch carries a validation error: {s}"
    );
}

/// T17 (demo must-have #1): the startup logo splash is shown on frame 1 (tabs
/// hidden) and dismisses on a click.
#[test]
fn robot_startup_splash_dismisses_on_click() {
    // Build WITHOUT skip_splash so the splash is live.
    let repos: Vec<(String, Arc<dyn RepositoryBackendTrait>)> = vec![
        ("rust-dev".to_string(), Arc::new(StubRepo::rw("rust-dev"))),
    ];
    let holger: Arc<dyn HolgerObject> = Arc::new(LocalHolger::new(FastRoutes::new(repos)));
    let data = UiData::new(holger).expect("runtime");
    let app = HolgerUiApp::new(data); // no skip_splash
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(app));
    let mut robot = RobotSession::new(harness, "holger-ui");
    robot.step();

    // Frame 1: splash up, tabs hidden.
    assert_eq!(robot.state()["splash_done"], json!(false), "splash shows on startup");
    assert!(!robot.label_visible("Status"), "tabs hidden behind the splash");

    // Inject a pointer click → splash dismisses.
    let pos = egui::Pos2::new(120.0, 120.0);
    let m = egui::Modifiers::default();
    robot.inject_events([
        egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, modifiers: m },
        egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, modifiers: m },
    ]);
    robot.step();
    robot.step();

    assert_eq!(robot.state()["splash_done"], json!(true), "splash dismissed on click");
    assert!(robot.label_visible("Status"), "tabs visible after dismiss");
}

/// T7: the Artifact fetch flow — a found hit and a clean not-found, driven via
/// the UI and asserted as DATA (`/artifact`). Needs T1.
#[test]
fn robot_artifact_fetch_found_and_not_found() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(data_app(false)));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Artifact").expect("Artifact tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("artifact"));

    // A hit: serde 1.0.0 resolves to bytes.
    robot.app_mut().0.set_artifact_query("rust-data", "serde", "1.0.0");
    robot.click_label("fetch").expect("fetch button");
    robot.step();
    let s = robot.state();
    assert_eq!(s["artifact"]["name"], json!("serde"), "fetched name: {s}");
    assert_eq!(s["artifact"]["found"], json!(true), "serde found: {s}");
    assert!(s["artifact"]["size_bytes"].as_u64().unwrap_or(0) > 0, "non-zero size: {s}");
    assert_eq!(s["artifact"]["error"], json!(null), "no transport error: {s}");

    // A clean miss: NOT_FOUND is found==false with no error (distinct from a
    // transport error).
    robot.app_mut().0.set_artifact_query("rust-data", "ghost", "9.9.9");
    robot.click_label("fetch").expect("fetch button");
    robot.step();
    let s = robot.state();
    assert_eq!(s["artifact"]["found"], json!(false), "ghost not found: {s}");
    assert_eq!(s["artifact"]["error"], json!(null), "clean NOT_FOUND, not an error: {s}");
}

/// T8: the Browse tab refresh button lists the repo's artifacts as DATA. Needs T1.
#[test]
fn robot_browse_tab_refresh_lists_artifacts() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(data_app(false)));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Browse").expect("Browse tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("browse"));
    robot.click_label("⟳ refresh").expect("refresh button");
    robot.step();
    let s = robot.state();
    assert_eq!(s["browse"]["repository"], json!("rust-data"), "browse targets the selected repo: {s}");
    let entries = s["browse"]["entries"].as_array().expect("entries array");
    assert_eq!(entries.len(), 2, "serde + tokio listed: {s}");
    assert!(entries.iter().any(|e| e["name"] == json!("serde")), "serde row: {s}");
    assert!(entries.iter().any(|e| e["name"] == json!("tokio")), "tokio row: {s}");
}

/// T9: the Archive tab refresh button exposes the stats grid + file tree, and the
/// graph grows with artifact nodes. Needs T1.
#[test]
fn robot_archive_tab_refresh_stats_and_files() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(data_app(false)));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Archive").expect("Archive tab");
    robot.step();
    assert_eq!(robot.state()["tab"], json!("archive"));
    robot.click_label("⟳ refresh").expect("refresh button");
    robot.step();
    let s = robot.state();
    assert_eq!(s["archive"]["file_count"], json!(3), "archive file_count: {s}");
    assert_eq!(s["archive"]["total_uncompressed_bytes"], json!(4242), "archive bytes: {s}");
    let files = s["archive"]["files"].as_array().expect("files array");
    assert_eq!(files.len(), 3, "three archive entries: {s}");

    // The graph grows artifact nodes from the loaded archive.
    robot.click_label("Graph").expect("Graph tab");
    robot.step();
    let s = robot.state();
    let kinds = s["graph"]["kinds"].as_array().expect("kinds array");
    assert!(kinds.iter().any(|k| k == &json!("artifact")), "graph grew artifact nodes: {s}");
}

/// T10: the security scan BLOCK verdict + findings are driven via the UI over a
/// vuln corpus (the openssl advisory), asserted as DATA.
#[test]
fn robot_security_scan_block_verdict() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(data_app(true)));
    let mut robot = RobotSession::new(harness, "holger-ui");

    robot.click_label("Tools").expect("Tools");
    robot.step();
    robot.click_label("3 · security · Móðguðr").expect("security");
    robot.step();
    robot.click_label("Scan selected repo").expect("scan");
    robot.step();
    let s = robot.state();
    assert_eq!(s["security"]["decision"], json!("block"), "vuln corpus blocks: {s}");
    assert!(s["security"]["block"].as_u64().unwrap_or(0) >= 1, "≥1 blocked artifact: {s}");
    assert_eq!(s["security"]["error"], json!(null), "block is a verdict, not a transport error: {s}");
    // The openssl finding is present with its advisory id.
    let findings = s["security"]["findings"].as_array().expect("findings array");
    let openssl = findings.iter().find(|f| f["name"] == json!("openssl")).expect("openssl finding");
    let ids = openssl["ids"].as_array().expect("ids array");
    assert!(
        ids.iter().any(|i| i.as_str().map(|s| s.contains("RUSTSEC-2023-0044")).unwrap_or(false)),
        "openssl finding carries the advisory id: {s}"
    );
}

/// Tool #4 Deploy (Skíðblaðnir) — the button now WORKS (was a no-op "** being
/// implemented" stub). The robot opens Tools, selects Deploy, picks the nexus
/// target, and clicks "Deploy to test…"; the app reads the selected repo's REAL
/// sealed znippy bundle (`archive_info`) and produces a real airgap-engine
/// push-only deploy plan. Every claim is asserted against the live `state_json`
/// — the deploy result as DATA, not pixels.
#[test]
fn robot_deploys_selected_repo_sealed_bundle() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(data_app(false)));
    let mut robot = RobotSession::new(harness, "holger-ui");

    let scenario = Scenario::new("holger-ui-deploy")
        .step(
            Step::new("open Tools")
                .action(Action::ClickLabel("Tools".into()))
                .assert(Assert::State { pointer: "/tab".into(), expected: json!("tools") }),
        )
        .step(
            Step::new("select Deploy (Skíðblaðnir) → tool == deploy")
                .action(Action::ClickLabel("4 · deploy · Skíðblaðnir".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("deploy") }),
        )
        .step(
            Step::new("pick the nexus target")
                .action(Action::ClickLabel("nexus".into()))
                .assert(Assert::State { pointer: "/deploy/target".into(), expected: json!("nexus") }),
        )
        .step(
            Step::new("Deploy to test… → a REAL airgap deploy plan over the sealed bundle")
                .action(Action::ClickLabel("Deploy to test…".into()))
                .assert(Assert::State { pointer: "/deploy/result/ran".into(), expected: json!(true) }),
        );

    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 4, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(r.status, status::PASS, "robot step {:?}: {}", r.test_name, r.message);
    }

    // The deploy carried the REAL sealed bundle (rust-data's archive_info: 3 files)
    // and a real airgap push-only plan — not a no-op.
    let s = robot.state();
    assert_eq!(s["deploy"]["result"]["file_count"], json!(3), "sealed bundle file count: {s}");
    assert_eq!(s["deploy"]["result"]["target"], json!("nexus"), "deployed to the picked target: {s}");
    assert!(
        s["deploy"]["result"]["plan"].as_str().unwrap_or("").contains("airgap populate"),
        "deploy produced a real airgap-engine plan: {s}"
    );
    assert!(
        s["deploy"]["result"]["plan"].as_str().unwrap_or("").contains("push-only"),
        "deploy carries the already-sealed bundle (push-only): {s}"
    );
    assert_eq!(s["deploy"]["result"]["error"], json!(null), "a clean deploy plan, no error: {s}");
}

/// **About + Tools·Demo — the shared common-framework surfaces, robot-clicked.** The
/// robot opens the **About** identity popup (the `ℹ About` header button), asserts the
/// live `state_json` reports it open with holger's identity, dismisses it with Close,
/// then opens **Tools → 6 · demo appliance** and clicks "Start demo appliance…" — the
/// jera-backed demo. Every step asserts the live `state_json`: the demo dispatch is
/// recorded through the shared job manager (a non-empty jera job id), not a bespoke
/// spawn. Real AccessKit clicks; matrix rows a robot run fills.
#[test]
fn robot_opens_about_and_dispatches_the_jera_demo() {
    let harness = Harness::builder()
        .with_size(egui::Vec2::new(1100.0, 720.0))
        .build_state(|ctx, app: &mut UiApp| app.0.draw_ui(ctx), UiApp(seeded_app()));
    let mut robot = RobotSession::new(harness, "holger-ui");

    let scenario = Scenario::new("holger-ui-about-and-demo")
        // About: the shared identity surface opens + reports holger's identity.
        .step(
            Step::new("open About → popup open + identity reported")
                .action(Action::ClickLabel("ℹ About".into()))
                .assert(Assert::State { pointer: "/about/open".into(), expected: json!(true) }),
        )
        .step(
            Step::new("About reports the wordmark identity")
                .assert(Assert::State { pointer: "/about/wordmark".into(), expected: json!("holger") }),
        )
        .step(
            Step::new("dismiss About with Close")
                .action(Action::ClickLabel("Close".into()))
                .assert(Assert::State { pointer: "/about/open".into(), expected: json!(false) }),
        )
        // Tools · Demo appliance: dispatched THROUGH jera (observable job id).
        .step(
            Step::new("open Tools")
                .action(Action::ClickLabel("Tools".into()))
                .assert(Assert::State { pointer: "/tab".into(), expected: json!("tools") }),
        )
        .step(
            Step::new("select the demo appliance tool")
                .action(Action::ClickLabel("6 · demo appliance".into()))
                .assert(Assert::State { pointer: "/tool".into(), expected: json!("demo") }),
        )
        .step(
            Step::new("Start demo appliance → dispatched as a jera job")
                .action(Action::ClickLabel("Start demo appliance… (as a jera job)".into()))
                .assert(Assert::State { pointer: "/demo_appliance/dispatched".into(), expected: json!(true) }),
        );

    let rows = robot.run_scenario(&scenario);
    assert_eq!(rows.len(), 6, "one matrix row per robot step");
    for r in &rows {
        assert_eq!(r.status, status::PASS, "robot step {:?}: {}", r.test_name, r.message);
    }

    // The demo went through the shared job manager: a real jera job id + the pinned
    // demo registry image — not a bespoke spawn.
    let s = robot.state();
    let job_id = s["demo_appliance"]["job_id"].as_str().unwrap_or("");
    assert!(!job_id.is_empty(), "the demo dispatch recorded a jera job id: {s}");
    assert!(
        s["demo_appliance"]["image"].as_str().unwrap_or("").contains("registry"),
        "the dispatched demo container is the pinned registry image: {s}"
    );
    // About carried holger's version + the shared framework it is built on (incl. jera).
    let fw = s["about"]["framework"].as_array().expect("framework list");
    assert!(
        fw.iter().any(|c| c.as_str().unwrap_or("").contains("jera")),
        "About names the shared jera job manager: {s}"
    );
}