nornir 0.4.34

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
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
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
//! Thin-client timeline loader: fetch a [`Timeline`] from a running
//! `nornir-server` over the `Viz.Timeline` gRPC instead of opening a local
//! Iceberg warehouse. The server builds the timeline from the warehouse it
//! owns (it holds the redb lock) and returns it as JSON; we deserialize into
//! the same [`Timeline`] the embedded path produces, so the egui app is
//! source-agnostic.

use anyhow::{Context, Result};

use super::live::LiveEvent;
use super::model::Timeline;
use crate::warehouse::iceberg::TablePreview;

mod pb {
    tonic::include_proto!("nornir.v1");
}

/// Build an `http://…` endpoint url + a `Bearer <token>` metadata value — the
/// shared connect/auth shape for the viz gRPC clients.
fn endpoint_and_bearer(
    endpoint: &str,
    token: &str,
) -> Result<(String, tonic::metadata::MetadataValue<tonic::metadata::Ascii>)> {
    let endpoint = if endpoint.starts_with("http") {
        endpoint.to_string()
    } else {
        format!("http://{endpoint}")
    };
    let bearer = format!("Bearer {token}").parse().context("parse bearer token")?;
    Ok((endpoint, bearer))
}

/// The `nornir-workspace` metadata value for `workspace` (empty ⇒ none) — selects
/// which served workspace the gRPC calls target. Driven by the app's currently
/// selected workspace (the in-UI picker), not an env var, so the viz can switch
/// workspaces live.
fn ws_header(workspace: &str) -> Option<tonic::metadata::MetadataValue<tonic::metadata::Ascii>> {
    (!workspace.is_empty()).then(|| workspace.parse().ok()).flatten()
}

/// List the workspaces the server has registered (`Workspaces.List` RPC) — the
/// names that populate the viz's workspace picker.
pub fn list_workspaces(endpoint: &str, token: &str) -> Result<Vec<String>> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz client")?;
    rt.block_on(async {
        let (endpoint, bearer) = endpoint_and_bearer(endpoint, token)?;
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let mut client = pb::workspaces_client::WorkspacesClient::with_interceptor(
            channel,
            move |mut req: tonic::Request<()>| {
                req.metadata_mut().insert("authorization", bearer.clone());
                Ok(req)
            },
        );
        let resp = client.list(pb::Empty {}).await.context("Workspaces.List RPC")?.into_inner();
        Ok(resp.workspaces.into_iter().map(|w| w.name).collect())
    })
}

/// Fetch the timeline for `workspace` from `endpoint` (e.g.
/// `http://127.0.0.1:7878`), authenticating with the bearer `token`. Runs the
/// async tonic call on a private current-thread runtime so it's safe to call
/// from the synchronous egui update loop.
pub fn fetch_timeline(endpoint: &str, token: &str, workspace: &str) -> Result<Timeline> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz client")?;
    rt.block_on(async {
        let endpoint = if endpoint.starts_with("http") {
            endpoint.to_string()
        } else {
            format!("http://{endpoint}")
        };
        let bearer: tonic::metadata::MetadataValue<tonic::metadata::Ascii> =
            format!("Bearer {token}").parse().context("parse bearer token")?;
        let ws_md = ws_header(workspace);
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let mut client = pb::viz_client::VizClient::with_interceptor(
            channel,
            move |mut req: tonic::Request<()>| {
                req.metadata_mut().insert("authorization", bearer.clone());
                if let Some(ws) = &ws_md {
                    req.metadata_mut().insert("nornir-workspace", ws.clone());
                }
                Ok(req)
            },
        );
        let resp = client
            .timeline(pb::VizTimelineRequest { workspace: workspace.to_string() })
            .await
            .context("Viz.Timeline RPC")?
            .into_inner();
        let timeline: Timeline =
            serde_json::from_str(&resp.json).context("decode timeline json from server")?;
        Ok(timeline)
    })
}

/// `Viz.ReleaseEvents` — every `release_events` row for `workspace`, decoded
/// into the same [`ReleaseEventRow`] the embedded warehouse read returns, so the
/// 🚀 Release tab + 📡 Live Run hydrate render identically in thin mode. The
/// server holds the redb lock, so the rows come over this RPC instead of a local
/// warehouse open.
pub fn fetch_release_events(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<Vec<crate::warehouse::release_events::ReleaseEventRow>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .release_events(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.ReleaseEvents RPC")?
            .into_inner();
        let rows = serde_json::from_str(&r.json).context("decode release_events json from server")?;
        Ok(rows)
    })
}

/// `Viz.TestResults` — every `test_results` row for `workspace`, decoded into
/// the same [`TestResultRow`] the embedded warehouse read returns, so the 🧪
/// Test tab renders identically in thin mode.
pub fn fetch_test_results(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<Vec<crate::warehouse::test_results::TestResultRow>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .test_results(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.TestResults RPC")?
            .into_inner();
        let rows = serde_json::from_str(&r.json).context("decode test_results json from server")?;
        Ok(rows)
    })
}

/// `Viz.TestMatrix` — the BUILD-FREE test matrix for `workspace`: the discovered
/// inventory (syn scan) + every `test_results` row, so the thin 🧪 Test tab joins
/// them into the identical ok|fail|X tri-state matrix (with the `is_heavy` flag).
pub fn fetch_test_matrix(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<(
    Vec<crate::warehouse::test_inventory::TestInventoryRow>,
    Vec<crate::warehouse::test_results::TestResultRow>,
)> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .test_matrix(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.TestMatrix RPC")?
            .into_inner();
        #[derive(serde::Deserialize)]
        struct Resp {
            inventory: Vec<crate::warehouse::test_inventory::TestInventoryRow>,
            results: Vec<crate::warehouse::test_results::TestResultRow>,
        }
        let resp: Resp =
            serde_json::from_str(&r.json).context("decode test_matrix json from server")?;
        Ok((resp.inventory, resp.results))
    })
}

/// `Viz.BenchTelemetry` — the `bench_telemetry` + `bench_runs` rows for
/// `workspace`, decoded into the same `(Vec<BenchTelemetryRow>, Vec<BenchRun>)`
/// the embedded warehouse read returns, so the 📡 Bench LIVE panel folds and
/// renders identically in thin mode.
pub fn fetch_bench_live(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<(Vec<crate::warehouse::iceberg::BenchTelemetryRow>, Vec<crate::bench::BenchRun>)> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .bench_telemetry(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.BenchTelemetry RPC")?
            .into_inner();
        let v: serde_json::Value =
            serde_json::from_str(&r.json).context("decode bench json from server")?;
        let telemetry = serde_json::from_value(v.get("telemetry").cloned().unwrap_or_default())
            .context("decode bench_telemetry rows")?;
        let runs = serde_json::from_value(v.get("runs").cloned().unwrap_or_default())
            .context("decode bench_runs rows")?;
        Ok((telemetry, runs))
    })
}

/// `Viz.BakeoffResults` — every `agent_model_runs` row for `workspace`, decoded
/// into the same [`AgentModelRunRow`] the embedded warehouse read returns, so the
/// 🏆 Leaderboard tab renders identically in thin mode.
pub fn fetch_bakeoff_results(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<Vec<crate::warehouse::agent_model_runs::AgentModelRunRow>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .bakeoff_results(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.BakeoffResults RPC")?
            .into_inner();
        let rows = serde_json::from_str(&r.json).context("decode agent_model_runs json from server")?;
        Ok(rows)
    })
}

/// `Telemetry.SubmitBakeoff` — push client-run `agent_model_runs` rows into the
/// served `workspace`'s warehouse (the server owns the lock). Returns the
/// accepted count. The thin counterpart to the embedded `append_agent_model_runs`
/// — fills the live 🏆 Leaderboard. Mirrors the `nornir bakeoff` CLI submit.
pub fn submit_bakeoff(
    endpoint: &str,
    token: &str,
    workspace: &str,
    rows: &[crate::warehouse::agent_model_runs::AgentModelRunRow],
) -> Result<u32> {
    let runs: Vec<pb::AgentModelRunPb> = rows
        .iter()
        .map(|r| pb::AgentModelRunPb {
            run_id: r.run_id.clone(),
            ts_micros: r.ts_micros,
            agent: r.agent.clone(),
            model: r.model.clone(),
            prompt_id: r.prompt_id.clone(),
            prompt: r.prompt.clone(),
            output: r.output.clone(),
            latency_ms: r.latency_ms,
            tokens_in: r.tokens_in,
            tokens_out: r.tokens_out,
            tokens_per_s: r.tokens_per_s,
            score: r.score,
            ok: r.ok,
            error: r.error.clone().unwrap_or_default(),
            cost_usd: r.cost_usd,
            mcp_tool_calls: r.mcp_tool_calls,
        })
        .collect();
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::telemetry_client::TelemetryClient::with_interceptor(channel, auth);
        let r = c
            .submit_bakeoff(pb::SubmitBakeoffRequest { runs })
            .await
            .context("Telemetry.SubmitBakeoff RPC")?
            .into_inner();
        Ok(r.accepted)
    })
}

/// `Telemetry.SubmitTestResults` — push client-run `test_results` rows into the
/// served `workspace`'s warehouse. Returns the accepted count. Fills the live 🧪
/// Test pane. Mirrors the `nornir test` CLI submit.
pub fn submit_test_results(
    endpoint: &str,
    token: &str,
    workspace: &str,
    rows: &[crate::warehouse::test_results::TestResultRow],
) -> Result<u32> {
    let pb_rows: Vec<pb::TestResultPb> = rows
        .iter()
        .map(|r| pb::TestResultPb {
            run_id: r.run_id.clone(),
            repo: r.repo.clone(),
            suite: r.suite.clone(),
            test_name: r.test_name.clone(),
            status: r.status.clone(),
            duration_ms: r.duration_ms,
            ts_micros: r.ts_micros,
            message: r.message.clone(),
            aspect: r.aspect.clone(),
            metric: r.metric,
        })
        .collect();
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::telemetry_client::TelemetryClient::with_interceptor(channel, auth);
        let r = c
            .submit_test_results(pb::SubmitTestResultsRequest { rows: pb_rows })
            .await
            .context("Telemetry.SubmitTestResults RPC")?
            .into_inner();
        Ok(r.accepted)
    })
}

/// `Telemetry.SubmitReleaseEvents` — push client-run `release_events` rows into
/// the served `workspace`'s warehouse. Returns the accepted count. Fills the live
/// 🚀 Release tab. Mirrors the `nornir release run` CLI submit. The `Option`
/// fields (`depends_on`, `elapsed_ms`) are carried with a presence flag so None
/// round-trips distinct from an empty list.
pub fn submit_release_events(
    endpoint: &str,
    token: &str,
    workspace: &str,
    rows: &[crate::warehouse::release_events::ReleaseEventRow],
) -> Result<u32> {
    let pb_rows: Vec<pb::ReleaseEventPb> = rows
        .iter()
        .map(|r| pb::ReleaseEventPb {
            run_id: r.run_id.clone(),
            seq: r.seq,
            ts_micros: r.ts_micros,
            component: r.component.clone(),
            repo: r.repo.clone(),
            op: r.op.clone(),
            phase: r.phase.clone(),
            status: r.status.clone(),
            detail: r.detail.clone(),
            has_depends_on: r.depends_on.is_some(),
            depends_on: r.depends_on.clone().unwrap_or_default(),
            has_elapsed_ms: r.elapsed_ms.is_some(),
            elapsed_ms: r.elapsed_ms.unwrap_or_default(),
        })
        .collect();
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::telemetry_client::TelemetryClient::with_interceptor(channel, auth);
        let r = c
            .submit_release_events(pb::SubmitReleaseEventsRequest { rows: pb_rows })
            .await
            .context("Telemetry.SubmitReleaseEvents RPC")?
            .into_inner();
        Ok(r.accepted)
    })
}

/// `Viz.Knowledge` — the server-side knowledge-map scan summary for `workspace`
/// (the server owns the cloned repos, so the scan runs there). Decoded into the
/// [`KnowledgeSummary`](super::knowledge::KnowledgeSummary) the 🗺 Knowledge tab
/// renders.
pub fn knowledge_summary(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<super::knowledge::KnowledgeSummary> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::viz_client::VizClient::with_interceptor(channel, auth);
        let r = c
            .knowledge(pb::VizTimelineRequest { workspace: String::new() })
            .await
            .context("Viz.Knowledge RPC")?
            .into_inner();
        let summary = serde_json::from_str(&r.json).context("decode knowledge summary json from server")?;
        Ok(summary)
    })
}

/// Open the server's `Release.Progress` server-stream and invoke `on_event`
/// for each converted [`LiveEvent`]. Blocks until the stream closes (the server
/// ends it after `RunEnd`) or errors — call it from a dedicated `std::thread`
/// (see [`super::live`]). Runs its own current-thread tokio runtime so it never
/// touches the egui loop. This is what makes a remote viz animate a release run
/// in real time over Tailscale: same events the local file tail would produce.
pub fn stream_progress(
    endpoint: &str,
    token: &str,
    mut on_event: impl FnMut(LiveEvent),
) -> Result<()> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz live client")?;
    rt.block_on(async {
        let (endpoint, bearer) = endpoint_and_bearer(endpoint, token)?;
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let mut client = pb::release_client::ReleaseClient::with_interceptor(
            channel,
            move |mut req: tonic::Request<()>| {
                req.metadata_mut().insert("authorization", bearer.clone());
                Ok(req)
            },
        );
        let mut stream = client
            .progress(pb::Empty {})
            .await
            .context("Release.Progress RPC")?
            .into_inner();
        while let Some(ev) = stream.message().await.context("progress stream")? {
            if let Some(live) = to_live(ev) {
                on_event(live);
            }
        }
        Ok(())
    })
}

/// List every warehouse table the server owns (the `Warehouse.Tables` RPC) —
/// the remote counterpart to `IcebergWarehouse::table_names`.
pub fn fetch_tables(endpoint: &str, token: &str, workspace: &str) -> Result<Vec<String>> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz client")?;
    rt.block_on(async {
        let (endpoint, bearer) = endpoint_and_bearer(endpoint, token)?;
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let ws_md = ws_header(workspace);
        let mut client = pb::warehouse_client::WarehouseClient::with_interceptor(
            channel,
            move |mut req: tonic::Request<()>| {
                req.metadata_mut().insert("authorization", bearer.clone());
                if let Some(ws) = &ws_md {
                    req.metadata_mut().insert("nornir-workspace", ws.clone());
                }
                Ok(req)
            },
        );
        let resp = client.tables(pb::Empty {}).await.context("Warehouse.Tables RPC")?.into_inner();
        Ok(resp.names)
    })
}

/// Scan one warehouse table for display (the `Warehouse.Scan` RPC) — the remote
/// counterpart to `IcebergWarehouse::scan_preview`. `limit` 0 = server default.
pub fn scan_table(endpoint: &str, token: &str, table: &str, limit: u32, workspace: &str) -> Result<TablePreview> {
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz client")?;
    rt.block_on(async {
        let (endpoint, bearer) = endpoint_and_bearer(endpoint, token)?;
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let ws_md = ws_header(workspace);
        let mut client = pb::warehouse_client::WarehouseClient::with_interceptor(
            channel,
            move |mut req: tonic::Request<()>| {
                req.metadata_mut().insert("authorization", bearer.clone());
                if let Some(ws) = &ws_md {
                    req.metadata_mut().insert("nornir-workspace", ws.clone());
                }
                Ok(req)
            },
        );
        let resp = client
            .scan(pb::WarehouseScanRequest { table: table.to_string(), limit })
            .await
            .context("Warehouse.Scan RPC")?
            .into_inner();
        Ok(TablePreview {
            columns: resp.columns,
            rows: resp.rows.into_iter().map(|r| r.cells).collect(),
        })
    })
}

// ── shared connect helper + reusable interceptor ────────────────────────────

/// Bearer + optional `nornir-workspace` header, reusable across every generated
/// client (so the new RPC wrappers below don't each re-inline the closure).
#[derive(Clone)]
pub(crate) struct Auth {
    bearer: tonic::metadata::MetadataValue<tonic::metadata::Ascii>,
    ws: Option<tonic::metadata::MetadataValue<tonic::metadata::Ascii>>,
}
impl tonic::service::Interceptor for Auth {
    fn call(&mut self, mut req: tonic::Request<()>) -> Result<tonic::Request<()>, tonic::Status> {
        req.metadata_mut().insert("authorization", self.bearer.clone());
        if let Some(ws) = &self.ws {
            req.metadata_mut().insert("nornir-workspace", ws.clone());
        }
        Ok(req)
    }
}

/// Run one blocking gRPC call on a private current-thread runtime: connect to
/// `endpoint`, build the [`Auth`] interceptor (bearer + `workspace` header), and
/// hand `(channel, auth)` to `f`. Keeps the egui loop synchronous.
fn call<T, F, Fut>(endpoint: &str, token: &str, workspace: &str, f: F) -> Result<T>
where
    F: FnOnce(tonic::transport::Channel, Auth) -> Fut,
    Fut: std::future::Future<Output = Result<T>>,
{
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .context("build tokio runtime for viz client")?;
    rt.block_on(async {
        let (endpoint, bearer) = endpoint_and_bearer(endpoint, token)?;
        let channel = tonic::transport::Channel::from_shared(endpoint.clone())
            .with_context(|| format!("invalid server url `{endpoint}`"))?
            .connect()
            .await
            .with_context(|| format!("connect to nornir-server at {endpoint}"))?;
        let auth = Auth { bearer, ws: ws_header(workspace) };
        f(channel, auth).await
    })
}

// ── plain view structs (UI consumes these, not the pb types) ─────────────────

/// Workspace info for the picker's side panel (`Workspaces.Get`).
#[derive(Clone, Debug, Default)]
pub struct WorkspaceInfo {
    pub name: String,
    pub mode: String,
    pub poll: String,
    pub current_snapshot: String,
    pub updated_at: String,
    /// `(member, source/sha summary)` pairs.
    pub members: Vec<(String, String)>,
    /// AUT6 working-tree freshness per member: `(member, dirty, digest)`. The
    /// SHA in the summary above is committed state only; this reports whether the
    /// server's clone has uncommitted changes. Exposed in `state_json`.
    pub freshness: Vec<(String, bool, String)>,
}

/// One search hit (`Search.Query`).
#[derive(Clone, Debug)]
pub struct Hit {
    pub corpus: String,
    pub repo: String,
    pub path: String,
    pub score: f32,
    pub title: String,
    pub snippet: String,
}

/// One symbol (`Knowledge.SymbolLookup`).
#[derive(Clone, Debug)]
pub struct KnownSym {
    pub crate_name: String,
    pub item_kind: String,
    pub item_name: String,
    pub visibility: String,
    pub file: String,
    pub line: u32,
    pub signature: String,
}

/// Release-gate outcome for a repo (`Release.GateAll`).
#[derive(Clone, Debug, Default)]
pub struct GateReport {
    pub repo: String,
    pub passed: Vec<String>,
    pub failed: Vec<(String, String)>,
}

/// One bench metric series point for charting (`Bench.History`).
#[derive(Clone, Debug)]
pub struct BenchPoint {
    pub date: String,
    pub version: String,
    pub metric: String,
    pub value: f64,
}

/// Server identity returned by `Health.Ping` — surfaced in the About popup so a
/// remote viz shows the *server's* version next to the client's.
#[derive(Clone, Debug, Default)]
pub struct ServerInfo {
    pub status: String,
    pub version: String,
    pub repo_count: u32,
}

/// `Health.Ping` — the server's version + status + loaded-repo count. Cheap, no
/// workspace scope. Powers the About popup's "server vX" line.
pub fn ping(endpoint: &str, token: &str) -> Result<ServerInfo> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::health_client::HealthClient::with_interceptor(channel, auth);
        let r = c.ping(pb::Empty {}).await.context("Health.Ping RPC")?.into_inner();
        Ok(ServerInfo {
            status: r.status,
            version: r.version,
            repo_count: r.repo_count,
        })
    })
}

// ── new clickable-surface RPC wrappers ───────────────────────────────────────

/// `Workspaces.Get` — the info-panel backing call for the picker selection.
pub fn get_workspace(endpoint: &str, token: &str, name: &str) -> Result<WorkspaceInfo> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::workspaces_client::WorkspacesClient::with_interceptor(channel, auth);
        let r = c
            .get(pb::WorkspaceName { name: name.to_string() })
            .await
            .context("Workspaces.Get RPC")?
            .into_inner();
        Ok(WorkspaceInfo {
            name: r.name,
            mode: r.mode,
            poll: r.poll,
            current_snapshot: r.current_snapshot,
            updated_at: r.updated_at,
            freshness: r
                .members
                .iter()
                .map(|m| (m.name.clone(), m.worktree_dirty, m.worktree_digest.clone()))
                .collect(),
            members: r
                .members
                .into_iter()
                .map(|m| {
                    // Char-boundary safe slice: a non-ASCII / placeholder sha
                    // would panic on a raw `&..[..8]` byte index.
                    let sha = match m.last_seen_sha.char_indices().nth(8) {
                        Some((byte_idx, _)) => &m.last_seen_sha[..byte_idx],
                        None => &m.last_seen_sha,
                    };
                    // AUT6 staleness marker: a dirty server clone is advisory —
                    // the warehouse was indexed from committed state only.
                    let fresh = if m.worktree_dirty { " ⚠ uncommitted" } else { "" };
                    (m.name, format!("{} @ {sha} [{}]{fresh}", m.remote, m.sync_state))
                })
                .collect(),
        })
    })
}

/// `Workspaces.Fetch` — the "⟳ Sync now" button. Returns `(fetched, changed, errors)`.
/// `Workspaces.Fetch` — poll the remote(s) now. `force` republishes the
/// warehouse even when no git member changed (e.g. it was cleared). Returns
/// (fetched, changed, errors, snapshot).
pub fn fetch_workspace(
    endpoint: &str,
    token: &str,
    name: &str,
    force: bool,
) -> Result<(u32, Vec<String>, Vec<String>, String)> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::workspaces_client::WorkspacesClient::with_interceptor(channel, auth);
        let r = c
            .fetch(pb::WorkspaceFetchRequest { name: name.to_string(), force, background: false })
            .await
            .context("Workspaces.Fetch RPC")?
            .into_inner();
        Ok((r.fetched, r.changed, r.errors, r.snapshot))
    })
}

/// `Workspaces.Register` — add (and EAGER-populate) a workspace. `mode` is one of
/// `monitored` | `pushed` | `external` (default pushed); `descriptor` is the
/// server-readable `nornir-workspace.toml` path/URL for a monitored workspace.
/// Returns the registered workspace's `(name, mode, member_count)`. The viz "Add
/// workspace" button calls this; CLI parity = `nornir workspace add`.
pub fn register_workspace(
    endpoint: &str,
    token: &str,
    name: &str,
    descriptor: &str,
    mode: &str,
    poll: &str,
) -> Result<(String, String, usize)> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::workspaces_client::WorkspacesClient::with_interceptor(channel, auth);
        let r = c
            .register(pb::RegisterWorkspaceRequest {
                name: name.to_string(),
                descriptor: descriptor.to_string(),
                mode: mode.to_string(),
                poll: poll.to_string(),
                lazy: false,
            })
            .await
            .context("Workspaces.Register RPC")?
            .into_inner();
        Ok((r.name, r.mode, r.members.len()))
    })
}

/// `Workspaces.Remove` — kill (de-register) a workspace. The viz "Kill workspace"
/// button (behind a confirm) calls this; CLI parity = `nornir workspace rm`.
pub fn remove_workspace(endpoint: &str, token: &str, name: &str) -> Result<()> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::workspaces_client::WorkspacesClient::with_interceptor(channel, auth);
        c.remove(pb::WorkspaceName { name: name.to_string() })
            .await
            .context("Workspaces.Remove RPC")?;
        Ok(())
    })
}

/// The common outcome of an `Ops.*` heavy run: overall verdict + the CLI-parity
/// summary line + per-target rows + the warehouse run id the rows landed under.
#[derive(Clone, Debug, Default)]
pub struct OpRunResult {
    pub ok: bool,
    pub summary: String,
    /// `(target, status, message)` per repo/target.
    pub targets: Vec<(String, String, String)>,
    pub run_id: String,
}

fn op_result_from(r: pb::RunOpResult) -> OpRunResult {
    OpRunResult {
        ok: r.ok,
        summary: r.summary,
        targets: r.targets.into_iter().map(|t| (t.name, t.status, t.message)).collect(),
        run_id: r.run_id,
    }
}

/// `Ops.RunTestMatrix` — run the test matrix server-side over the workspace's
/// checkouts and persist `test_results`. `repo` empty = the FULL matrix (heavy);
/// `aspects` empty = the default set. The 🧪 Test pane's "Run matrix" button calls
/// this; CLI parity = `nornir test all` (client mode) / `nornir test run <repo>`.
pub fn run_test_matrix(
    endpoint: &str,
    token: &str,
    repo: &str,
    aspects: &str,
    workspace: &str,
) -> Result<OpRunResult> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::ops_client::OpsClient::with_interceptor(channel, auth);
        let r = c
            .run_test_matrix(pb::RunTestMatrixRequest {
                repo: repo.to_string(),
                aspects: aspects.to_string(),
            })
            .await
            .context("Ops.RunTestMatrix RPC")?
            .into_inner();
        Ok(op_result_from(r))
    })
}

/// `Ops.RunBench` — run the benches server-side for `repo` (empty = primary) and
/// persist a `BenchRun`. The 📈 Bench pane's "Run bencher" button calls this; CLI
/// parity = `nornir bench run <repo>`.
pub fn run_bench(endpoint: &str, token: &str, repo: &str, workspace: &str) -> Result<OpRunResult> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::ops_client::OpsClient::with_interceptor(channel, auth);
        let r = c
            .run_bench(pb::RunBenchRequest { repo: repo.to_string() })
            .await
            .context("Ops.RunBench RPC")?
            .into_inner();
        Ok(op_result_from(r))
    })
}

/// `Ops.RunRelease` — run the release-grade heavy gate across the build order and
/// persist `release_events`. The 🚀 Release pane's "Release (heavy gate)" button
/// calls this; CLI parity = `nornir release gate all` / `nornir release run`.
pub fn run_release(endpoint: &str, token: &str, repo: &str, workspace: &str) -> Result<OpRunResult> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::ops_client::OpsClient::with_interceptor(channel, auth);
        let r = c
            .run_release(pb::RunReleaseRequest { repo: repo.to_string() })
            .await
            .context("Ops.RunRelease RPC")?
            .into_inner();
        Ok(op_result_from(r))
    })
}

/// `Workspaces.Fetch{background=true}` — the **Populate** path: clone members
/// now and return right after the (fast) clone, letting the server's poll loop
/// build the warehouse async (single-writer safe). Returns
/// `(fetched, changed, errors, snapshot)`; snapshot is empty (build is deferred).
/// CLI parity = `nornir workspace populate`.
pub fn populate_workspace(
    endpoint: &str,
    token: &str,
    name: &str,
) -> Result<(u32, Vec<String>, Vec<String>, String)> {
    call(endpoint, token, "", |channel, auth| async move {
        let mut c = pb::workspaces_client::WorkspacesClient::with_interceptor(channel, auth);
        let r = c
            .fetch(pb::WorkspaceFetchRequest { name: name.to_string(), force: false, background: true })
            .await
            .context("Workspaces.Fetch(background) RPC")?
            .into_inner();
        Ok((r.fetched, r.changed, r.errors, r.snapshot))
    })
}

/// `Search.Query` — BM25 over the Tantivy corpora. `corpus`/`repo` empty = all.
pub fn search(
    endpoint: &str,
    token: &str,
    query: &str,
    corpus: &str,
    repo: &str,
    limit: u32,
    workspace: &str,
) -> Result<Vec<Hit>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::search_client::SearchClient::with_interceptor(channel, auth);
        let r = c
            .query(pb::SearchRequest {
                query: query.to_string(),
                corpus: corpus.to_string(),
                repo: repo.to_string(),
                limit,
            })
            .await
            .context("Search.Query RPC")?
            .into_inner();
        Ok(r.hits
            .into_iter()
            .map(|h| Hit {
                corpus: h.corpus,
                repo: h.repo,
                path: h.path,
                score: h.score,
                title: h.title,
                snippet: h.snippet,
            })
            .collect())
    })
}

/// `Knowledge.SymbolLookup` — item-name substring search over `symbol_facts`.
pub fn knowledge_lookup(
    endpoint: &str,
    token: &str,
    repo: &str,
    arg: &str,
    limit: u32,
    workspace: &str,
) -> Result<Vec<KnownSym>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, auth);
        let r = c
            .symbol_lookup(pb::KnowledgeSymbolQuery {
                repo: repo.to_string(),
                arg: arg.to_string(),
                limit,
            })
            .await
            .context("Knowledge.SymbolLookup RPC")?
            .into_inner();
        Ok(r.symbols
            .into_iter()
            .map(|s| KnownSym {
                crate_name: s.crate_name,
                item_kind: s.item_kind,
                item_name: s.item_name,
                visibility: s.visibility,
                file: s.file,
                line: s.line,
                signature: s.signature,
            })
            .collect())
    })
}

/// `Release.GateAll` — run every release gate for `repo`, pass/fail split.
pub fn gate_all(endpoint: &str, token: &str, repo: &str, workspace: &str) -> Result<GateReport> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, auth);
        let r = c
            .gate_all(pb::RepoOnly { repo: repo.to_string() })
            .await
            .context("Release.GateAll RPC")?
            .into_inner();
        Ok(GateReport {
            repo: r.repo,
            passed: r.passed,
            failed: r.failed.into_iter().map(|f| (f.name, f.error)).collect(),
        })
    })
}

/// `Mimir.SecurityScan` — server-side SBOM + vuln + license scan of `repo`
/// (scans the monitored `git/<repo>` checkout). Returns the raw JSON; the
/// Security tab parses it. No sources needed on the viz host.
pub fn security_scan(endpoint: &str, token: &str, repo: &str, workspace: &str) -> Result<String> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, auth);
        let r = c
            .security_scan(pb::RepoOnly { repo: repo.to_string() })
            .await
            .context("Mimir.SecurityScan RPC")?
            .into_inner();
        Ok(r.json)
    })
}

/// `Mimir.DepsOf` — repos `repo` depends on, as raw JSON. Server resolves the
/// graph from the checkout descriptor OR (monitored workspaces like njord) the
/// warehouse's `dep_graph_edges`. Lets a test assert njord's dep-graph resolves.
pub fn mimir_deps_of(
    endpoint: &str,
    token: &str,
    repo: &str,
    workspace: &str,
    transitive: bool,
) -> Result<String> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::mimir_client::MimirClient::with_interceptor(channel, auth);
        let r = c
            .deps_of(pb::DepQuery { repo: repo.to_string(), transitive })
            .await
            .context("Mimir.DepsOf RPC")?
            .into_inner();
        Ok(r.json)
    })
}

/// `Release.Trace` — regression time-bisect JSON for `repo` (raw, UI pretty-prints).
pub fn trace(
    endpoint: &str,
    token: &str,
    repo: &str,
    workspace: &str,
) -> Result<String> {
    let ws = workspace.to_string();
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::release_client::ReleaseClient::with_interceptor(channel, auth);
        let r = c
            .trace(pb::TraceQuery { repo: repo.to_string(), workspace: ws })
            .await
            .context("Release.Trace RPC")?
            .into_inner();
        Ok(r.json)
    })
}

/// `Bench.History` — flatten every run's metrics into chartable points.
pub fn bench_history(
    endpoint: &str,
    token: &str,
    repo: &str,
    workspace: &str,
) -> Result<Vec<BenchPoint>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::bench_client::BenchClient::with_interceptor(channel, auth);
        let r = c
            .history(pb::RepoOnly { repo: repo.to_string() })
            .await
            .context("Bench.History RPC")?
            .into_inner();
        let mut pts = Vec::new();
        for run in r.runs {
            for res in run.results {
                for kvf in res.metrics {
                    pts.push(BenchPoint {
                        date: run.date.clone(),
                        version: run.version.clone(),
                        metric: format!("{}::{}", res.name, kvf.key),
                        value: kvf.value,
                    });
                }
            }
        }
        Ok(pts)
    })
}

/// One semantic-search hit (`Vector.Search`).
#[derive(Clone, Debug)]
pub struct VecHit {
    pub score: f64,
    pub file: String,
    pub start_line: u64,
    pub end_line: u64,
}

/// `Vector.Search` — GPU/CPU semantic search over a repo's embedded snapshot.
/// `repo` required; `sha` empty = latest. Returns hits or a clear error (the
/// server replies UNIMPLEMENTED when built without an embedder).
pub fn vector_search(
    endpoint: &str,
    token: &str,
    repo: &str,
    query: &str,
    limit: u32,
    workspace: &str,
) -> Result<Vec<VecHit>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::vector_client::VectorClient::with_interceptor(channel, auth);
        let r = c
            .search(pb::VectorSearchRequest {
                repo: repo.to_string(),
                query: query.to_string(),
                sha: String::new(),
                limit,
            })
            .await
            .context("Vector.Search RPC")?
            .into_inner();
        let v: serde_json::Value =
            serde_json::from_str(&r.json).context("decode vector hits json")?;
        let hits = v
            .get("hits")
            .and_then(|h| h.as_array())
            .map(|arr| {
                arr.iter()
                    .map(|h| VecHit {
                        score: h.get("score").and_then(|x| x.as_f64()).unwrap_or(0.0),
                        file: h.get("file").and_then(|x| x.as_str()).unwrap_or("").to_string(),
                        start_line: h.get("start_line").and_then(|x| x.as_u64()).unwrap_or(0),
                        end_line: h.get("end_line").and_then(|x| x.as_u64()).unwrap_or(0),
                    })
                    .collect()
            })
            .unwrap_or_default();
        Ok(hits)
    })
}

/// `Index.Stats` — `(total_docs, per-corpus counts)` for the search status panel.
pub fn index_stats(endpoint: &str, token: &str, workspace: &str) -> Result<(u64, Vec<(String, String)>)> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::index_client::IndexClient::with_interceptor(channel, auth);
        let r = c.stats(pb::Empty {}).await.context("Index.Stats RPC")?.into_inner();
        Ok((r.total, r.by_corpus.into_iter().map(|kv| (kv.key, kv.value)).collect()))
    })
}

/// `Knowledge.Callers` / `Callees` — who-calls / who-is-called-by `name`.
/// `callers = true` → Callers, else Callees. Returns `(caller_path, callee_ident,
/// file, line)` rows.
pub fn knowledge_calls(
    endpoint: &str,
    token: &str,
    repo: &str,
    name: &str,
    callers: bool,
    limit: u32,
    workspace: &str,
) -> Result<Vec<(String, String, String, u32)>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, auth);
        let q = pb::KnowledgeCallQuery { repo: repo.to_string(), name: name.to_string(), limit };
        let calls = if callers {
            c.callers(q).await.context("Knowledge.Callers RPC")?
        } else {
            c.callees(q).await.context("Knowledge.Callees RPC")?
        }
        .into_inner()
        .calls;
        Ok(calls.into_iter().map(|k| (k.caller_path, k.callee_ident, k.file, k.line)).collect())
    })
}

/// `Knowledge.CallPath` — a call path from `from` to `to` (empty = none found).
pub fn knowledge_call_path(
    endpoint: &str,
    token: &str,
    repo: &str,
    from: &str,
    to: &str,
    workspace: &str,
) -> Result<Vec<String>> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::knowledge_client::KnowledgeClient::with_interceptor(channel, auth);
        let r = c
            .call_path(pb::KnowledgeCallPathQuery {
                repo: repo.to_string(),
                from: from.to_string(),
                to: to.to_string(),
            })
            .await
            .context("Knowledge.CallPath RPC")?
            .into_inner();
        Ok(r.names)
    })
}

/// `Funnel.Show` — the whole idea→plan funnel, flattened into a render-ready
/// [`FunnelView`]. The `FunnelDump` already carries per-node `deps`, so the
/// DAG is fully reconstructable without any extra RPC.
pub fn funnel_show(
    endpoint: &str,
    token: &str,
    workspace: &str,
) -> Result<super::funnel_view::FunnelView> {
    use super::funnel_view::{FunnelView, NodeStat, NodeView, PlanView};
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, auth);
        let dump = c.show(pb::Empty {}).await.context("Funnel.Show RPC")?.into_inner();
        let mut plans = Vec::new();
        for idea in dump.ideas {
            for plan in idea.plans {
                let nodes = plan
                    .nodes
                    .into_iter()
                    .map(|n| NodeView {
                        id: n.id,
                        kind: n.kind,
                        title: n.title,
                        status: NodeStat::parse(&n.status),
                        targets: Vec::new(), // FunnelDumpNode carries no targets
                        deps: n.deps,
                    })
                    .collect();
                plans.push(PlanView {
                    id: plan.id,
                    summary: plan.summary,
                    status: plan.status.to_ascii_lowercase(),
                    idea_text: idea.text.clone(),
                    nodes,
                });
            }
        }
        plans.sort_by(|a, b| a.id.cmp(&b.id));
        Ok(FunnelView { plans })
    })
}

/// FI1 — paste an idea/error into the server's funnel (`Funnel.SubmitIdea`).
/// `item_kind` is `"idea"` or `"error"` (empty ⇒ idea). Returns the new item id.
pub fn funnel_submit(
    endpoint: &str,
    token: &str,
    workspace: &str,
    text: &str,
    item_kind: &str,
    source: &str,
) -> Result<String> {
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, auth);
        let r = c
            .submit_idea(pb::SubmitIdeaRequest {
                text: text.to_string(),
                source: source.to_string(),
                item_kind: item_kind.to_string(),
            })
            .await
            .context("Funnel.SubmitIdea RPC")?
            .into_inner();
        Ok(r.id)
    })
}

/// FI2 — fetch the server-side intake history (`Funnel.History`), newest-first,
/// optionally filtered by kind/status (empty = no filter).
pub fn funnel_history(
    endpoint: &str,
    token: &str,
    workspace: &str,
    kind: &str,
    status: &str,
) -> Result<Vec<super::funnel_view::HistoryItemView>> {
    use super::funnel_view::HistoryItemView;
    call(endpoint, token, workspace, |channel, auth| async move {
        let mut c = pb::funnel_client::FunnelClient::with_interceptor(channel, auth);
        let resp = c
            .history(pb::FunnelHistoryRequest {
                kind: kind.to_string(),
                status: status.to_string(),
                limit: 0,
            })
            .await
            .context("Funnel.History RPC")?
            .into_inner();
        Ok(resp
            .items
            .into_iter()
            .map(|it| HistoryItemView {
                id: it.id,
                item_kind: it.item_kind,
                text: it.text,
                source: it.source,
                submitted_at: it.submitted_at,
                status: it.status,
                plan_ids: it.plan_ids,
            })
            .collect())
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    /// Live smoke against `$NORNIR_SERVER` (+ `$NORNIR_SERVER_TOKEN`). Ignored by
    /// default (needs a running server). Run with:
    ///   NORNIR_SERVER=http://oden:7878 NORNIR_SERVER_TOKEN=… \
    ///     cargo test --features viz --lib viz::remote::tests -- --ignored --nocapture
    #[test]
    #[ignore]
    fn live_list_workspaces() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = list_workspaces(&ep, &tok).expect("list_workspaces should succeed");
        eprintln!("live workspaces: {ws:?}");
        assert!(!ws.is_empty(), "server returned no workspaces");
    }

    /// Wire-contract test for `Viz.ReleaseEvents`: the server serializes
    /// `Vec<ReleaseEventRow>` exactly as `nornir-server`'s `release_events`
    /// handler does (`serde_json::to_string(&rows)`); the client's
    /// `fetch_release_events` decodes the response JSON with
    /// `serde_json::from_str`. This asserts that round-trip preserves EVERY field
    /// (so the remote Release tab renders the identical rows) — LAW: real data in,
    /// real rows out, not just "didn't panic".
    #[test]
    fn release_events_wire_roundtrip() {
        use crate::warehouse::release_events::{status, ReleaseEventRow};
        let rows = vec![
            ReleaseEventRow {
                run_id: "run-42".into(),
                seq: 0,
                ts_micros: 1_000,
                component: "znippy".into(),
                repo: "znippy".into(),
                op: "test".into(),
                phase: "start".into(),
                status: status::RUNNING.into(),
                detail: String::new(),
                depends_on: Some(vec![]),
                elapsed_ms: None,
            },
            ReleaseEventRow {
                run_id: "run-42".into(),
                seq: 1,
                ts_micros: 2_000,
                component: "holger".into(),
                repo: "holger".into(),
                op: "gate".into(),
                phase: "end".into(),
                status: status::OK.into(),
                detail: "all gates green".into(),
                depends_on: Some(vec!["znippy".into()]),
                elapsed_ms: Some(1234),
            },
        ];
        // Server side: exactly what the handler emits.
        let json = serde_json::to_string(&rows).unwrap();
        // Client side: exactly what fetch_release_events decodes.
        let back: Vec<ReleaseEventRow> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, rows, "release_events wire round-trip must be lossless");
        // And the non-empty content is preserved (real values asserted).
        assert_eq!(back[1].depends_on.as_deref(), Some(&["znippy".to_string()][..]));
        assert_eq!(back[1].elapsed_ms, Some(1234));
        assert_eq!(back[1].detail, "all gates green");
    }

    /// Wire-contract test for `Viz.TestResults`: the server serializes
    /// `Vec<TestResultRow>` exactly as `nornir-server`'s `test_results` handler
    /// does (`serde_json::to_string(&rows)`); the client's `fetch_test_results`
    /// decodes the response JSON with `serde_json::from_str`. This asserts that
    /// the round-trip preserves EVERY field so the remote 🧪 Test tab renders
    /// the identical matrix — LAW: real data in, real rows out, not just "didn't panic".
    #[test]
    fn test_results_wire_roundtrip() {
        use crate::warehouse::test_results::{status, TestResultRow};
        let rows = vec![
            TestResultRow {
                run_id: "run-t1".into(),
                ts_micros: 1_000,
                repo: "znippy".into(),
                suite: "unit".into(),
                test_name: "compress_roundtrip".into(),
                status: status::PASS.into(),
                duration_ms: 12.0,
                message: String::new(),
                aspect: "unit".into(),
                metric: 0.0,
            },
            TestResultRow {
                run_id: "run-t1".into(),
                ts_micros: 2_000,
                repo: "znippy".into(),
                suite: "clippy".into(),
                test_name: "clippy::all".into(),
                status: status::FAIL.into(),
                duration_ms: 88.0,
                message: "error[E0277]: ...".into(),
                aspect: "clippy".into(),
                metric: 3.0,
            },
        ];
        // Server side: exactly what the handler emits.
        let json = serde_json::to_string(&rows).unwrap();
        // Client side: exactly what fetch_test_results decodes.
        let back: Vec<TestResultRow> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, rows, "test_results wire round-trip must be lossless");
        assert_eq!(back[0].status, status::PASS);
        assert_eq!(back[0].duration_ms, 12.0);
        assert_eq!(back[1].status, status::FAIL);
        assert_eq!(back[1].message, "error[E0277]: ...");
        assert_eq!(back[1].metric, 3.0);
    }

    /// Wire-contract test for `Viz.TestMatrix`: the server serializes
    /// `{inventory:[TestInventoryRow], results:[TestResultRow]}` exactly as
    /// `nornir-server`'s `test_matrix` handler does; `fetch_test_matrix` decodes
    /// both arrays. Then `join_matrix` must yield the identical ok|fail|X matrix
    /// on the thin client as it would locally — so the remote 🧪 Test pane shows
    /// the same tri-state. LAW: real data in, the JOINED matrix out.
    #[test]
    fn test_matrix_wire_roundtrip_and_join() {
        use crate::warehouse::test_inventory::{join_matrix, TestInventoryRow};
        use crate::warehouse::test_results::{status, TestResultRow};
        let inventory = vec![
            TestInventoryRow {
                repo: "nornir".into(), crate_name: "nornir".into(),
                module_path: "nornir::tests".into(), test_name: "passes".into(),
                file: "src/lib.rs".into(), line: 1, is_heavy: false, is_async: false,
            },
            TestInventoryRow {
                repo: "nornir".into(), crate_name: "nornir".into(),
                module_path: "nornir::tests".into(), test_name: "heavy_one".into(),
                file: "src/lib.rs".into(), line: 9, is_heavy: true, is_async: true,
            },
        ];
        let results = vec![TestResultRow::unit(
            "r", "nornir", "nornir", "passes", status::PASS, 1.0, 100, "",
        )];
        // Server side: exactly what the test_matrix handler emits.
        let json = serde_json::json!({ "inventory": inventory, "results": results }).to_string();
        // Client side: exactly what fetch_test_matrix decodes.
        #[derive(serde::Deserialize)]
        struct Resp {
            inventory: Vec<TestInventoryRow>,
            results: Vec<TestResultRow>,
        }
        let resp: Resp = serde_json::from_str(&json).unwrap();
        assert_eq!(resp.inventory, inventory, "inventory round-trips losslessly");
        assert_eq!(resp.results, results, "results round-trip losslessly");

        // The thin client joins → the identical tri-state matrix.
        let m = join_matrix(&resp.inventory, &resp.results);
        let by = |n: &str| m.iter().find(|r| r.test_name == n).unwrap();
        assert_eq!(by("passes").state, "ok", "ran + passed → ok");
        assert_eq!(by("heavy_one").state, "X", "discovered, never run → X");
        assert!(by("heavy_one").is_heavy, "heavy flag survives the wire + join");
    }

    /// Wire-contract test for `Viz.BenchTelemetry`: the server serializes the two
    /// tables as `{telemetry:[BenchTelemetryRow], runs:[BenchRun]}` exactly as
    /// `nornir-server`'s `bench_telemetry` handler does; the client's
    /// `fetch_bench_live` decodes both arrays back out. This asserts the round-trip
    /// preserves EVERY field of BOTH tables so the remote 📡 Bench LIVE panel folds
    /// identically to embedded — LAW: real data in, real rows out.
    #[test]
    fn bench_telemetry_wire_roundtrip() {
        use crate::bench::{BenchRun, TestOutcome};
        use crate::warehouse::iceberg::BenchTelemetryRow;
        let telemetry = vec![BenchTelemetryRow {
            run_id: "run-b1".into(),
            repo: "znippy".into(),
            bench: "znippy.compress".into(),
            n_cores: 8,
            cpu_pct_avg: 51.5,
            cpu_pct_max: 92.0,
            cores_busy_avg: 6.5,
            cores_busy_max: 8,
            mem_peak_mb: 256.0,
            mem_pct_max: 30.0,
            elapsed_ms: 1234.0,
        }];
        let runs = vec![BenchRun {
            date: "2026-06-14".into(),
            timestamp: None,
            version: "1.0".into(),
            machine: "host".into(),
            cores: 8,
            results: Vec::new(),
            tests: vec![TestOutcome {
                name: "compress".into(),
                passed: false,
                duration_ms: Some(12.0),
                message: None,
            }],
        }];
        // Server side: exactly what the handler emits.
        let json = serde_json::json!({ "telemetry": telemetry, "runs": runs }).to_string();
        // Client side: exactly what fetch_bench_live decodes.
        let v: serde_json::Value = serde_json::from_str(&json).unwrap();
        let back_telem: Vec<BenchTelemetryRow> =
            serde_json::from_value(v.get("telemetry").cloned().unwrap()).unwrap();
        let back_runs: Vec<BenchRun> =
            serde_json::from_value(v.get("runs").cloned().unwrap()).unwrap();
        assert_eq!(back_telem, telemetry, "bench_telemetry wire round-trip must be lossless");
        // Real field values from the telemetry table.
        assert_eq!(back_telem[0].bench, "znippy.compress");
        assert_eq!(back_telem[0].n_cores, 8);
        assert_eq!(back_telem[0].cores_busy_max, 8);
        assert!((back_telem[0].cores_busy_avg - 6.5).abs() < 1e-9);
        assert!((back_telem[0].mem_peak_mb - 256.0).abs() < 1e-9);
        // Real field values from the runs table (BenchRun has no PartialEq).
        assert_eq!(back_runs.len(), 1);
        assert_eq!(back_runs[0].date, "2026-06-14");
        assert_eq!(back_runs[0].cores, 8);
        assert_eq!(back_runs[0].tests.len(), 1);
        assert_eq!(back_runs[0].tests[0].name, "compress");
        assert!(!back_runs[0].tests[0].passed, "failed test survives the wire");
    }

    /// Wire-contract test for `Viz.BakeoffResults`: same round-trip discipline for
    /// `Vec<AgentModelRunRow>` — every metric field must survive so the remote
    /// Leaderboard ranks identically to embedded.
    #[test]
    fn bakeoff_results_wire_roundtrip() {
        use crate::warehouse::agent_model_runs::AgentModelRunRow;
        let rows = vec![AgentModelRunRow {
            run_id: "bake-1".into(),
            ts_micros: 9_000,
            agent: "claude".into(),
            model: "mistral".into(),
            prompt_id: "p-sum".into(),
            prompt: "summarize".into(),
            output: "ok".into(),
            latency_ms: 120.5,
            tokens_in: 10,
            tokens_out: 42,
            tokens_per_s: 88.3,
            score: 0.91,
            ok: true,
            error: None,
            cost_usd: 0.0123,
            mcp_tool_calls: 5,
        }];
        let json = serde_json::to_string(&rows).unwrap();
        let back: Vec<AgentModelRunRow> = serde_json::from_str(&json).unwrap();
        assert_eq!(back, rows, "bakeoff wire round-trip must be lossless");
        assert_eq!(back[0].tokens_per_s, 88.3);
        assert_eq!(back[0].score, 0.91);
        // The matrix axis + economics survive the wire (so the remote grid renders).
        assert_eq!(back[0].agent, "claude");
        assert_eq!(back[0].cost_usd, 0.0123);
        assert_eq!(back[0].mcp_tool_calls, 5);

        // A pre-matrix server's JSON (no agent/cost/mcp fields) still decodes,
        // defaulting the agent to AGENT_UNSET (serde defaults).
        let legacy = r#"[{"run_id":"r","ts_micros":1,"model":"m","prompt_id":"p","prompt":"q","output":"o","latency_ms":1.0,"tokens_in":1,"tokens_out":1,"tokens_per_s":1.0,"score":0.5,"ok":true,"error":null}]"#;
        let decoded: Vec<AgentModelRunRow> = serde_json::from_str(legacy).unwrap();
        assert_eq!(decoded[0].agent, "-", "legacy row defaults agent to AGENT_UNSET");
        assert_eq!(decoded[0].cost_usd, 0.0);
        assert_eq!(decoded[0].mcp_tool_calls, 0);
    }

    /// Wire-contract test for `Viz.Knowledge`: the server builds the summary with
    /// `scan_summary_json`; the client decodes it into a `KnowledgeSummary`. Assert
    /// the bubbles + per-repo rollups survive (so the remote map renders crates>0).
    #[test]
    fn knowledge_summary_wire_roundtrip() {
        use super::super::knowledge::{Bubble, KnowledgeSummary, RepoScanSummary};
        let summary = KnowledgeSummary {
            repos: vec![RepoScanSummary {
                repo: "znippy".into(),
                ok: true,
                symbols: 120,
                calls: 88,
                features: 3,
                git_files: 40,
                error: None,
            }],
            crates: vec![Bubble {
                repo: "znippy".into(),
                krate: "znippy".into(),
                symbols: 120,
                calls: 88,
                files: 40,
                gates: 3,
                heat_30d: 7,
            }],
        };
        let json = serde_json::to_string(&summary).unwrap();
        let back: KnowledgeSummary = serde_json::from_str(&json).unwrap();
        assert_eq!(back.crates.len(), 1);
        assert_eq!(back.crates[0].symbols, 120);
        assert_eq!(back.repos[0].calls, 88);
        assert!(back.repos[0].ok);
    }

    /// Live `Viz.ReleaseEvents` smoke for a workspace (default `holger`). Ignored
    /// (needs a running server). Asserts the remote Release tab would have rows.
    #[test]
    #[ignore]
    fn live_release_events() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = std::env::var("NORNIR_WS").unwrap_or_else(|_| "holger".into());
        let rows = fetch_release_events(&ep, &tok, &ws).expect("fetch_release_events");
        eprintln!("live release_events ws={ws}: {} rows", rows.len());
    }

    /// Live `Viz.BakeoffResults` smoke (ignored).
    #[test]
    #[ignore]
    fn live_bakeoff_results() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = std::env::var("NORNIR_WS").unwrap_or_else(|_| "holger".into());
        let rows = fetch_bakeoff_results(&ep, &tok, &ws).expect("fetch_bakeoff_results");
        eprintln!("live agent_model_runs ws={ws}: {} rows", rows.len());
    }

    /// Live `Viz.Knowledge` smoke (ignored) — the server-side scan summary.
    #[test]
    #[ignore]
    fn live_knowledge_summary() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = std::env::var("NORNIR_WS").unwrap_or_else(|_| "holger".into());
        let s = knowledge_summary(&ep, &tok, &ws).expect("knowledge_summary");
        eprintln!("live knowledge ws={ws}: {} crates", s.crates.len());
        assert!(!s.crates.is_empty(), "remote knowledge map empty for {ws}");
    }

    /// Live FI1+FI2 round-trip: submit an `error` item then read it back via
    /// `Funnel.History`. Exercises the server's new History RPC + the
    /// on-write `funnel_events` schema evolution against a real server.
    #[test]
    #[ignore]
    fn live_funnel_intake_and_history() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = std::env::var("NORNIR_WS").unwrap_or_else(|_| "znippy".into());
        let marker = format!("funnel-intake live test {}", chrono::Utc::now().to_rfc3339());
        let id = funnel_submit(&ep, &tok, &ws, &marker, "error", "live-test")
            .expect("Funnel.SubmitIdea(error) must succeed");
        eprintln!("submitted error id={id} ws={ws}");
        let errs = funnel_history(&ep, &tok, &ws, "error", "").expect("Funnel.History must succeed");
        let mine = errs.iter().find(|it| it.id == id).expect("submitted error in history");
        assert_eq!(mine.item_kind, "error");
        assert_eq!(mine.text, marker);
        eprintln!("history error_count={} (found mine, kind={})", errs.len(), mine.item_kind);
    }

    /// Live `Funnel.Show` smoke for a workspace (default `holger`). Captures the
    /// actual RPC outcome — must NOT panic, returns an empty-or-populated view.
    #[test]
    #[ignore]
    fn live_funnel_show() {
        let ep = std::env::var("NORNIR_SERVER").expect("set NORNIR_SERVER");
        let tok = std::env::var("NORNIR_SERVER_TOKEN").expect("set NORNIR_SERVER_TOKEN");
        let ws = std::env::var("NORNIR_WS").unwrap_or_else(|_| "holger".into());
        match funnel_show(&ep, &tok, &ws) {
            Ok(v) => eprintln!("funnel_show ws={ws} OK: {} plans", v.plans.len()),
            Err(e) => {
                eprintln!("funnel_show ws={ws} ERR: {e:#}");
                panic!("funnel_show failed: {e:#}");
            }
        }
    }
}

/// Convert a proto `ProgressEvent` (the oneof) into the viz [`LiveEvent`] —
/// the same enum the local NDJSON tail deserializes, so the pane is wire-source
/// agnostic. Unknown/empty kinds are dropped (forward-compat).
fn to_live(ev: pb::ProgressEvent) -> Option<LiveEvent> {
    use pb::progress_event::Kind;
    Some(match ev.kind? {
        Kind::RunStart(x) => LiveEvent::RunStart { run_id: x.run_id, workspace: x.workspace },
        Kind::RepoStart(x) => LiveEvent::RepoStart { repo: x.repo, sha: x.sha },
        Kind::PhaseStart(x) => LiveEvent::PhaseStart { repo: x.repo, phase: x.phase },
        Kind::PhaseEnd(x) => LiveEvent::PhaseEnd {
            repo: x.repo,
            phase: x.phase,
            ok: x.ok,
            duration_ms: x.duration_ms,
        },
        Kind::BinaryStart(x) => LiveEvent::BinaryStart { repo: x.repo, binary: x.binary },
        Kind::TestPass(x) => LiveEvent::TestPass { repo: x.repo, binary: x.binary, name: x.name },
        Kind::TestFail(x) => LiveEvent::TestFail { repo: x.repo, binary: x.binary, name: x.name },
        Kind::BinaryDone(x) => LiveEvent::BinaryDone {
            repo: x.repo,
            binary: x.binary,
            passed: x.passed,
            failed: x.failed,
        },
        Kind::RepoEnd(x) => LiveEvent::RepoEnd { repo: x.repo, ok: x.ok },
        Kind::RunEnd(x) => LiveEvent::RunEnd { run_id: x.run_id, ok: x.ok },
    })
}