quorum-rs 0.7.0-rc.6

Rust SDK and CLI for multi-agent deliberation systems — ships the `quorum` binary (run / status / trace / tui / init) plus the underlying agent, LLM, tool, prompt, and worker library.
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
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
//! `nsed init` — interactive workspace setup wizard.
//!
//! Generates `nsed.yaml` (and optionally `config/agent.yml`) by guiding the
//! user through:
//! 1. Orchestrator configuration (one or more, remote or embedded)
//! 2. Agent setup (provider discovery + agent presets via nsed-cli-common)
//! 3. Policy creation (deliberation rules: rounds, convergence, SLA, mode)
//! 4. Agent → policy assignment (for static-agent policies)
//! 5. Room + default_room wiring
//! 6. Write, validate, and print summary

#[cfg(test)]
mod tests;

use std::collections::HashMap;
use std::path::Path;
use std::process::ExitCode;

use inquire::{Confirm, CustomType, InquireError, MultiSelect, Select, Text};

use crate::cli::remote::{AgentInfo, DiscoveredPolicy, RemoteOrchestrator};
use crate::cli::workspace::{
    AgentsConfig, ContextRef, OrchestratorConfig, OrchestratorMode, PolicyConfig, RoleConfig,
    RoomConfig, WorkspaceConfig,
};
use crate::config::resolve_env_token;
use crate::init::AgentSummary;
use crate::scheduling::PolicySla;

// ── Cancellation helper ─────────────────────────────────────────────────────

/// Wraps an `inquire` result: cancellation → `Ok(None)`, other errors bubble.
fn ask<T>(r: Result<T, InquireError>) -> Result<Option<T>, InquireError> {
    match r {
        Ok(v) => Ok(Some(v)),
        Err(InquireError::OperationCanceled | InquireError::OperationInterrupted) => Ok(None),
        Err(e) => Err(e),
    }
}

// ── Pure helpers (testable without interactive prompts) ──────────────────────

/// Sanitize an orchestrator/room/policy name to a valid slug.
/// Keeps alphanumeric, dashes, underscores. Lowercases. Returns `None` if empty.
pub fn sanitize_name(raw: &str) -> Option<String> {
    let slug: String = raw
        .trim()
        .to_lowercase()
        .chars()
        .map(|c| {
            if c.is_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '_'
            }
        })
        .collect();
    // Collapse consecutive underscores into a single one
    let mut collapsed = String::with_capacity(slug.len());
    for c in slug.chars() {
        if c == '_' && collapsed.ends_with('_') {
            continue;
        }
        collapsed.push(c);
    }
    let slug = collapsed.trim_matches('_').to_string();
    if slug.is_empty() { None } else { Some(slug) }
}

/// Build the YAML string for a `WorkspaceConfig`.
pub fn render_yaml(config: &WorkspaceConfig) -> Result<String, String> {
    serde_yaml::to_string(config).map_err(|e| format!("failed to serialize config: {e}"))
}

/// Render YAML for terminal preview, redacting any literal (non-env-ref) tokens.
pub fn render_yaml_redacted(config: &WorkspaceConfig) -> Result<String, String> {
    let mut preview = config.clone();
    for orch in preview.orchestrators.values_mut() {
        if let Some(ref t) = orch.token
            && !t.starts_with("${")
        {
            orch.token = Some("<redacted>".into());
        }
    }
    render_yaml(&preview)
}

/// Build a `WorkspaceConfig` from collected wizard inputs.
pub fn build_config(
    orchestrators: HashMap<String, OrchestratorConfig>,
    policies: HashMap<String, PolicyConfig>,
    rooms: HashMap<String, RoomConfig>,
    default_room: Option<String>,
    agent_config_file: Option<String>,
    dashboard_port: Option<u16>,
) -> WorkspaceConfig {
    WorkspaceConfig {
        orchestrators,
        policies,
        rooms,
        shared: None,
        default_room,
        agents: agent_config_file.map(|f| AgentsConfig {
            config_file: f,
            dashboard_port,
        }),
    }
}

/// Build agent display options from `AgentInfo` list (remote-discovered agents).
#[cfg(test)]
pub fn agent_display_options(agents: &[AgentInfo]) -> Vec<String> {
    agents
        .iter()
        .map(|a| {
            let status = if a.is_online { "" } else { "" };
            format!("{status} {:<20} {}", a.agent_id, a.model_name)
        })
        .collect()
}

/// Parse selected agent display strings back to agent IDs.
#[cfg(test)]
pub fn parse_selected_agents(selected: &[String], all_agents: &[AgentInfo]) -> Vec<String> {
    let display = agent_display_options(all_agents);
    selected
        .iter()
        .filter_map(|sel| {
            let idx = display.iter().position(|d| d == sel)?;
            Some(all_agents[idx].agent_id.clone())
        })
        .collect()
}

/// Build display options for locally-created agent summaries.
#[cfg(test)]
pub fn created_agent_display(agents: &[AgentSummary]) -> Vec<String> {
    agents
        .iter()
        .map(|a| format!("{:<20} {} ({})", a.name, a.model_name, a.provider_id))
        .collect()
}

/// Parse selected created-agent display strings back to agent names.
#[cfg(test)]
pub fn parse_selected_created(selected: &[String], all: &[AgentSummary]) -> Vec<String> {
    let display = created_agent_display(all);
    selected
        .iter()
        .filter_map(|sel| {
            let idx = display.iter().position(|d| d == sel)?;
            Some(all[idx].name.clone())
        })
        .collect()
}

// ── Prompt helper — ask for a unique name ───────────────────────────────────

fn ask_unique_name(
    prompt: &str,
    default: &str,
    existing: &[String],
) -> Result<Option<String>, String> {
    loop {
        let raw = match ask(Text::new(prompt).with_default(default).prompt())
            .map_err(|e| e.to_string())?
        {
            Some(r) => r,
            None => return Ok(None),
        };
        let name = match sanitize_name(&raw) {
            Some(s) => s,
            None => {
                eprintln!("  Invalid name — use alphanumeric, dashes, underscores.");
                continue;
            }
        };
        if existing.contains(&name) {
            eprintln!("  '{name}' already exists — pick a different name.");
            continue;
        }
        return Ok(Some(name));
    }
}

// ── Interactive wizard ──────────────────────────────────────────────────────

pub async fn run(output_path: &Path) -> ExitCode {
    if output_path.exists() {
        eprintln!("warning: {} already exists", output_path.display());
        match ask(Confirm::new("Overwrite?").with_default(false).prompt()) {
            Ok(Some(true)) => {}
            Ok(_) => {
                eprintln!("Cancelled.");
                return ExitCode::SUCCESS;
            }
            Err(e) => {
                eprintln!("Prompt failed: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    eprintln!("quorum init — workspace setup wizard\n");

    // ── Step 1: Orchestrators (loop) ────────────────────────────────────────

    eprintln!("─── Orchestrators ─────────────────────────────────────────");
    eprintln!("  Where deliberation runs. Add one or more (remote API or local embedded).\n");

    let mut orchestrators: HashMap<String, OrchestratorConfig> = HashMap::new();
    let mut discovered_agents: HashMap<String, Vec<AgentInfo>> = HashMap::new();
    let mut discovered_policies: HashMap<String, Vec<DiscoveredPolicy>> = HashMap::new();

    loop {
        let existing_names: Vec<String> = orchestrators.keys().cloned().collect();

        // Happy-path shortcut: first iteration auto-picks Remote
        // (the overwhelmingly common case) and auto-names it
        // `remote`. After the first orchestrator is registered the
        // loop asks a single Y/N "add another?" (default N) instead
        // of forcing operators through a Remote/Local/Done menu —
        // most setups have exactly one orchestrator.
        let is_first = orchestrators.is_empty();
        let (is_remote, orch_name) = if is_first {
            (true, "remote".to_string())
        } else {
            eprintln!("Orchestrators: {}", existing_names.join(", "));
            let add_more = match ask(Confirm::new("Add another orchestrator?")
                .with_default(false)
                .with_help_message("Press Enter for No — most setups have one")
                .prompt())
            {
                Ok(Some(v)) => v,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("Prompt failed: {e}");
                    return ExitCode::FAILURE;
                }
            };
            if !add_more {
                break;
            }

            // Explicit menu for the rare add-another flow.
            let add_opts = vec![
                "Remote  — connect to an existing orchestrator",
                "Embedded — run a local orchestrator process (advanced)",
            ];
            let choice = match ask(Select::new("Add orchestrator:", add_opts).prompt()) {
                Ok(Some(c)) => c,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("Prompt failed: {e}");
                    return ExitCode::FAILURE;
                }
            };
            let is_remote = choice.starts_with("Remote");
            let default_name = if is_remote {
                if orchestrators.contains_key("remote") {
                    format!("remote_{}", orchestrators.len() + 1)
                } else {
                    "remote".into()
                }
            } else if orchestrators.contains_key("local") {
                format!("local_{}", orchestrators.len() + 1)
            } else {
                "local".into()
            };

            let name = match ask_unique_name("Orchestrator name:", &default_name, &existing_names) {
                Ok(Some(n)) => n,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            };
            (is_remote, name)
        };

        if is_remote {
            match wizard_remote_orchestrator().await {
                Ok(Some((orch, agents, policies))) => {
                    if !agents.is_empty() {
                        discovered_agents.insert(orch_name.clone(), agents);
                    }
                    if !policies.is_empty() {
                        discovered_policies.insert(orch_name.clone(), policies);
                    }
                    orchestrators.insert(orch_name, orch);
                }
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            }
        } else {
            match wizard_embedded_orchestrator() {
                Ok(Some(orch)) => {
                    orchestrators.insert(orch_name, orch);
                }
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            }
        }
    }

    // Merge all discovered agents for display in later steps.
    let all_discovered: Vec<AgentInfo> = discovered_agents
        .values()
        .flat_map(|v| v.iter().cloned())
        .collect();

    // ── Step 2: Agent Setup (optional) ──────────────────────────────────────

    eprintln!("\n─── Agents ────────────────────────────────────────────────");
    eprintln!("  Create agent personas for deliberation (detects Ollama, prompts for providers).");
    if !all_discovered.is_empty() {
        eprintln!(
            "  {} agent(s) already discovered from remote orchestrator(s).",
            all_discovered.len()
        );
    }
    eprintln!();

    let mut created_agents: Vec<AgentSummary> = Vec::new();
    let mut agent_config_yaml: Option<String> = None;

    let setup_agents = match ask(Confirm::new("Set up local agents now?")
        .with_default(true)
        .prompt())
    {
        Ok(Some(v)) => v,
        Ok(None) => {
            eprintln!("Cancelled.");
            return ExitCode::SUCCESS;
        }
        Err(e) => {
            eprintln!("Prompt failed: {e}");
            return ExitCode::FAILURE;
        }
    };

    if setup_agents {
        // Determine orchestrator URL for the agent config file
        let orch_url = resolve_orchestrator_url(&orchestrators);

        match crate::init::run_agent_setup(&orch_url).await {
            Ok(Some(result)) => {
                if !result.agents.is_empty() {
                    eprintln!(
                        "\n{} agent(s) configured: {}",
                        result.agents.len(),
                        result
                            .agents
                            .iter()
                            .map(|a| a.name.as_str())
                            .collect::<Vec<_>>()
                            .join(", ")
                    );
                    created_agents = result.agents;
                }
                if !result.agent_config_yaml.is_empty() {
                    // Inject `telemetry.endpoints[].nats_url` from any
                    // orchestrator that captured one at redeem time —
                    // otherwise `quorum serve` falls through to its
                    // localhost default. Operator can still override
                    // per network via --nats-url or by editing the
                    // block.
                    let yaml = result.agent_config_yaml;
                    let yaml_with_telemetry = match orchestrators
                        .values()
                        .find_map(|o| o.nats_url.as_deref())
                    {
                        Some(nats_url) if !yaml.contains("telemetry:") => {
                            format!(
                                "telemetry:\n  endpoints:\n    - name: orchestrator\n      nats_url: \"{nats_url}\"\n\n{yaml}"
                            )
                        }
                        _ => yaml,
                    };
                    agent_config_yaml = Some(yaml_with_telemetry);
                }
            }
            Ok(None) => {
                eprintln!("  Skipped agent setup.");
            }
            Err(e) => {
                eprintln!("error: agent setup failed: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // ── Dashboard port (optional, only when agents are configured) ──────────
    // Track whether the user was prompted so we can distinguish "said No"
    // (don't inherit old config) from "not prompted" (preserve old config).
    // On re-init, use the existing config's dashboard_port as prompt defaults.

    let existing_dashboard_port: Option<u16> = std::fs::read_to_string(output_path)
        .ok()
        .and_then(|c| serde_yaml::from_str::<WorkspaceConfig>(&c).ok())
        .and_then(|w| w.agents)
        .and_then(|a| a.dashboard_port);

    let mut dashboard_port: Option<u16> = None;
    let mut dashboard_prompted = false;

    if agent_config_yaml.is_some() || !created_agents.is_empty() {
        dashboard_prompted = true;
        match ask(Confirm::new("Enable agent dashboard?")
            .with_default(true)
            .prompt())
        {
            Ok(Some(true)) => {
                let port_default = existing_dashboard_port.unwrap_or(8081);
                match ask(CustomType::<u16>::new("Dashboard port:")
                    .with_default(port_default)
                    .prompt())
                {
                    Ok(Some(0)) => {
                        eprintln!("error: port must be between 1 and 65535");
                        return ExitCode::FAILURE;
                    }
                    Ok(Some(port)) => {
                        dashboard_port = Some(port);
                        eprintln!("  ✓ Dashboard on port {port}");
                    }
                    Ok(None) => {
                        eprintln!("Cancelled.");
                        return ExitCode::SUCCESS;
                    }
                    Err(e) => {
                        eprintln!("error: {e}");
                        return ExitCode::FAILURE;
                    }
                }
            }
            Ok(Some(false)) => {} // User explicitly said "No" — dashboard_port stays None
            Ok(None) => {
                eprintln!("Cancelled.");
                return ExitCode::SUCCESS;
            }
            Err(e) => {
                eprintln!("error: {e}");
                return ExitCode::FAILURE;
            }
        }
    }

    // ── Step 3: Policies (loop) ─────────────────────────────────────────────

    eprintln!("\n─── Policies ──────────────────────────────────────────────");
    eprintln!("  Deliberation rules: how many rounds, when to stop, which agents participate.");
    eprintln!(
        "  Skip this to dispatch via remote orchestrator policies\n  \
         (run with `quorum run --policy <remote_id> --room <name> ...`).\n"
    );

    // Default no — most operators on remote orchestrators use the
    // admin's pre-registered policies. Local policy definition is
    // only needed for self-managed fleets or custom deliberation
    // rules.
    let define_local_policies = match ask(
        Confirm::new("Define local policies + rooms now?")
            .with_default(false)
            .with_help_message(
                "Press Enter for No — operators on remote orchestrators usually dispatch via --policy <id>",
            )
            .prompt(),
    )
    .map_err(|e| e.to_string())
    {
        Ok(Some(v)) => v,
        Ok(None) => {
            eprintln!("Cancelled.");
            return ExitCode::SUCCESS;
        }
        Err(e) => {
            eprintln!("Prompt failed: {e}");
            return ExitCode::FAILURE;
        }
    };

    let mut policies: HashMap<String, PolicyConfig> = HashMap::new();
    // Track which policies use static mode and need agent assignment later.
    let mut static_policies: Vec<String> = Vec::new();
    // Rooms populated either by the skip-local branch (remote policy
    // MultiSelect) or by the explicit "define local policies + rooms"
    // path below. Declared up here so both branches feed the same map.
    let mut rooms: HashMap<String, RoomConfig> = HashMap::new();

    if !define_local_policies {
        // Operator skipped local policies — show the (tenancy-filtered)
        // remote policy list the orchestrator already returned so they
        // can pick which ones become local rooms. Empty when the probe
        // failed or auth was skipped; falls through to the prior CLI-
        // flag hint in that case.
        let total_remote: usize = discovered_policies.values().map(Vec::len).sum();
        if total_remote == 0 {
            eprintln!(
                "  Skipped local policy + room definition. Use `quorum run --policy <id> --room <name> ...`\n  \
                 or re-run `quorum init` later to add them."
            );
        } else {
            match populate_rooms_from_remote(&discovered_policies, &mut rooms) {
                Ok(true) => {}
                Ok(false) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            }
        }
    }

    if define_local_policies {
        loop {
            let existing_names: Vec<String> = policies.keys().cloned().collect();
            if !existing_names.is_empty() {
                eprintln!("Policies: {}", existing_names.join(", "));
            }

            if !policies.is_empty() {
                let add_more = match ask(Confirm::new("Add another policy?")
                    .with_default(false)
                    .prompt())
                {
                    Ok(Some(v)) => v,
                    Ok(None) => {
                        eprintln!("Cancelled.");
                        return ExitCode::SUCCESS;
                    }
                    Err(e) => {
                        eprintln!("Prompt failed: {e}");
                        return ExitCode::FAILURE;
                    }
                };
                if !add_more {
                    break;
                }
            }

            let default_name = if policies.is_empty() {
                "default".into()
            } else {
                format!("policy_{}", policies.len() + 1)
            };

            let policy_name = match ask_unique_name("Policy name:", &default_name, &existing_names)
            {
                Ok(Some(n)) => n,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            };

            let policy = match wizard_policy() {
                Ok(Some((p, is_static))) => {
                    if is_static {
                        static_policies.push(policy_name.clone());
                    }
                    p
                }
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            };

            policies.insert(policy_name, policy);
        }
    } // close `if define_local_policies { loop { … } }`

    // ── Step 4: Agent Assignment (for static policies) ──────────────────────

    if !static_policies.is_empty() {
        eprintln!("\n─── Agent Assignment ──────────────────────────────────────");
        eprintln!("  Assign agents to each static policy (minimum 2 per policy).\n");

        for policy_name in &static_policies {
            let agents = match wizard_assign_agents(policy_name, &created_agents, &all_discovered) {
                Ok(Some(a)) => a,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            };

            if let Some(policy) = policies.get_mut(policy_name) {
                policy.agents = Some(agents);
            }
        }
    }

    // ── Step 5: Rooms (loop) ────────────────────────────────────────────────
    // A room links a local policy to an orchestrator. If the
    // operator skipped local policies (Step 3 No-default), they're
    // dispatching against remote orchestrator policies via
    // `quorum run --policy <id> --room <name>` so the local rooms
    // map can stay empty.

    let orch_names: Vec<String> = orchestrators.keys().cloned().collect();
    let policy_names: Vec<String> = policies.keys().cloned().collect();

    if !policies.is_empty() {
        eprintln!("\n─── Rooms ─────────────────────────────────────────────────");
        eprintln!(
            "  A room links a policy to an orchestrator. `quorum run` uses the default room.\n"
        );
    }

    if !policies.is_empty() {
        loop {
            let existing_names: Vec<String> = rooms.keys().cloned().collect();
            if !existing_names.is_empty() {
                eprintln!("Rooms: {}", existing_names.join(", "));
            }

            if !rooms.is_empty() {
                let add_more = match ask(Confirm::new("Add another room?")
                    .with_default(false)
                    .prompt())
                {
                    Ok(Some(v)) => v,
                    Ok(None) => {
                        eprintln!("Cancelled.");
                        return ExitCode::SUCCESS;
                    }
                    Err(e) => {
                        eprintln!("Prompt failed: {e}");
                        return ExitCode::FAILURE;
                    }
                };
                if !add_more {
                    break;
                }
            }

            let default_name = if rooms.is_empty() {
                "main".into()
            } else {
                format!("room_{}", rooms.len() + 1)
            };

            let room_name = match ask_unique_name("Room name:", &default_name, &existing_names) {
                Ok(Some(n)) => n,
                Ok(None) => {
                    eprintln!("Cancelled.");
                    return ExitCode::SUCCESS;
                }
                Err(e) => {
                    eprintln!("error: {e}");
                    return ExitCode::FAILURE;
                }
            };

            // Pick policy
            let policy_ref = if policy_names.len() == 1 {
                eprintln!("  Using policy '{}' (only one defined)", policy_names[0]);
                policy_names[0].clone()
            } else {
                match ask(Select::new("Policy for this room:", policy_names.clone()).prompt()) {
                    Ok(Some(p)) => p,
                    Ok(None) => {
                        eprintln!("Cancelled.");
                        return ExitCode::SUCCESS;
                    }
                    Err(e) => {
                        eprintln!("Prompt failed: {e}");
                        return ExitCode::FAILURE;
                    }
                }
            };

            // Pick orchestrator
            let orch_ref = if orch_names.len() == 1 {
                eprintln!(
                    "  Using orchestrator '{}' (only one defined)",
                    orch_names[0]
                );
                Some(orch_names[0].clone())
            } else {
                match ask(Select::new("Orchestrator for this room:", orch_names.clone()).prompt()) {
                    Ok(Some(o)) => Some(o),
                    Ok(None) => {
                        eprintln!("Cancelled.");
                        return ExitCode::SUCCESS;
                    }
                    Err(e) => {
                        eprintln!("Prompt failed: {e}");
                        return ExitCode::FAILURE;
                    }
                }
            };

            rooms.insert(
                room_name,
                RoomConfig {
                    policy: policy_ref,
                    orchestrator: orch_ref,
                },
            );
        }
    } // close `if !policies.is_empty() { loop { … } }`

    // ── Default room ────────────────────────────────────────────────────────

    let room_names: Vec<String> = rooms.keys().cloned().collect();
    let default_room = if room_names.is_empty() {
        // No local rooms because operator skipped policy step. The
        // `default_room` field is optional — leave it None so
        // `quorum run` requires an explicit `--room` argument.
        None
    } else if room_names.len() == 1 {
        Some(room_names[0].clone())
    } else {
        match ask(Select::new("Default room:", room_names).prompt()) {
            Ok(Some(r)) => Some(r),
            Ok(None) => {
                eprintln!("Cancelled.");
                return ExitCode::SUCCESS;
            }
            Err(e) => {
                eprintln!("error: {e}");
                return ExitCode::FAILURE;
            }
        }
    };

    // ── Build config ────────────────────────────────────────────────────────

    let has_remote = orchestrators.values().any(|o| {
        o.mode
            .as_ref()
            .is_some_and(|m| *m == OrchestratorMode::Remote)
    });
    let agent_config_ref = agent_config_yaml
        .as_ref()
        .map(|_| "config/agent.yml".to_string())
        .or_else(|| {
            // Preserve existing agent config reference on re-init:
            // read the current nsed.yaml and reuse its agents.config_file path.
            let dir = output_path.parent().unwrap_or(Path::new("."));
            if let Ok(contents) = std::fs::read_to_string(output_path)
                && let Ok(existing) = serde_yaml::from_str::<WorkspaceConfig>(&contents)
                && let Some(agents) = existing.agents
            {
                let resolved = dir.join(&agents.config_file);
                if resolved.exists() {
                    return Some(agents.config_file);
                }
            }
            // Fall back: check default path on disk.
            let default_path = dir.join("config/agent.yml");
            default_path
                .exists()
                .then(|| "config/agent.yml".to_string())
        });
    // Preserve existing dashboard_port on re-init only when the user was not
    // prompted (e.g. no agents configured). If they were prompted and said "No",
    // don't silently re-enable from the old config.
    let dashboard_port = if dashboard_prompted {
        dashboard_port
    } else {
        dashboard_port.or(existing_dashboard_port)
    };

    let config = build_config(
        orchestrators,
        policies,
        rooms,
        default_room,
        agent_config_ref,
        dashboard_port,
    );

    if let Err(e) = config.validate() {
        eprintln!("error: generated config is invalid: {e}");
        return ExitCode::FAILURE;
    }

    let yaml = match render_yaml(&config) {
        Ok(y) => y,
        Err(e) => {
            eprintln!("error: {e}");
            return ExitCode::FAILURE;
        }
    };

    // ── Summary (tokens redacted for terminal safety) ─────────────────────

    let preview = render_yaml_redacted(&config).unwrap_or_else(|_| yaml.clone());
    eprintln!("\n--- Generated nsed.yaml ---");
    eprintln!("{preview}");

    let agent_config_path = output_path
        .parent()
        .unwrap_or(Path::new("."))
        .join("config/agent.yml");
    let mut files_to_write = vec![output_path.display().to_string()];
    if agent_config_yaml.is_some() {
        files_to_write.push(agent_config_path.display().to_string());
    }
    eprintln!("Files: {}", files_to_write.join(", "));

    match ask(Confirm::new("Write these files?")
        .with_default(true)
        .prompt())
    {
        Ok(Some(true)) => {}
        Ok(_) => {
            eprintln!("Cancelled.");
            return ExitCode::SUCCESS;
        }
        Err(e) => {
            eprintln!("Prompt failed: {e}");
            return ExitCode::FAILURE;
        }
    }

    if let Err(e) = std::fs::write(output_path, &yaml) {
        eprintln!("error: failed to write {}: {e}", output_path.display());
        return ExitCode::FAILURE;
    }
    eprintln!("✓ Wrote {}", output_path.display());

    // Write agent config if generated — path already resolved above
    if let Some(ref agent_yaml) = agent_config_yaml {
        if let Some(parent) = agent_config_path.parent()
            && !parent.exists()
            && let Err(e) = std::fs::create_dir_all(parent)
        {
            eprintln!("error: failed to create {}: {e}", parent.display());
            return ExitCode::FAILURE;
        }
        if let Err(e) = std::fs::write(&agent_config_path, agent_yaml) {
            eprintln!(
                "error: failed to write {}: {e}",
                agent_config_path.display()
            );
            return ExitCode::FAILURE;
        }
        eprintln!("✓ Wrote config/agent.yml");
    }

    eprint!("{}", format_next_steps(has_remote));

    ExitCode::SUCCESS
}

// ── Next-steps message ─────────────────────────────────────────────────────

/// Formats the post-init "Next steps" message.
fn format_next_steps(has_remote: bool) -> String {
    let mut msg = String::from("\nNext steps:\n");
    msg.push_str("  quorum validate                  # parse nsed.yaml; surface schema errors\n");
    msg.push_str("  quorum run \"your question\"       # submit a one-shot deliberation\n");
    msg.push_str("  quorum tui                       # interactive monitor of in-flight jobs\n");
    msg.push_str(
        "  quorum serve --config config/agent.yml \\\n             --nats-url <from `quorum redeem` output>\n",
    );
    msg.push_str("                                   # run YOUR agents against the orchestrator\n");
    if has_remote {
        msg.push('\n');
        msg.push_str(
            "  \u{2139}  Remote orchestrator detected. `quorum serve` is only needed if\n",
        );
        msg.push_str("     you're contributing agents to the deliberation pool. Pure dispatch\n");
        msg.push_str(
            "     (`quorum run` / `tui`) works against the remote agents already there.\n",
        );
    }
    msg
}

// ── Orchestrator URL resolver ───────────────────────────────────────────────

/// Determine the best orchestrator URL for agent config.
/// Prefers orchestrators with an explicit address (embedded stores its API
/// port there too), falling back to `http://localhost:8080`.
/// When multiple orchestrators have addresses, picks the one with the
/// lexicographically smallest key for deterministic output.
pub fn resolve_orchestrator_url(orchestrators: &HashMap<String, OrchestratorConfig>) -> String {
    let mut keys: Vec<&String> = orchestrators.keys().collect();
    keys.sort();
    for key in keys {
        if let Some(ref addr) = orchestrators[key].address {
            return addr.clone();
        }
    }
    "http://localhost:8080".to_string()
}

/// Render a discovered remote policy as a single MultiSelect option
/// label. Prefix with the orchestrator name only when more than one
/// orchestrator is in play — keeps the common single-orch case
/// uncluttered while still disambiguating multi-orch setups.
fn format_remote_policy_option(orch: &str, multi_orch: bool, policy: &DiscoveredPolicy) -> String {
    let tag_hint = if policy.tags.is_empty() {
        String::new()
    } else {
        format!(" [{}]", policy.tags.join(", "))
    };
    if multi_orch {
        format!(
            "{orch}/{id}{name}{tag_hint}",
            id = policy.policy_id,
            name = policy.name
        )
    } else {
        format!(
            "{id}{name}{tag_hint}",
            id = policy.policy_id,
            name = policy.name
        )
    }
}

/// Pick a room-name slug that does not collide with anything already
/// in `rooms`. Tries `policy_id` first; on collision falls back to
/// `<orch>__<policy_id>`; on further collision appends a counter.
fn unique_room_name(rooms: &HashMap<String, RoomConfig>, orch: &str, policy_id: &str) -> String {
    if !rooms.contains_key(policy_id) {
        return policy_id.to_string();
    }
    let qualified = format!("{orch}__{policy_id}");
    if !rooms.contains_key(&qualified) {
        return qualified;
    }
    let mut n = 2usize;
    loop {
        let candidate = format!("{qualified}_{n}");
        if !rooms.contains_key(&candidate) {
            return candidate;
        }
        n += 1;
    }
}

/// Prompt the operator to pick from the (already tenancy-filtered)
/// remote policies surfaced by orchestrator discovery, and turn each
/// pick into a local `RoomConfig` that references the remote policy
/// id + orchestrator name.
///
/// Returns `Ok(true)` on normal completion (including empty
/// selection — operator deliberately picked nothing), `Ok(false)`
/// when the prompt was cancelled (Esc / ^C), and `Err(_)` on prompt
/// failure.
fn populate_rooms_from_remote(
    discovered: &HashMap<String, Vec<DiscoveredPolicy>>,
    rooms: &mut HashMap<String, RoomConfig>,
) -> Result<bool, String> {
    let multi_orch = discovered.len() > 1;
    let mut entries: Vec<(String, DiscoveredPolicy, String)> = Vec::new();
    let mut orch_keys: Vec<&String> = discovered.keys().collect();
    orch_keys.sort();
    for orch in orch_keys {
        for policy in &discovered[orch] {
            let label = format_remote_policy_option(orch, multi_orch, policy);
            entries.push((orch.clone(), policy.clone(), label));
        }
    }

    let labels: Vec<String> = entries.iter().map(|(_, _, l)| l.clone()).collect();

    eprintln!("\n─── Remote Policies ───────────────────────────────────────");
    eprintln!("  Pick which orchestrator-side policies become local rooms. Empty = none.\n");

    let picked = match ask(
        MultiSelect::new("Remote policies to wire as rooms:", labels.clone())
            .with_help_message(
                "Space toggles, Enter confirms. Empty selection skips room creation.",
            )
            .prompt(),
    )
    .map_err(|e| e.to_string())?
    {
        Some(p) => p,
        None => return Ok(false),
    };

    for label in picked {
        let Some((orch, policy, _)) = entries.iter().find(|(_, _, l)| l == &label) else {
            continue;
        };
        let room_name = unique_room_name(rooms, orch, &policy.policy_id);
        rooms.insert(
            room_name,
            RoomConfig {
                policy: policy.policy_id.clone(),
                orchestrator: Some(orch.clone()),
            },
        );
    }
    Ok(true)
}

// ── Sub-wizards ─────────────────────────────────────────────────────────────

async fn wizard_remote_orchestrator()
-> Result<Option<(OrchestratorConfig, Vec<AgentInfo>, Vec<DiscoveredPolicy>)>, String> {
    let address = match ask(Text::new("Orchestrator URL:")
        .with_default("https://api.peeramid.xyz")
        .prompt())
    .map_err(|e| e.to_string())?
    {
        Some(a) => {
            let trimmed = a.trim().to_string();
            if trimmed.is_empty() {
                return Err("address cannot be empty".into());
            }
            trimmed
        }
        None => return Ok(None),
    };

    // Branch on how the operator authenticates. Three sources, in
    // order of friction:
    //   - existing token from `~/.nsed/operator.token` (returning
    //     operator) — surfaced only when the file exists
    //   - bearer token they've been given out-of-band
    //   - single-use invite code redeemed here-and-now
    let existing_token_path = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(|h| {
            std::path::PathBuf::from(h)
                .join(".nsed")
                .join("operator.token")
        })
        .filter(|p| p.exists());

    let mut auth_opts: Vec<String> = Vec::new();
    if let Some(ref path) = existing_token_path {
        auth_opts.push(format!("Use existing token ({})", path.display()));
    }
    auth_opts.push("Bearer token (long-lived, pre-issued)".to_string());
    auth_opts.push("Invite code (single-use, redeem now)".to_string());

    let auth_method = match ask(Select::new("How do you want to authenticate?", auth_opts).prompt())
        .map_err(|e| e.to_string())?
    {
        Some(m) => m,
        None => return Ok(None),
    };

    // Token + (optional) suggested NATS URL captured here so
    // `quorum serve` doesn't fall back to nats://localhost when the
    // operator simply re-uses this nsed.yaml later.
    let (token_raw, suggested_nats_url): (String, Option<String>) =
        if auth_method.starts_with("Use existing token") {
            // `existing_token_path` is Some by construction — this branch
            // only appears in the menu when the file exists.
            let path = existing_token_path
                .as_ref()
                .ok_or_else(|| "existing token path missing".to_string())?;
            warn_if_token_file_world_readable(path);
            let raw = std::fs::read_to_string(path)
                .map_err(|e| format!("Failed to read {}: {e}", path.display()))?;
            let trimmed = raw.trim().to_string();
            if trimmed.is_empty() {
                return Err(format!(
                    "{} is empty — re-redeem an invite or delete the file",
                    path.display()
                ));
            }
            eprintln!("  ✓ Loaded token from {}", path.display());
            (trimmed, None)
        } else if auth_method.starts_with("Invite") {
            match redeem_operator_invite_in_wizard(&address).await? {
                Some(pair) => pair,
                None => return Ok(None),
            }
        } else {
            let token = match ask(Text::new("Bearer token (or ${ENV_VAR}):")
                .with_default("${NSED_BEARER_TOKEN}")
                .prompt())
            .map_err(|e| e.to_string())?
            {
                Some(t) => {
                    let trimmed = t.trim().to_string();
                    if trimmed.is_empty() {
                        return Err("token cannot be empty".into());
                    }
                    trimmed
                }
                None => return Ok(None),
            };
            (token, None)
        };

    let orch = OrchestratorConfig {
        mode: Some(OrchestratorMode::Remote),
        address: Some(address.clone()),
        token: Some(token_raw.clone()),
        nats_url: suggested_nats_url.clone(),
        config_file: None,
    };

    // Probe the orchestrator for agents + policies (best-effort).
    // Both lists are scoped server-side by the caller's tenancy
    // (per PR #445 filter_*_by_tenancy), so what we get back is
    // already what this operator is allowed to dispatch into.
    let resolved_token = resolve_env_token("token", &token_raw);
    let mut agents = Vec::new();
    let mut policies = Vec::new();

    if !resolved_token.trim().is_empty() {
        eprintln!("Probing {address} ...");
        match RemoteOrchestrator::new(&address, &resolved_token) {
            Ok(client) => {
                match client.health().await {
                    Ok(h) => eprintln!("  ✓ Health: {} (NATS: {})", h.status, h.nats_connection),
                    Err(e) => eprintln!("  ✗ Health check failed: {e}"),
                }
                match client.agents().await {
                    Ok(a) => {
                        eprintln!("{} agent(s) discovered", a.len());
                        agents = a;
                    }
                    Err(e) => eprintln!("  ✗ Agent discovery failed: {e}"),
                }
                match client.discover_policies().await {
                    Ok(p) => {
                        eprintln!("{} policy(s) discovered", p.len());
                        policies = p;
                    }
                    Err(e) => eprintln!("  ✗ Policy discovery failed: {e}"),
                }
            }
            Err(e) => eprintln!("  ✗ Could not create client: {e}"),
        }
    } else {
        eprintln!("  ⚠ Token not resolved — skipping probe (set env var and re-run)");
    }

    Ok(Some((orch, agents, policies)))
}

fn wizard_embedded_orchestrator() -> Result<Option<OrchestratorConfig>, String> {
    let config_file = match ask(Text::new("Config file path (will be created if missing):")
        .with_default("./config/orchestrator.yml")
        .prompt())
    .map_err(|e| e.to_string())?
    {
        Some(f) => {
            let trimmed = f.trim().to_string();
            if trimmed.is_empty() {
                return Err("config file path cannot be empty".into());
            }
            trimmed
        }
        None => return Ok(None),
    };

    // Prompt for key fields used in the full config template
    let app_port: u16 = match ask(Text::new("API port:").with_default("8080").prompt())
        .map_err(|e| e.to_string())?
    {
        Some(p) => match p.trim().parse::<u16>() {
            Ok(v) if v > 0 => v,
            _ => return Err("port must be 1–65535".into()),
        },
        None => return Ok(None),
    };

    let nats_port: u16 = match ask(Text::new("NATS port:").with_default("4222").prompt())
        .map_err(|e| e.to_string())?
    {
        Some(p) => match p.trim().parse::<u16>() {
            Ok(v) if v > 0 => v,
            _ => return Err("port must be 1–65535".into()),
        },
        None => return Ok(None),
    };

    let nats_url = format!("nats://127.0.0.1:{nats_port}");

    // Scaffold the config file if it doesn't exist
    let config_path = Path::new(&config_file);
    if !config_path.exists() {
        eprintln!("  Config file '{}' does not exist.", config_file);
        let create = match ask(Confirm::new("Create orchestrator config from template?")
            .with_default(true)
            .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(v) => v,
            None => return Ok(None),
        };
        if create {
            if let Some(parent) = config_path.parent()
                && !parent.exists()
            {
                std::fs::create_dir_all(parent)
                    .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
            }
            // Use the full template from nsed-cli-common (same as `nsed-orchestrator init`)
            let content = crate::init::render_default_orchestrator_config(app_port, nats_port);
            write_orchestrator_config_file(config_path, &content)
                .map_err(|e| format!("failed to write {}: {e}", config_file))?;
            eprintln!("  ✓ Created {config_file} (edit to customise auth, credentials, providers)");
        }
    } else {
        eprintln!("  ✓ Using existing {config_file}");
    }

    Ok(Some(OrchestratorConfig {
        mode: Some(OrchestratorMode::Embedded),
        address: Some(format!("http://localhost:{app_port}")),
        token: None,
        nats_url: Some(nats_url),
        config_file: Some(config_file),
    }))
}

/// Policy wizard — collects deliberation rules and mode choice.
/// Returns `(PolicyConfig, is_static)` where `is_static` means agents need
/// assignment in a later step (the `agents` field is left as a placeholder).
fn wizard_policy() -> Result<Option<(PolicyConfig, bool)>, String> {
    let mode_opts = vec![
        "Static agents — explicitly assign agents to this policy",
        "Role-based   — define roles with required capabilities; agents matched at runtime",
    ];
    let mode_choice =
        match ask(Select::new("Policy mode:", mode_opts).prompt()).map_err(|e| e.to_string())? {
            Some(c) => c,
            None => return Ok(None),
        };
    let is_static = mode_choice.starts_with("Static");

    // ── Deliberation parameters ─────────────────────────────────────────────

    let rounds = match ask(
        Text::new("Max deliberation rounds (upper bound):")
            .with_default("3")
            .with_help_message(
                "upper bound on iterations; the orchestrator may finish earlier when convergence is reached",
            )
            .prompt(),
    )
    .map_err(|e| e.to_string())?
    {
        Some(r) => match r.trim().parse::<u32>() {
            Ok(n) if n >= 1 => n,
            _ => return Err("max_rounds must be >= 1".into()),
        },
        None => return Ok(None),
    };

    let effort = match ask(Text::new("Effort (0.0–1.0):").with_default("0.6").prompt())
        .map_err(|e| e.to_string())?
    {
        Some(c) => match c.trim().parse::<f32>() {
            Ok(v) if (0.0..=1.0).contains(&v) => v,
            _ => return Err("effort must be 0.0–1.0".into()),
        },
        None => return Ok(None),
    };

    // ── SLA — all fields ────────────────────────────────────────────────────

    let sla = match wizard_sla()? {
        Some(s) => s,
        None => return Ok(None),
    };

    // ── Agent capability requirements ───────────────────────────────────────
    // These filter which agents are eligible. Each agent must advertise
    // matching capability tags. Format: `lang:rust`, `security:*`, `*`.

    let capabilities = if is_static {
        eprintln!(
            "  Agent capabilities filter which agents are eligible for assignment in the next step."
        );
        match ask(
            Text::new("Agent capabilities required (comma-separated, empty = any agent):")
                .with_default("")
                .with_help_message(
                    "e.g. lang:rust, security:owasp — each assigned agent must have these",
                )
                .prompt(),
        )
        .map_err(|e| e.to_string())?
        {
            Some(c) => parse_comma_list(&c),
            None => return Ok(None),
        }
    } else {
        // Role-based mode defines capabilities per role, but policy-level caps
        // are an additional global filter.
        match ask(Text::new(
            "Global agent capabilities required (comma-separated, empty = per-role only):",
        )
        .with_default("")
        .with_help_message("applied in addition to per-role capabilities")
        .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(c) => parse_comma_list(&c),
            None => return Ok(None),
        }
    };

    // ── Discovery tags ──────────────────────────────────────────────────────

    let tags = match ask(Text::new(
        "Discovery tags (comma-separated, empty = none, e.g. domain:security, public):",
    )
    .with_default("")
    .with_help_message("tags for policy discovery and matching")
    .prompt())
    .map_err(|e| e.to_string())?
    {
        Some(t) => parse_comma_list(&t),
        None => return Ok(None),
    };

    if is_static {
        // Placeholder — agents assigned in step 4.
        Ok(Some((
            PolicyConfig {
                agents: Some(vec!["__placeholder__".into(), "__placeholder__".into()]),
                roles: None,
                max_rounds: rounds,
                effort,
                sla,
                capabilities,
                tags,
                mode: Default::default(),
            },
            true,
        )))
    } else {
        // Role-based mode — collect roles (each role has count + capabilities)
        eprintln!();
        eprintln!("  Each role defines a capability requirement and how many agents fill it.");
        let roles = match wizard_roles() {
            Ok(Some(r)) => r,
            Ok(None) => return Ok(None),
            Err(e) => return Err(e),
        };

        Ok(Some((
            PolicyConfig {
                agents: None,
                roles: Some(roles),
                max_rounds: rounds,
                effort,
                sla,
                capabilities,
                tags,
                mode: Default::default(),
            },
            false,
        )))
    }
}

/// Prompt the operator for an invite code, redeem it against
/// `orchestrator_url` (#307 operator-redeem endpoint), and return the
/// freshly minted bearer token. The token is embedded in the
/// workspace YAML as a literal (not an env-var template) since the
/// operator only sees this value once — they have nothing to
/// substitute later.
///
/// A fresh NATS User NKey is generated locally and the public half is
/// presented to the orchestrator at redeem time. When the redeemed
/// code carries the agent grant (#444), the orchestrator also returns
/// a scoped User JWT + NATS URL — the wizard then persists `.creds` +
/// `.seed` to `~/.nsed/` so the agent process can pick them up via
/// `NATS_CREDS=~/.nsed/agent.creds`. Chat-only codes simply ignore
/// the pubkey and return the bearer token alone.
///
/// `Ok(None)` = operator cancelled / pressed Esc. `Err(_)` =
/// orchestrator rejected the code or transport failure. In either
/// case the caller bails out of the wizard cleanly.
/// Returns `(bearer_token, Option<nats_url>)` on success. The
/// nats_url is the orchestrator's suggested NATS endpoint for the
/// minted agent identity — operator persists it so `quorum serve`
/// doesn't fall back to `nats://localhost:4222`. URL is topology
/// not identity (see docs/identity-model.md), so the operator can
/// override per network.
async fn redeem_operator_invite_in_wizard(
    orchestrator_url: &str,
) -> Result<Option<(String, Option<String>)>, String> {
    use crate::nats_utils::{
        RedeemInviteError, format_nats_creds, redeem_operator_invite_with_orchestrator,
    };

    let code = match ask(Text::new("Paste invite code:").prompt()).map_err(|e| e.to_string())? {
        Some(c) => {
            let trimmed = c.trim().to_string();
            if trimmed.is_empty() {
                return Err("invite code cannot be empty".into());
            }
            trimmed
        }
        None => return Ok(None),
    };

    let keypair = nkeys::KeyPair::new_user();
    let pub_key = keypair.public_key();

    eprintln!("Redeeming invite at {orchestrator_url}");
    match redeem_operator_invite_with_orchestrator(
        orchestrator_url,
        &code,
        Some(&pub_key),
        Some("nsed init wizard"),
    )
    .await
    {
        Ok(resp) => {
            eprintln!(
                "  ✓ Redeemed as `{}` (token saved into workspace YAML)",
                resp.name
            );
            if let Some(budget) = resp.budget {
                eprintln!("  ✓ Initial budget: {budget} credits");
            }
            if let (Some(user_jwt), Some(nats_url)) =
                (resp.user_jwt.as_ref(), resp.nats_url.as_ref())
            {
                let seed = keypair
                    .seed()
                    .map_err(|e| format!("Failed to extract NKey seed: {e}"))?;
                let (creds_path, seed_path) =
                    persist_agent_creds(&format_nats_creds(user_jwt, &seed), &seed)?;
                eprintln!("  ✓ NATS creds : {}", creds_path.display());
                eprintln!("  ✓ NATS seed  : {}", seed_path.display());
                eprintln!("  ✓ NATS URL   : {nats_url}");
                eprintln!(
                    "  → Point your agent at the creds file (e.g. `NATS_CREDS={}` or the YAML \
                     `nats.auth.creds_file` field).",
                    creds_path.display()
                );
            }
            Ok(Some((resp.token, resp.nats_url)))
        }
        Err(RedeemInviteError::Expired) => {
            Err("This invite code has expired. Ask the admin for a fresh code.".into())
        }
        Err(RedeemInviteError::Replayed) => Err(
            "This invite code was already redeemed. Each code is single-use — ask the admin \
             for a fresh code."
                .into(),
        ),
        Err(RedeemInviteError::Revoked) => Err("The admin revoked this invite code.".into()),
        Err(RedeemInviteError::InvalidCode) => Err(
            "This invite code is invalid. Common causes: tampered during copy/paste, wrong \
             code type (agent-credential vs operator-token), or signing-secret mismatch."
                .into(),
        ),
        Err(RedeemInviteError::NotConfigured) => Err(
            "The orchestrator does not have invite codes configured. Ask the admin to set \
             APP_INVITES__SIGNING_SECRET on the orchestrator."
                .into(),
        ),
        Err(RedeemInviteError::KvUnavailable) => Err(
            "The orchestrator's backing store is temporarily unreachable. Try again in a minute."
                .into(),
        ),
        Err(RedeemInviteError::Unexpected { status, body }) => {
            Err(format!("Unexpected response: HTTP {status} body={body:?}"))
        }
        Err(RedeemInviteError::Transport(e)) => Err(format!("Failed to reach orchestrator: {e:#}")),
        Err(RedeemInviteError::Decode(e)) => Err(format!(
            "Orchestrator accepted the invite but the SDK couldn't process the response \
             ({e:#}). The invite is now consumed — ask the admin for a fresh code; the \
             orchestrator may be misconfigured."
        )),
    }
}

/// Persist a fresh `.creds` + `.seed` pair to `~/.nsed/agent.{creds,seed}`
/// after a unified-grant redeem. Files are written mode 0600 on Unix.
///
/// If a file already exists at either path, it's rotated to a
/// timestamped `.bak-<unix-ts>` sidecar before the new write —
/// previously the wizard refused, which lost the freshly-minted
/// token (the orchestrator had already burned the JTI by the time
/// this function ran, so failing here meant the operator had to ask
/// for a new invite). The old creds are never deleted, just renamed,
/// so an operator who needs the previous identity can recover it
/// from `.bak-<ts>`.
///
/// Returns the resolved paths so the caller can echo them to the user.
fn persist_agent_creds(
    creds_content: &str,
    user_seed: &str,
) -> std::result::Result<(std::path::PathBuf, std::path::PathBuf), String> {
    let home = std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .ok_or_else(|| "Cannot determine $HOME — set HOME or USERPROFILE.".to_string())?;
    let mut creds_path = std::path::PathBuf::from(&home);
    creds_path.push(".nsed");
    let dir = creds_path.clone();
    creds_path.push("agent.creds");
    let mut seed_path = std::path::PathBuf::from(&home);
    seed_path.push(".nsed");
    seed_path.push("agent.seed");

    std::fs::create_dir_all(&dir)
        .map_err(|e| format!("Failed to create {}: {e}", dir.display()))?;

    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    for path in [&creds_path, &seed_path] {
        if path.exists() {
            let bak = path.with_extension(format!(
                "{}.bak-{}",
                path.extension().and_then(|s| s.to_str()).unwrap_or(""),
                ts
            ));
            std::fs::rename(path, &bak).map_err(|e| {
                format!(
                    "Failed to rotate existing {} to {}: {e}",
                    path.display(),
                    bak.display()
                )
            })?;
            eprintln!(
                "  ↻ Rotated existing {}{} (recoverable if needed)",
                path.display(),
                bak.display()
            );
        }
    }

    write_secret_file(&creds_path, creds_content)
        .map_err(|e| format!("Failed to write {}: {e}", creds_path.display()))?;
    write_secret_file(&seed_path, user_seed)
        .map_err(|e| format!("Failed to write {}: {e}", seed_path.display()))?;

    Ok((creds_path, seed_path))
}

/// Stat the operator-token file before reading it and emit a warn
/// when the file is world- or group-readable. The wizard reuses
/// `~/.nsed/operator.token` from prior redeem runs; if a previous
/// tool wrote it with default permissions, the bearer token is
/// visible to every uid on the box. Warn-only — operators may have
/// the file inside an encrypted volume or run on a single-user
/// host; refusing to read would block legitimate setups.
#[cfg(unix)]
fn warn_if_token_file_world_readable(path: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    let Ok(meta) = std::fs::metadata(path) else {
        return;
    };
    let mode = meta.permissions().mode();
    // Any read bit set for group or other = readable by someone
    // other than the owner.
    if mode & 0o077 != 0 {
        eprintln!(
            "{} is {:o} (group/other readable) — bearer token is exposed. \
             Run `chmod 0600 {}` after this wizard exits.",
            path.display(),
            mode & 0o777,
            path.display()
        );
    }
}
#[cfg(not(unix))]
fn warn_if_token_file_world_readable(_path: &std::path::Path) {}

/// Atomic-write an orchestrator config file with `0o600` perms on
/// Unix. The config carries the orchestrator's JWT signing seed,
/// any inline NATS credentials block, and provider API key
/// references — anything that ends up here is treated as
/// secret-equivalent regardless of the field's nominal purpose.
fn write_orchestrator_config_file(path: &std::path::Path, content: &str) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o600)
            .open(path)?;
        f.write_all(content.as_bytes())?;
        Ok(())
    }
    #[cfg(not(unix))]
    {
        std::fs::write(path, content)
    }
}

fn write_secret_file(path: &std::path::Path, content: &str) -> std::io::Result<()> {
    #[cfg(unix)]
    {
        use std::io::Write;
        use std::os::unix::fs::OpenOptionsExt;
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .mode(0o600)
            .open(path)?;
        f.write_all(content.as_bytes())?;
        if !content.ends_with('\n') {
            writeln!(f)?;
        }
        Ok(())
    }
    #[cfg(not(unix))]
    {
        use std::io::Write;
        // Atomic create-or-fail so a racing process that materialises
        // the path between our existence check and this write can't
        // be silently clobbered. Same TOCTOU guarantee as the Unix
        // branch above (`create_new(true)`).
        let mut f = std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)?;
        f.write_all(content.as_bytes())?;
        if !content.ends_with('\n') {
            writeln!(f)?;
        }
        Ok(())
    }
}

/// Parse a comma-separated string into `Option<Vec<String>>`.
/// Returns `None` if empty.
fn parse_comma_list(raw: &str) -> Option<Vec<String>> {
    let items: Vec<String> = raw
        .split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();
    if items.is_empty() { None } else { Some(items) }
}

/// Collect SLA parameters: job timeout, response SLA (HITL buffer), max tokens.
///
/// - **Job timeout** (`job_timeout_secs`): whole-job wall-clock budget for the
///   entire deliberation. The BudgetManager divides this adaptively across
///   rounds and phases — when a phase's derived budget runs out, stragglers
///   are timed out.
/// - **Response SLA (HITL buffer)**: after the LLM produces a response, it's
///   held in a buffer for this duration, giving a human operator time to inspect,
///   edit, annotate, or reject before auto-release to the orchestrator.
///   Set to 0 to disable (pass-through). Operators can also pause, stop, or
///   auto-approve via the agent control plane API.
/// - **Max tokens**: caps each agent's LLM response length (maps to `max_tokens`).
fn wizard_sla() -> Result<Option<Option<PolicySla>>, String> {
    let job_timeout = match ask(Text::new(
        "Job timeout — whole-job wall-clock budget divided across rounds/phases (seconds, 0 = skip):",
    )
    .with_default("600")
    .with_help_message("the BudgetManager distributes this across rounds; stragglers are timed out when a phase's derived budget expires")
    .prompt())
    .map_err(|e| e.to_string())?
    {
        Some(t) => match t.trim().parse::<u64>() {
            Ok(0) => None,
            Ok(n) => Some(n),
            Err(_) => return Err("invalid timeout".into()),
        },
        None => return Ok(None),
    };

    // Only ask advanced SLA fields if the user set a job timeout
    let mut response_sla: Option<u64> = None;
    let mut max_tokens: Option<u32> = None;

    if let Some(job_secs) = job_timeout {
        let configure_advanced = match ask(Confirm::new(
            "Configure operator review window (HITL) and max tokens?",
        )
        .with_default(false)
        .with_help_message(
            "response SLA = buffer time for human review before auto-release to orchestrator",
        )
        .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(v) => v,
            None => return Ok(None),
        };

        if configure_advanced {
            // response_sla_secs is the HITL operator review window:
            // after the LLM produces a response, it's held in a buffer for
            // this duration, giving a human operator time to inspect, edit,
            // annotate, or reject before it's auto-released to the orchestrator.
            // 0 = pass-through (no buffer).
            response_sla = match ask(Text::new(
                "Response SLA — operator review window (seconds, 0 = no buffer):",
            )
            .with_default("0")
            .with_help_message(&format!(
                "HITL buffer: LLM responses held for review before auto-release (≤ {job_secs}s job budget)"
            ))
            .prompt())
            .map_err(|e| e.to_string())?
            {
                Some(t) => match t.trim().parse::<u64>() {
                    Ok(0) => None,
                    Ok(n) if n <= job_secs => Some(n),
                    Ok(n) => {
                        eprintln!(
                            "  warning: {n}s exceeds job timeout {job_secs}s, clamping to {job_secs}s"
                        );
                        Some(job_secs)
                    }
                    Err(_) => return Err("invalid response SLA".into()),
                },
                None => return Ok(None),
            };

            max_tokens = match ask(Text::new("Max tokens per agent response (0 = no limit):")
                .with_default("0")
                .with_help_message("caps LLM output length (maps to max_tokens parameter)")
                .prompt())
            .map_err(|e| e.to_string())?
            {
                Some(t) => match t.trim().parse::<u32>() {
                    Ok(0) => None,
                    Ok(n) => Some(n),
                    Err(_) => return Err("invalid max_tokens".into()),
                },
                None => return Ok(None),
            };
        }
    }

    if job_timeout.is_none() && response_sla.is_none() && max_tokens.is_none() {
        return Ok(Some(None));
    }

    // job_timeout_secs is a required field on PolicySla and must be > 0
    // (workspace validation rejects 0). If user skipped job timeout but set
    // other SLA fields, use a sensible default.
    let job_timeout_secs = job_timeout.unwrap_or(600);

    Ok(Some(Some(PolicySla {
        job_timeout_secs,
        response_sla_secs: response_sla,
        max_tokens,
    })))
}

/// Collect role definitions for a role-based policy.
fn wizard_roles() -> Result<Option<Vec<RoleConfig>>, String> {
    let mut roles: Vec<RoleConfig> = Vec::new();
    eprintln!("  Define roles (at least 2 total agents across all roles).\n");

    loop {
        let existing: Vec<String> = roles.iter().map(|r| r.role.clone()).collect();
        if !existing.is_empty() {
            let total: u32 = roles.iter().map(|r| r.count as u32).sum();
            eprintln!("  Roles so far: {} ({total} agent(s))", existing.join(", "));
        }

        if !roles.is_empty() {
            let total: u32 = roles.iter().map(|r| r.count as u32).sum();
            if total < 2 {
                eprintln!(
                    "  Need at least 2 total agents across roles (have {total}). Adding another role.\n"
                );
            } else {
                let add_more = match ask(Confirm::new("Add another role?")
                    .with_default(false)
                    .prompt())
                .map_err(|e| e.to_string())?
                {
                    Some(v) => v,
                    None => return Ok(None),
                };
                if !add_more {
                    break;
                }
            }
        }

        let default_name = if roles.is_empty() {
            "analyst".into()
        } else {
            format!("role_{}", roles.len() + 1)
        };

        let role_name = match ask_unique_name("Role name:", &default_name, &existing) {
            Ok(Some(n)) => n,
            Ok(None) => return Ok(None),
            Err(e) => return Err(e),
        };

        let count: u8 = match ask(Text::new("How many agents for this role?")
            .with_default("1")
            .with_help_message("each agent filling this role must match the required capabilities")
            .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(c) => match c.trim().parse::<u8>() {
                Ok(n) if n >= 1 => n,
                _ => return Err("count must be >= 1".into()),
            },
            None => return Ok(None),
        };

        let caps_raw = match ask(Text::new(
            "Agent capabilities required (comma-separated, e.g. lang:rust, security:*):",
        )
        .with_default("*")
        .with_help_message("agents must advertise these capability tags to fill this role")
        .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(c) => c,
            None => return Ok(None),
        };

        let capabilities: Vec<String> = caps_raw
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .collect();

        if capabilities.is_empty() {
            return Err("at least one capability required per role".into());
        }

        // Optional context files for this role
        let context = match ask(Text::new(
            "Context files for this role (name=path pairs, comma-separated, empty = none):",
        )
        .with_default("")
        .with_help_message("e.g. spec=docs/spec.md, code=src/main.rs")
        .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(raw) => {
                let mut refs = Vec::new();
                for pair in raw.split(',') {
                    let pair = pair.trim();
                    if pair.is_empty() {
                        continue;
                    }
                    match pair.split_once('=') {
                        Some((name, path))
                            if !name.trim().is_empty() && !path.trim().is_empty() =>
                        {
                            refs.push(ContextRef {
                                name: name.trim().to_string(),
                                path: path.trim().to_string(),
                            });
                        }
                        _ => {
                            eprintln!(
                                "  ⚠ Skipping malformed context pair: {pair:?} (expected name=path)"
                            );
                        }
                    }
                }
                if refs.is_empty() { None } else { Some(refs) }
            }
            None => return Ok(None),
        };

        roles.push(RoleConfig {
            role: role_name,
            count,
            capabilities,
            context,
            pinned_agents: None,
            moderator: false,
        });
    }

    Ok(Some(roles))
}

/// Build a unified display list combining created and discovered agents.
/// Returns `(display_strings, agent_ids, default_indices)`.
pub fn combined_agent_display(
    created: &[AgentSummary],
    discovered: &[AgentInfo],
) -> (Vec<String>, Vec<String>) {
    let mut display = Vec::new();
    let mut ids = Vec::new();

    for a in created {
        let caps = if a.capability_tags.is_empty() {
            String::new()
        } else {
            format!("  [{}]", a.capability_tags.join(", "))
        };
        display.push(format!(
            "★ {:<20} {} ({}){}",
            a.name, a.model_name, a.provider_id, caps
        ));
        ids.push(a.name.clone());
    }

    for a in discovered {
        let status = if a.is_online { "" } else { "" };
        let caps = if a.capability_tags.is_empty() {
            String::new()
        } else {
            format!("  [{}]", a.capability_tags.join(", "))
        };
        display.push(format!(
            "{status} {:<20} {} ({}){}",
            a.agent_id, a.model_name, a.provider_id, caps
        ));
        ids.push(a.agent_id.clone());
    }

    (display, ids)
}

/// Parse selected display strings back to agent IDs using the combined list.
pub fn parse_combined_selection(
    selected: &[String],
    display: &[String],
    ids: &[String],
) -> Vec<String> {
    selected
        .iter()
        .filter_map(|sel| {
            let idx = display.iter().position(|d| d == sel)?;
            Some(ids[idx].clone())
        })
        .collect()
}

/// Assign agents to a static policy from available sources.
/// Combines locally-created and remote-discovered agents in a single list.
fn wizard_assign_agents(
    policy_name: &str,
    created: &[AgentSummary],
    discovered: &[AgentInfo],
) -> Result<Option<Vec<String>>, String> {
    eprintln!("  Policy '{policy_name}' — assign agents:");

    let has_agents = !created.is_empty() || !discovered.is_empty();

    if has_agents {
        let (display, ids) = combined_agent_display(created, discovered);

        // Default: select all created agents + online discovered agents
        let defaults: Vec<usize> = (0..display.len())
            .filter(|&i| {
                if i < created.len() {
                    true // all created agents selected by default
                } else {
                    discovered[i - created.len()].is_online
                }
            })
            .collect();

        loop {
            let selected = match ask(MultiSelect::new("Select agents:", display.clone())
                .with_default(&defaults)
                .with_help_message("★ = created locally, ● = online remote, ○ = offline remote")
                .prompt())
            .map_err(|e| e.to_string())?
            {
                Some(s) => s,
                None => return Ok(None),
            };

            let names = parse_combined_selection(&selected, &display, &ids);
            if names.len() >= 2 {
                return Ok(Some(names));
            }
            eprintln!("  Need at least 2 agents, got {}. Try again.", names.len());
        }
    }

    // Fallback: manual entry (no agents available from setup or discovery)
    loop {
        let raw = match ask(Text::new("Agent names (comma-separated, min 2):")
            .with_default("DEFAULT, FriendlyAssistant, CapableAnalyst")
            .prompt())
        .map_err(|e| e.to_string())?
        {
            Some(r) => r,
            None => return Ok(None),
        };

        let names: Vec<String> = {
            let mut seen = std::collections::HashSet::new();
            raw.split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty() && seen.insert(s.to_lowercase()))
                .collect()
        };

        if names.len() >= 2 {
            return Ok(Some(names));
        }
        eprintln!("  Need at least 2 distinct agents, got {}.", names.len());
    }
}