nornir 0.5.1

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
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
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
//! `nornir release doctor` — the **advisory** release report: the "see it and get
//! hints first" tier. Read-only, no mutation. It answers the question you actually
//! have across the whole constellation — *can I release, what's off, in what order?*
//! — instead of Maven's per-project `dependency:tree`.
//!
//! Three signals composed here:
//! * **dirty trees** — real LOCAL `git status` per repo (via [`crate::gitio`]), not
//!   a server clone.
//! * **external-dependency version skew** — per shared external crate, the target
//!   (highest declared version) and each repo's status (ok / behind / forbidden),
//!   with bump hints. The anti-Maven bit: it surfaces *disagreement across repos*.
//! * (topo publish order + blast radius reuse the existing dep-graph tools.)
//!
//! Policy is **inferred** (target = highest version anyone already uses) plus a tiny
//! `forbidden` override (e.g. `arrow 56`). No pin table to hand-maintain.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};

// ─────────────────────────── policy ───────────────────────────

/// A forbidden external-dependency version — matched on the MAJOR component of a
/// declared version (e.g. `arrow` `56` bans `56`, `56.2`, `=56.2.1`).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ForbiddenDep {
    pub crate_name: String,
    pub version: String,
}

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct DepPolicy {
    pub forbidden: Vec<ForbiddenDep>,
}

// ─────────────────────────── inputs ───────────────────────────

/// One repo's declared EXTERNAL dependency versions (crate → declared version req).
#[derive(Debug, Clone)]
pub struct RepoExternals {
    pub repo: String,
    pub deps: BTreeMap<String, String>,
}

// ─────────────────────── skew analysis ───────────────────────

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub enum SkewStatus {
    Ok,
    Behind,
    Forbidden,
}

#[derive(Debug, Clone, Serialize)]
pub struct RepoCrateStatus {
    pub repo: String,
    pub version: String,
    pub status: SkewStatus,
    /// `true` when this repo is `Behind` on the crate yet the TARGET major already
    /// resolves in its `Cargo.lock` (a dual-major tree). That means a transitive
    /// dependency pins the old major — a direct bump of the declared version won't
    /// take until that dep moves, so the plain "bump" hint would be misleading.
    /// Filled in by [`enrich_transitive_pins`]; `false` until then (and in the
    /// pure [`analyze_skew`], which does no I/O).
    #[serde(default)]
    pub held_by_transitive_pin: bool,
}

#[derive(Debug, Clone, Serialize)]
pub struct CrateSkew {
    pub crate_name: String,
    /// The highest declared version across the repos = the inferred target.
    pub target: String,
    /// `true` when repos declare more than one distinct version.
    pub diverged: bool,
    pub entries: Vec<RepoCrateStatus>,
}

impl CrateSkew {
    /// Repos that should bump (status not Ok) — the hint set.
    pub fn bump_repos(&self) -> Vec<&str> {
        self.entries
            .iter()
            .filter(|e| e.status != SkewStatus::Ok)
            .map(|e| e.repo.as_str())
            .collect()
    }
}

/// Parse a declared version requirement into a comparable `(major, minor, patch)`
/// key, tolerating partials (`"57"` → `(57,0,0)`) and req operators (`"^1.2"`,
/// `">=0.9.0"`, `"=56.2.1"`).
fn version_key(s: &str) -> (u64, u64, u64) {
    let cleaned = s.trim().trim_start_matches(|c: char| !c.is_ascii_digit());
    let mut it = cleaned.split('.').map(|p| {
        p.chars()
            .take_while(|c| c.is_ascii_digit())
            .collect::<String>()
            .parse::<u64>()
            .unwrap_or(0)
    });
    (it.next().unwrap_or(0), it.next().unwrap_or(0), it.next().unwrap_or(0))
}

fn is_forbidden(crate_name: &str, version: &str, policy: &DepPolicy) -> bool {
    policy
        .forbidden
        .iter()
        .any(|f| f.crate_name == crate_name && same_semver_line(&f.version, version))
}

/// Whether two versions share the SemVer-significant leading component: for
/// `major >= 1` that's the major alone (`1.x` ↔ `1.y`); for `0.x` it's
/// `(major, minor)` — `0.9` and `0.10` are DIFFERENT SemVer lines, so a `0.9`
/// forbid must not ban every `0.x` (bug #19).
fn same_semver_line(forbidden: &str, version: &str) -> bool {
    let (fm, fmin, _) = version_key(forbidden);
    let (vm, vmin, _) = version_key(version);
    if fm == 0 { fm == vm && fmin == vmin } else { fm == vm }
}

/// THE BRAIN (pure, no I/O). Per external crate, infer the target = the highest
/// declared version, and classify each repo: `Ok` at the target, `Behind` below it,
/// `Forbidden` if the policy bans that version. Only crates that DIVERGE across
/// repos, or that hit a forbidden version, are surfaced (a single-repo dep at one
/// version isn't a skew worth a hint).
pub fn analyze_skew(repos: &[RepoExternals], policy: &DepPolicy) -> Vec<CrateSkew> {
    let mut by_crate: BTreeMap<&str, Vec<(&str, &str)>> = BTreeMap::new();
    for r in repos {
        for (c, v) in &r.deps {
            by_crate.entry(c.as_str()).or_default().push((r.repo.as_str(), v.as_str()));
        }
    }

    let mut out = Vec::new();
    for (crate_name, mut uses) in by_crate {
        let has_forbidden = uses.iter().any(|(_, v)| is_forbidden(crate_name, v, policy));
        let distinct: std::collections::BTreeSet<(u64, u64, u64)> =
            uses.iter().map(|(_, v)| version_key(v)).collect();
        let diverged = distinct.len() >= 2;
        if !diverged && !has_forbidden {
            continue;
        }

        uses.sort_by(|a, b| a.0.cmp(b.0)); // stable by repo name
        let target_key = uses.iter().map(|(_, v)| version_key(v)).max().unwrap();
        let target = uses
            .iter()
            .find(|(_, v)| version_key(v) == target_key)
            .map(|(_, v)| v.to_string())
            .unwrap();

        let entries = uses
            .iter()
            .map(|(repo, v)| {
                let status = if is_forbidden(crate_name, v, policy) {
                    SkewStatus::Forbidden
                } else if version_key(v) < target_key {
                    SkewStatus::Behind
                } else {
                    SkewStatus::Ok
                };
                RepoCrateStatus {
                    repo: repo.to_string(),
                    version: v.to_string(),
                    status,
                    held_by_transitive_pin: false,
                }
            })
            .collect();

        out.push(CrateSkew { crate_name: crate_name.to_string(), target, diverged, entries });
    }
    out
}

// ─────────────────── patch-fork promote gate ───────────────────
//
// A crate that builds on a local `[patch.crates-io]` override to a NON-registry
// source (a `path=` or `git=` fork — e.g. `iceberg = { path =
// "../iceberg-arrow58" }`) is NOT crates.io-publishable: `cargo publish` strips
// `[patch]`, so the published immutable crate resolves the STOCK dep the fork
// replaced (here stock iceberg 0.9.1 = arrow 57, not the fork's arrow 58) →
// broken. The detector finds those forks; the transitive closure marks every
// workspace-internal dependent blocked too (skade rides the iceberg fork →
// blocked; nornir depends on skade → also blocked).

/// What kind of non-registry source a `[patch.crates-io]` entry points at.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum ForkKind {
    /// `dep = { path = "../fork" }`
    Path,
    /// `dep = { git = "https://…" }`
    Git,
}

/// One fork-patched dependency that blocks a crate from a crates.io publish.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PatchForkBlock {
    /// The workspace crate whose manifest carries (or transitively inherits) the
    /// fork patch. For a direct block this is the crate that declares the
    /// `[patch.crates-io]`; transitive blocks are computed separately.
    pub crate_name: String,
    /// The patched dependency name (e.g. `iceberg`).
    pub patched_dep: String,
    /// Whether the override is a `path=` or `git=` fork.
    pub fork_kind: ForkKind,
    /// The override source string (the path or git url) for the report.
    pub source: String,
    /// Human reason, suitable for a `⛔` line.
    pub reason: String,
    /// `true` when `patched_dep` is NOT produced anywhere in the constellation —
    /// a genuine FOREIGN fork (e.g. `iceberg → ../iceberg-arrow58`, where crates.io
    /// `iceberg` is a third party's crate). Stripping it on publish leaves the crate
    /// resolving to an incompatible stock dep → a hard promote-blocker. `false` for a
    /// path/git override of one of OUR OWN crates (a sibling we also publish, e.g.
    /// `skade → ../skade`): that's just a local dev override, publish-order covers it,
    /// and the strip is safe. Only foreign forks seed the promote-block closure.
    /// Set by [`compute_promote_block`] (the raw [`patch_fork_blockers`] scan leaves
    /// it `false` since foreign-ness needs the cross-workspace produced set).
    pub is_foreign_fork: bool,
}

/// PURE-ish detector (one filesystem scan, no network): walk every `Cargo.toml`
/// under `repo_root`, parse each `[patch.crates-io]` / `[patch."crates-io"]`
/// table, and return one [`PatchForkBlock`] per entry that redirects to a
/// NON-registry source (`path=` or `git=`). Registry-version no-op patches
/// (`foo = "1.2"` or `foo = { version = "1.2" }`, which only pin a registry
/// version) do NOT count — `cargo publish` keeps those resolvable.
///
/// `crate_name` on each block is the `[package].name` of the manifest that
/// declares the patch (or, for a virtual-workspace root manifest with no
/// `[package]`, every workspace member crate produced under that root — see
/// [`patch_fork_blockers`]'s caller, which folds the root patch into the
/// workspace's own crates via the transitive closure).
pub fn patch_fork_blockers(repo_root: &Path) -> Vec<PatchForkBlock> {
    let mut out = Vec::new();
    for toml_path in find_cargo_tomls(repo_root, 4) {
        let Ok(txt) = std::fs::read_to_string(&toml_path) else { continue };
        let Ok(doc) = txt.parse::<toml::Value>() else { continue };
        // The crate this manifest produces (if any). A virtual root manifest has
        // no [package]; we tag those blocks with the workspace dir's folder name
        // so they still attach to *something* and the transitive closure can fold
        // them into the real member crates.
        let owner = doc
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .map(str::to_string);

        let Some(patch) = doc.get("patch") else { continue };
        let Some(patch_tbl) = patch.as_table() else { continue };
        // `[patch.crates-io]` (and the quoted variants) is `patch."crates-io"`.
        for key in ["crates-io"] {
            let Some(entries) = patch_tbl.get(key).and_then(|t| t.as_table()) else { continue };
            for (dep, spec) in entries {
                let (kind, source) = match spec {
                    // `dep = "1.2"` → registry-version pin, NOT a fork. Skip.
                    toml::Value::String(_) => continue,
                    toml::Value::Table(t) => {
                        if let Some(p) = t.get("path").and_then(|v| v.as_str()) {
                            (ForkKind::Path, p.to_string())
                        } else if let Some(g) = t.get("git").and_then(|v| v.as_str()) {
                            (ForkKind::Git, g.to_string())
                        } else {
                            // `{ version = "1.2" }` registry no-op patch → skip.
                            continue;
                        }
                    }
                    _ => continue,
                };
                let owner_name = owner.clone().unwrap_or_else(|| {
                    // Virtual root: name the block after the repo dir so it is
                    // non-empty; the caller folds it into the member crates.
                    repo_root
                        .file_name()
                        .and_then(|n| n.to_str())
                        .unwrap_or("workspace")
                        .to_string()
                });
                let reason = format!(
                    "publishing strips [patch.crates-io] → stock {dep} is incompatible \
                     (fork: {source}). Unblock: publish the fork, or wait for upstream."
                );
                out.push(PatchForkBlock {
                    crate_name: owner_name,
                    patched_dep: dep.clone(),
                    fork_kind: kind,
                    source,
                    reason,
                    // Foreign-ness needs the cross-workspace produced set, which a
                    // single-repo scan doesn't have — `compute_promote_block` fills it.
                    is_foreign_fork: false,
                });
            }
        }
    }
    out.sort_by(|a, b| {
        (&a.crate_name, &a.patched_dep).cmp(&(&b.crate_name, &b.patched_dep))
    });
    out
}

/// The TRANSITIVE promote-block (REPO-granularity, COARSE). Kept for callers that
/// reason at repo level. NOTE: this over-blocks for the gate — if a repo produces
/// *any* blocked crate it blocks *all* of that repo's crates, so a workspace member
/// that never touches the fork (e.g. `znippy-common` alongside `znippy-iceberg`)
/// gets held too. For the publish gate use [`promote_blocked_crates_precise`] /
/// [`compute_promote_block`], which block per-crate against the foreign fork.
///
/// The TRANSITIVE promote-block: a workspace crate is blocked if it OR any of
/// its workspace-internal dependencies is fork-blocked. Given the directly
/// fork-blocked crate set `directly_blocked` and the workspace graphs, return
/// every blocked crate name (the seed plus the reverse closure over the
/// who-produces-what edges). Pure — operates on the gathered graphs.
///
/// `directly_blocked` is the set of crate names a [`patch_fork_blockers`] scan
/// attached the fork to. A virtual-root patch attaches to the repo-dir name;
/// pass each workspace member's `produces` set so the closure folds it in:
/// callers that scan a single workspace seed with the root's produced crates.
pub fn promote_blocked_crates(
    graphs: &[RepoGraph],
    directly_blocked: &std::collections::BTreeSet<String>,
) -> std::collections::BTreeSet<String> {
    use std::collections::BTreeSet;
    // Map crate → the repos that PRODUCE it, and repo → the crates it produces.
    // Edges run dep → dependent: if crate C is blocked, any repo that declares C
    // as a dep is blocked, and so are all the crates that repo produces.
    let produces: Vec<(&str, &BTreeSet<String>, &BTreeSet<String>)> = graphs
        .iter()
        .map(|g| (g.repo.as_str(), &g.produces, &g.deps))
        .collect();

    let mut blocked: BTreeSet<String> = directly_blocked.clone();
    // Fixed point: keep folding until no new crate joins the blocked set.
    loop {
        let mut grew = false;
        for (_repo, repo_produces, repo_deps) in &produces {
            // This repo is blocked if it produces a blocked crate OR depends on
            // a blocked crate.
            let repo_blocked = repo_produces.iter().any(|c| blocked.contains(c))
                || repo_deps.iter().any(|d| blocked.contains(d));
            if repo_blocked {
                for c in repo_produces.iter() {
                    if blocked.insert(c.clone()) {
                        grew = true;
                    }
                }
            }
        }
        if !grew {
            break;
        }
    }
    blocked
}

/// Per-crate (NOT per-repo) dependency edges: every publishable `[package]` under
/// `root` maps to the set of dependency crate names it declares (internal + external,
/// non-optional, incl. build-deps). Unlike [`gather_repo_graph`], which unions a whole
/// repo's deps, this keeps crates SEPARATE — so a workspace member that doesn't touch a
/// forked dep isn't tarred with a sibling's fork. Mirrors `gather_repo_graph`'s rules
/// (skips `publish = false` crates and optional deps).
pub fn gather_crate_deps(
    root: &Path,
) -> BTreeMap<String, std::collections::BTreeSet<String>> {
    use std::collections::BTreeSet;
    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for toml_path in find_cargo_tomls(root, 4) {
        let Ok(txt) = std::fs::read_to_string(&toml_path) else { continue };
        let Ok(doc) = txt.parse::<toml::Value>() else { continue };
        let package = doc.get("package");
        let publishable = package
            .and_then(|p| p.get("publish"))
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if !publishable {
            continue;
        }
        let Some(name) =
            package.and_then(|p| p.get("name")).and_then(|n| n.as_str())
        else {
            continue;
        };
        let entry = out.entry(name.to_string()).or_default();
        for key in ["dependencies", "build-dependencies"] {
            if let Some(t) = doc.get(key).and_then(|t| t.as_table()) {
                for (dep, spec) in t {
                    let optional = spec
                        .as_table()
                        .and_then(|d| d.get("optional"))
                        .and_then(|o| o.as_bool())
                        .unwrap_or(false);
                    if !optional {
                        entry.insert(dep.clone());
                    }
                }
            }
        }
    }
    out
}

/// CRATE-LEVEL promote-block (PRECISE). A crate is blocked iff its transitive
/// dependency closure (over `crate_deps`) reaches one of `foreign_forks` — a dep that's
/// been `[patch]`-redirected to a path/git fork AND is not produced anywhere in the
/// constellation, so stripping the patch on publish leaves it resolving to an
/// incompatible stock crate. Path-patches to OUR OWN crates (siblings we also publish)
/// are NOT foreign forks — publish order covers them — so a member that never
/// transitively touches a foreign fork stays publishable. Pure; unit-testable.
pub fn promote_blocked_crates_precise(
    crate_deps: &BTreeMap<String, std::collections::BTreeSet<String>>,
    foreign_forks: &std::collections::BTreeSet<String>,
) -> std::collections::BTreeSet<String> {
    use std::collections::BTreeSet;
    let mut blocked: BTreeSet<String> = BTreeSet::new();
    if foreign_forks.is_empty() {
        return blocked;
    }
    for crate_name in crate_deps.keys() {
        // DFS the transitive dep closure; blocked the moment it reaches a foreign fork.
        let mut stack = vec![crate_name.clone()];
        let mut seen: BTreeSet<String> = BTreeSet::new();
        let mut hit = false;
        while let Some(c) = stack.pop() {
            if foreign_forks.contains(&c) {
                hit = true;
                break;
            }
            if !seen.insert(c.clone()) {
                continue;
            }
            if let Some(deps) = crate_deps.get(&c) {
                for d in deps {
                    if foreign_forks.contains(d) {
                        hit = true;
                        break;
                    }
                    // Recurse only into crates we produce (internal edges); unknown
                    // externals are leaves.
                    if crate_deps.contains_key(d) {
                        stack.push(d.clone());
                    }
                }
            }
            if hit {
                break;
            }
        }
        if hit {
            blocked.insert(crate_name.clone());
        }
    }
    blocked
}

/// The full precise promote-block computation across a set of `(name, path)` repos.
/// Scans each repo for crate-level deps + `[patch.crates-io]` forks, classifies each
/// fork as FOREIGN (patched dep not produced anywhere → hard blocker) vs an own-crate
/// path/git override (safe), tags every [`PatchForkBlock`] with `is_foreign_fork`, and
/// returns the per-crate transitive block closure against the foreign forks. Shared by
/// `release doctor`, the publish path, and the viz wizard so all three agree.
pub fn compute_promote_block<I, P>(repos: I) -> PromoteBlockResult
where
    I: IntoIterator<Item = (String, P)>,
    P: AsRef<Path>,
{
    use std::collections::BTreeSet;
    let mut crate_deps: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    let mut forks: Vec<PatchForkBlock> = Vec::new();
    for (_name, path) in repos {
        let path = path.as_ref();
        for (c, deps) in gather_crate_deps(path) {
            crate_deps.entry(c).or_default().extend(deps);
        }
        forks.extend(patch_fork_blockers(path));
    }
    let produced: BTreeSet<String> = crate_deps.keys().cloned().collect();
    let foreign_forks: BTreeSet<String> = forks
        .iter()
        .map(|b| b.patched_dep.clone())
        .filter(|d| !produced.contains(d))
        .collect();
    for b in forks.iter_mut() {
        b.is_foreign_fork = foreign_forks.contains(&b.patched_dep);
    }
    forks.sort_by(|a, b| {
        (&a.crate_name, &a.patched_dep).cmp(&(&b.crate_name, &b.patched_dep))
    });
    let blocked = promote_blocked_crates_precise(&crate_deps, &foreign_forks);
    PromoteBlockResult { forks, foreign_forks, blocked }
}

/// Result of [`compute_promote_block`].
#[derive(Debug, Clone, Default)]
pub struct PromoteBlockResult {
    /// Every detected patch-fork, with `is_foreign_fork` set. Foreign ones are hard
    /// blockers; the rest are safe own-crate dev overrides.
    pub forks: Vec<PatchForkBlock>,
    /// The foreign-fork dependency names that seed the block (e.g. `iceberg`).
    pub foreign_forks: std::collections::BTreeSet<String>,
    /// The per-crate transitive promote-block closure.
    pub blocked: std::collections::BTreeSet<String>,
}

// ─────────────────── transitive-pin detection ───────────────────

/// The set of MAJOR versions a crate resolves to in a `Cargo.lock`. `arrow` with
/// both `57.3.1` and `58.3.0` present → `{57, 58}`. Pure (parses the lock text),
/// so it's unit-testable without a real checkout.
pub fn crate_majors_in_lock(lock_text: &str, crate_name: &str) -> std::collections::BTreeSet<u64> {
    let mut out = std::collections::BTreeSet::new();
    let Ok(doc) = lock_text.parse::<toml::Value>() else { return out };
    let Some(pkgs) = doc.get("package").and_then(|p| p.as_array()) else { return out };
    for pkg in pkgs {
        let name = pkg.get("name").and_then(|n| n.as_str());
        let ver = pkg.get("version").and_then(|v| v.as_str());
        if name == Some(crate_name) {
            if let Some(v) = ver {
                out.insert(version_key(v).0);
            }
        }
    }
    out
}

/// Enrich a skew analysis with transitive-pin facts: for each repo that's `Behind`
/// on a crate, set `held_by_transitive_pin` when that repo's `Cargo.lock` ALREADY
/// resolves the target major (a dual-major tree). That's the tell that a transitive
/// dependency pins the old major — so the naive "bump the declared version" hint
/// would be misleading (it can't take until the pinning dep moves). `repo_locks`
/// maps repo name → its `Cargo.lock` contents (absent / unreadable locks are
/// simply skipped, leaving the flag `false`).
pub fn enrich_transitive_pins(
    skew: &mut [CrateSkew],
    repo_locks: &BTreeMap<String, String>,
) {
    for c in skew.iter_mut() {
        let target_major = version_key(&c.target).0;
        for e in c.entries.iter_mut() {
            if e.status != SkewStatus::Behind {
                continue;
            }
            // Only a genuine MAJOR gap can be transitively pinned. A loose
            // declaration like `clap = "4"` reads as "behind 4.5.51" but resolves
            // to it (same major) — that's not a pin, just an imprecise req.
            let declared_major = version_key(&e.version).0;
            if declared_major >= target_major {
                continue;
            }
            if let Some(lock) = repo_locks.get(&e.repo) {
                // Held iff the lock carries BOTH the declared (old) major AND the
                // target major as distinct resolves — a real dual-major tree, the
                // fingerprint of a transitive dep pinning the old line.
                let majors = crate_majors_in_lock(lock, &c.crate_name);
                if majors.contains(&declared_major) && majors.contains(&target_major) {
                    e.held_by_transitive_pin = true;
                }
            }
        }
    }
}

// ─────────────────────── dirty trees ───────────────────────

#[derive(Debug, Clone, Serialize)]
pub struct RepoDirty {
    pub repo: String,
    pub dirty: bool,
    pub error: Option<String>,
}

/// Real per-repo working-tree dirty state, computed against the LOCAL checkout
/// (not a server clone) via [`crate::gitio::worktree_freshness`].
pub fn check_dirty(repos: &[(String, PathBuf)]) -> Vec<RepoDirty> {
    repos
        .iter()
        .map(|(name, path)| match crate::gitio::worktree_freshness(path) {
            Ok(f) => RepoDirty { repo: name.clone(), dirty: f.dirty, error: None },
            Err(e) => RepoDirty { repo: name.clone(), dirty: false, error: Some(e.to_string()) },
        })
        .collect()
}

// ─────────────────────── gatherer ───────────────────────

/// Collect a repo's declared EXTERNAL dependency versions by scanning its
/// `Cargo.toml` files. External = declared with a literal `version` and NO `path`
/// (path deps are workspace-internal). Keeps the highest version seen per crate.
pub fn gather_repo_externals(repo: &str, root: &Path) -> Result<RepoExternals> {
    let mut deps: BTreeMap<String, String> = BTreeMap::new();
    for toml_path in find_cargo_tomls(root, 4) {
        let Ok(txt) = std::fs::read_to_string(&toml_path) else { continue };
        let Ok(doc) = txt.parse::<toml::Value>() else { continue };
        for key in ["dependencies", "build-dependencies"] {
            collect_deps(doc.get(key), &mut deps);
        }
        if let Some(ws) = doc.get("workspace").and_then(|w| w.get("dependencies")) {
            collect_deps(Some(ws), &mut deps);
        }
    }
    Ok(RepoExternals { repo: repo.to_string(), deps })
}

/// Merge a `[dependencies]`-style table into `deps`, taking only external crates
/// (literal version, no `path`) and keeping the highest version per crate.
fn collect_deps(table: Option<&toml::Value>, deps: &mut BTreeMap<String, String>) {
    let Some(table) = table.and_then(|t| t.as_table()) else { return };
    for (name, spec) in table {
        let version = match spec {
            toml::Value::String(v) => Some(v.clone()),
            toml::Value::Table(t) => {
                if t.contains_key("path") {
                    None // workspace-internal
                } else {
                    t.get("version").and_then(|v| v.as_str()).map(str::to_string)
                }
            }
            _ => None,
        };
        if let Some(v) = version {
            deps.entry(name.clone())
                .and_modify(|cur| {
                    if version_key(&v) > version_key(cur) {
                        *cur = v.clone();
                    }
                })
                .or_insert(v);
        }
    }
}

/// Find `Cargo.toml` files under `root` up to `max_depth`, skipping `target`,
/// `.git`, and other hidden directories.
fn find_cargo_tomls(root: &Path, max_depth: usize) -> Vec<PathBuf> {
    let mut out = Vec::new();
    let mut stack = vec![(root.to_path_buf(), 0usize)];
    while let Some((dir, depth)) = stack.pop() {
        let manifest = dir.join("Cargo.toml");
        if manifest.is_file() {
            out.push(manifest);
        }
        if depth >= max_depth {
            continue;
        }
        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
        for e in entries.flatten() {
            let p = e.path();
            // Don't follow symlinks (e.g. `.claude/worktrees/*` → sibling repos) and
            // skip build/dot dirs — same containment as `cargo::walk_cargo_tomls`.
            if e.file_type().map(|t| t.is_symlink()).unwrap_or(false) {
                continue;
            }
            if !p.is_dir() {
                continue;
            }
            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("");
            if name == "target" || name.starts_with('.') {
                continue;
            }
            stack.push((p, depth + 1));
        }
    }
    out
}

// ──────────── publish preflight: path deps need a version ────────────

/// A `path` dependency of a PUBLISHABLE crate that lacks a `version` requirement.
/// `cargo publish` rejects exactly this ("all dependencies must have a version
/// requirement specified when publishing") — so it's the class of blocker that
/// `--rehearse` otherwise trips on MID-publish, per crate, slowly. This is the
/// STATIC pre-flight for it: found up front, before any registry work, and
/// classified so the fix is obvious.
#[derive(Debug, Clone, Serialize)]
pub struct PathDepVersionGap {
    /// Constellation member whose crate has the gap.
    pub repo: String,
    /// Repo-relative path of the offending `Cargo.toml`.
    pub manifest: String,
    /// The publishable crate carrying the versionless path dep.
    pub crate_name: String,
    /// The path dependency missing a `version =`.
    pub dep: String,
    /// The constellation repo that PRODUCES `dep`, if any. `Some` ⇒ AUTO-FIXABLE
    /// (member-owned — fill `version` from the dep crate's own manifest). `None` ⇒
    /// NEEDS A DECISION: a non-member dep (e.g. `modgunn`, `graphar`) — it must
    /// join the release cascade or be published to crates.io first.
    pub dep_owner: Option<String>,
    /// The dep crate's own declared version, when it's a member we can read — the
    /// value to write into `version = "…"`.
    pub suggested_version: Option<String>,
    /// True when the missing-version declaration lives in `[workspace.dependencies]`
    /// (inherited via `dep.workspace = true`), so the fix is at the workspace root.
    pub via_workspace: bool,
}

/// Read a repo's manifests (path + parsed doc), its `[workspace.package].version`
/// (to resolve `version.workspace = true`), and its `[workspace.dependencies]`
/// specs (to resolve `dep.workspace = true`).
fn read_repo_manifests(
    root: &Path,
) -> (Vec<(PathBuf, toml::Value)>, Option<String>, BTreeMap<String, toml::Value>) {
    let mut docs = Vec::new();
    let mut ws_pkg_ver = None;
    let mut ws_deps = BTreeMap::new();
    for p in find_cargo_tomls(root, 4) {
        let Ok(txt) = std::fs::read_to_string(&p) else { continue };
        let Ok(doc) = txt.parse::<toml::Value>() else { continue };
        if let Some(w) = doc.get("workspace") {
            if let Some(v) =
                w.get("package").and_then(|pk| pk.get("version")).and_then(|v| v.as_str())
            {
                ws_pkg_ver = Some(v.to_string());
            }
            if let Some(t) = w.get("dependencies").and_then(|t| t.as_table()) {
                for (k, spec) in t {
                    ws_deps.insert(k.clone(), spec.clone());
                }
            }
        }
        docs.push((p, doc));
    }
    (docs, ws_pkg_ver, ws_deps)
}

/// A package's own version, resolving `version.workspace = true`
/// (`version = { workspace = true }`) to the workspace `[workspace.package].version`.
fn crate_version_of(pkg: &toml::Value, ws_pkg_ver: &Option<String>) -> Option<String> {
    match pkg.get("version") {
        Some(toml::Value::String(s)) => Some(s.clone()),
        Some(toml::Value::Table(t))
            if t.get("workspace").and_then(|w| w.as_bool()).unwrap_or(false) =>
        {
            ws_pkg_ver.clone()
        }
        _ => None,
    }
}

/// Scan every PUBLISHABLE crate across the constellation for Normal/Build `path`
/// deps missing a `version` — the `cargo publish` manifest-verify blocker, caught
/// statically. Dev-deps are exempt (cargo drops a path dev-dep's requirement).
/// Each gap is classified member-owned (auto-fixable, with a suggested version)
/// vs non-member (needs a decision) via the produced-by map built from `repos`.
pub fn scan_path_dep_version_gaps(repos: &[(String, PathBuf)]) -> Vec<PathDepVersionGap> {
    // 1) produced map: crate name → (owning repo, its version), publishable crates.
    let mut produced: BTreeMap<String, (String, Option<String>)> = BTreeMap::new();
    for (repo, root) in repos {
        let (docs, ws_pkg_ver, _) = read_repo_manifests(root);
        for (_p, doc) in &docs {
            let Some(pkg) = doc.get("package") else { continue };
            if !pkg.get("publish").and_then(|v| v.as_bool()).unwrap_or(true) {
                continue;
            }
            let Some(name) = pkg.get("name").and_then(|n| n.as_str()) else { continue };
            let ver = crate_version_of(pkg, &ws_pkg_ver);
            produced.entry(name.to_string()).or_insert((repo.clone(), ver));
        }
    }

    // 2) per publishable crate, flag Normal/Build path deps with no version.
    let mut gaps: Vec<PathDepVersionGap> = Vec::new();
    for (repo, root) in repos {
        let (docs, _ws_pkg_ver, ws_deps) = read_repo_manifests(root);
        for (path, doc) in &docs {
            let Some(pkg) = doc.get("package") else { continue };
            if !pkg.get("publish").and_then(|v| v.as_bool()).unwrap_or(true) {
                continue;
            }
            let Some(crate_name) = pkg.get("name").and_then(|n| n.as_str()) else { continue };
            let rel = path.strip_prefix(root).unwrap_or(path).display().to_string();
            // Normal + Build dep tables, INCLUDING `[target.'cfg(…)'.…]` variants —
            // cargo publish requires a version on those path deps too.
            for tbl in publish_dep_tables(doc) {
                for (dkey, spec) in tbl {
                    // Resolve `dep.workspace = true` to the `[workspace.dependencies]` spec.
                    let via_ws = spec
                        .as_table()
                        .and_then(|t| t.get("workspace"))
                        .and_then(|w| w.as_bool())
                        .unwrap_or(false);
                    let eff = if via_ws { ws_deps.get(dkey).unwrap_or(spec) } else { spec };
                    let Some(et) = eff.as_table() else { continue }; // bare "1.2" → fine
                    if !et.contains_key("path") || et.contains_key("version") {
                        continue; // not a path dep, or already versioned → fine
                    }
                    let real = dep_real_name(dkey, eff);
                    let owner = produced.get(&real);
                    gaps.push(PathDepVersionGap {
                        repo: repo.clone(),
                        manifest: rel.clone(),
                        crate_name: crate_name.to_string(),
                        dep: real,
                        dep_owner: owner.map(|(r, _)| r.clone()),
                        suggested_version: owner.and_then(|(_, v)| v.clone()),
                        via_workspace: via_ws,
                    });
                }
            }
        }
    }
    // needs-decision first, then by repo/dep; dedupe identical (repo, manifest, dep).
    gaps.sort_by(|a, b| {
        (a.dep_owner.is_some(), &a.repo, &a.manifest, &a.dep)
            .cmp(&(b.dep_owner.is_some(), &b.repo, &b.manifest, &b.dep))
    });
    gaps.dedup_by(|a, b| a.repo == b.repo && a.manifest == b.manifest && a.dep == b.dep);
    gaps
}

/// The Normal + Build dependency tables of a manifest that `cargo publish` verifies
/// — the two top-level ones PLUS every `[target.'cfg(…)'.{dependencies,
/// build-dependencies}]` variant. Dev-deps are excluded (cargo drops a dev-dep's
/// path requirement). Returns the tables as `&toml::Table`.
fn publish_dep_tables(doc: &toml::Value) -> Vec<&toml::value::Table> {
    let mut out = Vec::new();
    for key in ["dependencies", "build-dependencies"] {
        if let Some(t) = doc.get(key).and_then(|t| t.as_table()) {
            out.push(t);
        }
    }
    if let Some(targets) = doc.get("target").and_then(|t| t.as_table()) {
        for (_cfg, ct) in targets {
            for key in ["dependencies", "build-dependencies"] {
                if let Some(t) = ct.get(key).and_then(|t| t.as_table()) {
                    out.push(t);
                }
            }
        }
    }
    out
}

/// Mutable access to one dependency table of a `toml_edit` manifest: either a
/// top-level `[dependencies]`/`[build-dependencies]` (`cfg = None`) or a
/// `[target.'<cfg>'.<table_name>]` variant (`cfg = Some(...)`).
fn dep_table_mut<'a>(
    doc: &'a mut toml_edit::DocumentMut,
    cfg: Option<&str>,
    table_name: &str,
) -> Option<&'a mut toml_edit::Table> {
    match cfg {
        None => doc.get_mut(table_name).and_then(|t| t.as_table_mut()),
        Some(c) => doc
            .get_mut("target")
            .and_then(|t| t.as_table_mut())
            .and_then(|t| t.get_mut(c))
            .and_then(|c| c.as_table_mut())
            .and_then(|c| c.get_mut(table_name))
            .and_then(|t| t.as_table_mut()),
    }
}

/// Resolve a crate's own `version`, following `version.workspace = true` by walking
/// up from its manifest dir to the `[workspace.package].version`.
fn resolve_crate_version(dep_manifest: &Path) -> Option<String> {
    let text = std::fs::read_to_string(dep_manifest).ok()?;
    let doc = text.parse::<toml::Value>().ok()?;
    match doc.get("package").and_then(|p| p.get("version")) {
        Some(toml::Value::String(s)) => return Some(s.clone()),
        Some(toml::Value::Table(t))
            if t.get("workspace").and_then(|w| w.as_bool()).unwrap_or(false) => {}
        _ => return None,
    }
    // version.workspace = true → find the nearest ancestor with [workspace.package].version.
    let mut dir = dep_manifest.parent();
    while let Some(d) = dir {
        if let Ok(txt) = std::fs::read_to_string(d.join("Cargo.toml")) {
            if let Ok(doc) = txt.parse::<toml::Value>() {
                if let Some(v) = doc
                    .get("workspace")
                    .and_then(|w| w.get("package"))
                    .and_then(|pk| pk.get("version"))
                    .and_then(|v| v.as_str())
                {
                    return Some(v.to_string());
                }
            }
        }
        dir = d.parent();
    }
    None
}

/// The outcome of `--fix`: how many gaps got a `version=` written, and which were
/// skipped (with why).
#[derive(Debug, Default)]
pub struct FixOutcome {
    pub fixed: usize,
    pub skipped: Vec<String>,
}

/// Auto-apply `version = "…"` to every path-dep-version gap, sourcing the version
/// from the DEP crate's own manifest (follow its `path`), falling back to the
/// report's `suggested_version`. Formatting-preserving (`toml_edit`). Idempotent:
/// a dep that already grew a version is simply not re-found. This is the smart the
/// doctor used to leave to a human — now `nornir release doctor --fix` does it.
pub fn fix_path_dep_versions(
    gaps: &[PathDepVersionGap],
    repos: &[(String, PathBuf)],
) -> Result<FixOutcome> {
    let repo_root: BTreeMap<&str, &Path> =
        repos.iter().map(|(n, p)| (n.as_str(), p.as_path())).collect();
    // Group by absolute manifest path so each file is opened + written once.
    let mut by_file: BTreeMap<PathBuf, Vec<&PathDepVersionGap>> = BTreeMap::new();
    for g in gaps {
        let Some(root) = repo_root.get(g.repo.as_str()) else {
            continue;
        };
        by_file.entry(root.join(&g.manifest)).or_default().push(g);
    }

    let mut out = FixOutcome::default();
    for (manifest, gs) in by_file {
        let text = std::fs::read_to_string(&manifest)
            .with_context(|| format!("read {}", manifest.display()))?;
        let mut doc: toml_edit::DocumentMut =
            text.parse().with_context(|| format!("parse {}", manifest.display()))?;
        let mdir = manifest.parent().unwrap_or_else(|| Path::new("."));
        let mut changed = false;
        // Locators for every Normal/Build dep table: the two top-level ones plus each
        // `[target.'cfg'.…]` variant (collected up front — inserting a version never
        // adds/removes a target table, so the set stays valid across mutation).
        let cfgs: Vec<String> = doc
            .get("target")
            .and_then(|t| t.as_table())
            .map(|t| t.iter().map(|(k, _)| k.to_string()).collect())
            .unwrap_or_default();
        let mut locators: Vec<(Option<String>, &str)> = Vec::new();
        for tn in ["dependencies", "build-dependencies"] {
            locators.push((None, tn));
        }
        for c in &cfgs {
            for tn in ["dependencies", "build-dependencies"] {
                locators.push((Some(c.clone()), tn));
            }
        }
        for g in gs {
            let mut handled = false;
            for (cfg, table_name) in &locators {
                let Some(tbl) = dep_table_mut(&mut doc, cfg.as_deref(), table_name) else {
                    continue;
                };
                // Find the dep KEY whose real name == g.dep with a path and no version.
                let key = tbl.iter().find_map(|(k, item)| {
                    let real =
                        item.get("package").and_then(|p| p.as_str()).unwrap_or(k);
                    let has_path = item.get("path").is_some();
                    let has_ver = item.get("version").is_some();
                    (real == g.dep && has_path && !has_ver).then(|| k.to_string())
                });
                let Some(key) = key else { continue };
                let path_val = tbl
                    .get(&key)
                    .and_then(|i| i.get("path"))
                    .and_then(|p| p.as_str())
                    .map(|p| mdir.join(p).join("Cargo.toml"));
                let ver = path_val
                    .as_deref()
                    .and_then(resolve_crate_version)
                    .or_else(|| g.suggested_version.clone());
                match ver {
                    Some(v) => {
                        if let Some(item) = tbl.get_mut(&key) {
                            if let Some(it) = item.as_inline_table_mut() {
                                it.insert("version", v.into());
                            } else if let Some(t) = item.as_table_mut() {
                                t.insert("version", toml_edit::value(v));
                            }
                            out.fixed += 1;
                            changed = true;
                        }
                    }
                    None => out.skipped.push(format!(
                        "{}/{}: {} (no resolvable version)",
                        g.repo, g.manifest, g.dep
                    )),
                }
                handled = true;
                break;
            }
            if !handled {
                out.skipped.push(format!(
                    "{}/{}: {} (dep entry not found — already fixed?)",
                    g.repo, g.manifest, g.dep
                ));
            }
        }
        if changed {
            std::fs::write(&manifest, doc.to_string())
                .with_context(|| format!("write {}", manifest.display()))?;
        }
    }
    Ok(out)
}

// ─────────────── cross-repo graph: topo order + blast radius ───────────────

/// The dependency table an edge was declared in. Dev edges are tracked (for
/// blast-radius / "who tests against whom") but are NEVER publish-order-gating: a
/// `cargo publish` requires a crate's Normal+Build deps on crates.io first, but
/// not its dev-deps (they're not part of the published crate's requirements for
/// consumers). Master-of-deps points #1/#2.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
pub enum DepKind {
    Normal,
    Build,
    Dev,
}

/// What a repo produces (its package names) and the cross-repo dependency facts —
/// enough to compute cross-repo edges LOCALLY (no warehouse, so it's correct even
/// for a monitored workspace where the warehouse `build_order` falls back to
/// alphabetical). The "master of dependencies": `deps` carries ONLY order-gating
/// edges (in-workspace `path=` Normal/Build deps, optional INCLUDED); dev edges,
/// optional/feature-gated deps, target-`cfg` deps, and crates.io version-pins are
/// tracked separately for transparency without polluting the order.
#[derive(Debug, Clone, Default)]
pub struct RepoGraph {
    pub repo: String,
    pub produces: std::collections::BTreeSet<String>,
    /// PUBLISH-ORDER-gating dependency crate names: in-workspace (`path=`, or
    /// `workspace=true` resolving to a path) deps of kind Normal|Build, OPTIONAL
    /// included (an optional path dep is still written into the published manifest
    /// → its producer must publish first). EXCLUDES: dev-deps, `publish=false`
    /// crates' deps, and pure crates.io version-pins (no path → already on the
    /// registry → not gating for a from-source republish).
    pub deps: std::collections::BTreeSet<String>,
    /// Dependency crate names declared under a `[dev-dependencies]` table anywhere
    /// in the repo (path OR version, any member incl. `publish=false` xtasks). NOT
    /// order-gating; surfaced in the "excluded dev-dep cross-repo edges" report so
    /// the exclusion is transparent (master-of-deps point #7).
    pub dev_deps: std::collections::BTreeSet<String>,
    /// Order-gating OPTIONAL (feature-gated) path dep crate name → the feature(s)
    /// that enable it (`[features]`, incl. `dep:foo` and weak `foo?/feat`). These
    /// ARE in `deps` (real publish deps) but are also surfaced in a dedicated
    /// section (master-of-deps point #4).
    pub optional_deps: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
    /// Order-gating path dep crate name → the `[target.'cfg(…)']` string(s) it is
    /// gated under. These ARE in `deps`; surfaced tagged with the cfg
    /// (master-of-deps point #5).
    pub cfg_deps: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
    /// Cross-repo-by-NAME deps pinned to a crates.io VERSION (no `path=`) — they
    /// would be order edges in the naive name-only model but are NOT gating
    /// (already resolvable from the registry). Tracked so a path-vs-version
    /// surprise is visible (master-of-deps point #8).
    pub version_pinned: std::collections::BTreeSet<String>,
    /// PER-CRATE order-gating in-workspace dep crate names (publishable crate name
    /// → the in-workspace path Normal/Build deps, optional included). cargo publishes
    /// CRATES, not repos, so this is the granularity at which the true publish order
    /// and real cycles live — a repo-level mutual dep (facett⇄knut) is often a clean
    /// crate-level DAG (facett-pipeline→knut-popsim, knut-pipelines→facett-pipeline,
    /// no loop). Used by [`publish_order`] / [`detect_cycles`].
    pub crate_deps: std::collections::BTreeMap<String, std::collections::BTreeSet<String>>,
}

/// The real crate name a dependency entry resolves to, honoring a `package = "…"`
/// rename (what `cargo metadata`'s `Dependency.name` reports).
fn dep_real_name(key: &str, spec: &toml::Value) -> String {
    spec.as_table()
        .and_then(|t| t.get("package"))
        .and_then(|p| p.as_str())
        .unwrap_or(key)
        .to_string()
}

/// True when `spec` resolves to IN-WORKSPACE SOURCE: a direct `path = …`, or a
/// `workspace = true` inheritance whose `[workspace.dependencies]` entry (looked up
/// by real name in `ws_paths`) itself carries a path. A pure version dep (no path)
/// is crates.io-resolvable and so NOT order-gating for a from-source republish.
fn dep_is_source_path(
    spec: &toml::Value,
    real: &str,
    ws_paths: &BTreeMap<String, bool>,
) -> bool {
    match spec {
        toml::Value::Table(t) => {
            if t.contains_key("path") {
                return true;
            }
            if t.get("workspace").and_then(|w| w.as_bool()).unwrap_or(false) {
                return *ws_paths.get(real).unwrap_or(&false);
            }
            false
        }
        // A bare `foo = "1.2"` is a version pin — never a path.
        _ => false,
    }
}

/// Scan a repo's Cargo.tomls into the cross-repo dependency facts. The master
/// gatherer: resolves workspace inheritance, separates dep KINDS, keeps optional
/// + target-`cfg` deps in the order graph (tagged), and excludes dev / version-pin
/// / `publish=false` edges from ordering while still recording them for the report.
pub fn gather_repo_graph(repo: &str, root: &Path) -> Result<RepoGraph> {
    use std::collections::BTreeSet;
    let manifests: Vec<toml::Value> = find_cargo_tomls(root, 4)
        .into_iter()
        .filter_map(|p| std::fs::read_to_string(&p).ok())
        .filter_map(|t| t.parse::<toml::Value>().ok())
        .collect();

    // Pass 1: the repo's `[workspace.dependencies]` — real name → has-path. Used to
    // resolve `dep.workspace = true` inheritance back to a real path/version.
    let mut ws_paths: BTreeMap<String, bool> = BTreeMap::new();
    for doc in &manifests {
        if let Some(t) = doc
            .get("workspace")
            .and_then(|w| w.get("dependencies"))
            .and_then(|t| t.as_table())
        {
            for (key, spec) in t {
                let real = dep_real_name(key, spec);
                let has_path = spec.as_table().map(|s| s.contains_key("path")).unwrap_or(false);
                ws_paths.insert(real, has_path);
            }
        }
    }

    let mut g = RepoGraph { repo: repo.to_string(), ..Default::default() };

    for doc in &manifests {
        let package = doc.get("package");
        // `publish = false` (xtask, bench, internal test helpers): ships nothing, so
        // its deps must NEVER gate publish order (that's what turns the
        // nornir↔{holger,znippy,facett} tooling link into a false cycle). Its DEV
        // edges are still captured below for the transparency report.
        let publishable = package
            .and_then(|p| p.get("publish"))
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        let pkg_name = package
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            .map(str::to_string);
        if publishable {
            if let Some(n) = &pkg_name {
                g.produces.insert(n.clone());
                g.crate_deps.entry(n.clone()).or_default();
            }
        }

        // Enumerate every dep table in this manifest: the three top-level kinds plus
        // their `[target.'cfg(…)'.…]` variants (master-of-deps point #5).
        let kinds = [
            ("dependencies", DepKind::Normal),
            ("build-dependencies", DepKind::Build),
            ("dev-dependencies", DepKind::Dev),
        ];
        let mut tables: Vec<(DepKind, Option<String>, &toml::Value)> = Vec::new();
        for (k, kind) in kinds {
            if let Some(t) = doc.get(k) {
                tables.push((kind, None, t));
            }
        }
        if let Some(targets) = doc.get("target").and_then(|t| t.as_table()) {
            for (cfg, ct) in targets {
                for (k, kind) in kinds {
                    if let Some(t) = ct.get(k) {
                        tables.push((kind, Some(cfg.clone()), t));
                    }
                }
            }
        }

        // First find the OPTIONAL order-table dep keys (so `[features]` can be
        // mapped to the deps it enables).
        let mut optional_keys: BTreeSet<String> = BTreeSet::new();
        for (kind, _cfg, t) in &tables {
            if *kind == DepKind::Dev {
                continue;
            }
            let Some(tbl) = t.as_table() else { continue };
            for (key, spec) in tbl {
                if spec.as_table().and_then(|d| d.get("optional")).and_then(|o| o.as_bool()).unwrap_or(false) {
                    optional_keys.insert(key.clone());
                }
            }
        }
        // `[features]` → which optional dep KEYS each feature turns on. Forms:
        // `dep:foo` (explicit), `foo/feat` (enables foo), `foo?/feat` (weak — does
        // NOT enable foo), bare `foo` (enables optional dep foo). An optional dep
        // with no explicit reference gets the implicit same-named feature.
        let mut key_features: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        if let Some(feats) = doc.get("features").and_then(|f| f.as_table()) {
            for (feat, list) in feats {
                let Some(arr) = list.as_array() else { continue };
                for item in arr {
                    let Some(s) = item.as_str() else { continue };
                    let enabled = if let Some(rest) = s.strip_prefix("dep:") {
                        Some(rest.to_string())
                    } else if let Some((name, _)) = s.split_once('/') {
                        if name.ends_with('?') { None } else { Some(name.to_string()) }
                    } else {
                        Some(s.to_string())
                    };
                    if let Some(dep) = enabled {
                        if optional_keys.contains(&dep) {
                            key_features.entry(dep).or_default().insert(feat.clone());
                        }
                    }
                }
            }
        }
        for key in &optional_keys {
            // Implicit feature `foo` for an optional dep `foo` with no explicit
            // `dep:foo` mention — cargo synthesizes it.
            key_features.entry(key.clone()).or_default().insert(key.clone());
        }

        // Second pass: record edges.
        for (kind, cfg, t) in &tables {
            let Some(tbl) = t.as_table() else { continue };
            for (key, spec) in tbl {
                let real = dep_real_name(key, spec);
                if *kind == DepKind::Dev {
                    // Dev edge — captured for the transparency report, never gating.
                    // (A dep named exactly after its own repo is still its own crate
                    // dev-dep, harmless: cross-repo matching filters to producers.)
                    if real != repo {
                        g.dev_deps.insert(real);
                    }
                    continue;
                }
                // Normal / Build. Only PUBLISHABLE crates' deps gate order.
                if !publishable {
                    continue;
                }
                if dep_is_source_path(spec, &real, &ws_paths) {
                    // Per-CRATE order edge (incl. same-repo crate deps, e.g.
                    // skade-katalog→skade) — the true publish granularity. The topo
                    // filters to produced crate names, so a self-named dep is fine.
                    if let Some(pn) = &pkg_name {
                        if *pn != real {
                            g.crate_deps.entry(pn.clone()).or_default().insert(real.clone());
                        }
                    }
                    // Repo-level set skips a dep named exactly after this repo
                    // (avoids a self-loop in the coarse repo graph).
                    if real == repo {
                        continue;
                    }
                    g.deps.insert(real.clone());
                    if optional_keys.contains(key) {
                        let feats = key_features.get(key).cloned().unwrap_or_default();
                        g.optional_deps.entry(real.clone()).or_default().extend(feats);
                    }
                    if let Some(c) = cfg {
                        g.cfg_deps.entry(real.clone()).or_default().insert(c.clone());
                    }
                } else {
                    // Cross-repo-by-name but version-pinned to crates.io → not gating.
                    g.version_pinned.insert(real);
                }
            }
        }
    }
    Ok(g)
}

/// repo → the set of OTHER repos it depends on (A→B when A declares a dependency
/// on a crate B produces).
fn repo_edges(graphs: &[RepoGraph]) -> BTreeMap<String, std::collections::BTreeSet<String>> {
    let mut out: BTreeMap<String, std::collections::BTreeSet<String>> = BTreeMap::new();
    for a in graphs {
        let set = out.entry(a.repo.clone()).or_default();
        for b in graphs {
            if a.repo != b.repo && b.produces.iter().any(|c| a.deps.contains(c)) {
                set.insert(b.repo.clone());
            }
        }
    }
    out
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct TopoReport {
    /// Publish order: dependencies before dependents.
    pub order: Vec<String>,
    /// Repos left unordered because they sit on a dependency cycle (empty = DAG).
    pub cycle: Vec<String>,
}

/// Topological PUBLISH order (dependencies first), Kahn's algorithm over local
/// Cargo.toml edges. Deterministic (ties broken by name).
pub fn publish_order(graphs: &[RepoGraph]) -> TopoReport {
    let deps_on = repo_edges(graphs);
    let mut indeg: BTreeMap<String, usize> =
        deps_on.iter().map(|(r, d)| (r.clone(), d.len())).collect();
    let mut dependents: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for (a, ds) in &deps_on {
        for b in ds {
            dependents.entry(b.clone()).or_default().push(a.clone());
        }
    }
    let mut ready: std::collections::BTreeSet<String> =
        indeg.iter().filter(|&(_, &d)| d == 0).map(|(r, _)| r.clone()).collect();
    let mut order = Vec::new();
    while let Some(n) = ready.iter().next().cloned() {
        ready.remove(&n);
        order.push(n.clone());
        if let Some(deps) = dependents.get(&n) {
            for a in deps {
                if let Some(d) = indeg.get_mut(a) {
                    *d -= 1;
                    if *d == 0 {
                        ready.insert(a.clone());
                    }
                }
            }
        }
    }
    let cycle: Vec<String> =
        indeg.keys().filter(|r| !order.contains(r)).cloned().collect();
    TopoReport { order, cycle }
}

/// Transitive dependents of `repo` — the blast radius of changing it (who must be
/// re-validated / re-released).
pub fn blast_radius(graphs: &[RepoGraph], repo: &str) -> Vec<String> {
    let deps_on = repo_edges(graphs);
    let mut result = std::collections::BTreeSet::new();
    let mut stack = vec![repo.to_string()];
    while let Some(cur) = stack.pop() {
        for (a, ds) in &deps_on {
            if ds.contains(&cur) && result.insert(a.clone()) {
                stack.push(a.clone());
            }
        }
    }
    result.into_iter().collect()
}

// ─────────────────── cycle-break advisor ───────────────────

/// A concrete suggestion for breaking ONE dependency cycle: the cycle's members,
/// the single edge cheapest to cut (the one justified by the FEWEST crates), the
/// crates on that edge, and human advice.
#[derive(Debug, Clone, Serialize)]
pub struct CycleAdvice {
    /// The strongly-connected component = the repos mutually entangled.
    pub members: Vec<String>,
    /// Suggested edge to cut: `cut_from` depends on `cut_to`.
    pub cut_from: String,
    pub cut_to: String,
    /// The crates `cut_to` produces that `cut_from` depends on — the thing to
    /// extract or make optional to break the edge.
    pub via: Vec<String>,
    pub rationale: String,
}

/// Crates that justify the edge `from → to`: the ones `to` produces and `from`
/// depends on. The smaller this set, the cheaper the edge is to cut.
fn edge_via(graphs: &[RepoGraph], from: &str, to: &str) -> Vec<String> {
    let (Some(f), Some(t)) = (
        graphs.iter().find(|g| g.repo == from),
        graphs.iter().find(|g| g.repo == to),
    ) else {
        return vec![];
    };
    let mut v: Vec<String> = t.produces.intersection(&f.deps).cloned().collect();
    v.sort();
    v
}

/// Tarjan's strongly-connected components over the repo dependency graph. Each SCC
/// with more than one repo (or a self-loop) is a dependency cycle. Returns SCCs as
/// sorted member lists, deterministic.
fn sccs(edges: &BTreeMap<String, std::collections::BTreeSet<String>>) -> Vec<Vec<String>> {
    use std::collections::BTreeSet;
    let nodes: Vec<String> = edges.keys().cloned().collect();
    let mut index: BTreeMap<String, usize> = BTreeMap::new();
    let mut low: BTreeMap<String, usize> = BTreeMap::new();
    let mut on_stack: BTreeSet<String> = BTreeSet::new();
    let mut stack: Vec<String> = Vec::new();
    let mut idx = 0usize;
    let mut out: Vec<Vec<String>> = Vec::new();

    // Iterative Tarjan (explicit work stack) so deep graphs don't blow the call
    // stack. Each frame walks a node's successors one at a time.
    for start in &nodes {
        if index.contains_key(start) {
            continue;
        }
        let mut work: Vec<(String, usize)> = vec![(start.clone(), 0)];
        while let Some((v, mut i)) = work.pop() {
            if i == 0 {
                index.insert(v.clone(), idx);
                low.insert(v.clone(), idx);
                idx += 1;
                stack.push(v.clone());
                on_stack.insert(v.clone());
            }
            let succs: Vec<String> =
                edges.get(&v).map(|s| s.iter().cloned().collect()).unwrap_or_default();
            let mut recursed = false;
            while i < succs.len() {
                let w = &succs[i];
                if !index.contains_key(w) {
                    work.push((v.clone(), i + 1));
                    work.push((w.clone(), 0));
                    recursed = true;
                    break;
                } else if on_stack.contains(w) {
                    let lw = index[w];
                    let lv = low[&v];
                    low.insert(v.clone(), lv.min(lw));
                }
                i += 1;
            }
            if recursed {
                continue;
            }
            // Done with v: fold its low-link into its parent (top of work stack).
            if low[&v] == index[&v] {
                let mut comp = Vec::new();
                while let Some(w) = stack.pop() {
                    on_stack.remove(&w);
                    comp.push(w.clone());
                    if w == v {
                        break;
                    }
                }
                comp.sort();
                out.push(comp);
            }
            if let Some((parent, _)) = work.last() {
                let lp = low[parent];
                let lv = low[&v];
                low.insert(parent.clone(), lp.min(lv));
            }
        }
    }
    out
}

/// For every dependency CYCLE (SCC > 1, or a self-loop), suggest the cheapest edge
/// to cut: the intra-cycle edge justified by the fewest crates (ties broken by
/// name). Pure — operates on the local Cargo.toml graph. Empty when the graph is a
/// clean DAG.
pub fn cycle_advice(graphs: &[RepoGraph]) -> Vec<CycleAdvice> {
    let edges = repo_edges(graphs);
    let mut advice = Vec::new();
    for comp in sccs(&edges) {
        let in_comp: std::collections::BTreeSet<&str> = comp.iter().map(|s| s.as_str()).collect();
        let self_loop =
            comp.len() == 1 && edges.get(&comp[0]).map(|d| d.contains(&comp[0])).unwrap_or(false);
        if comp.len() < 2 && !self_loop {
            continue;
        }
        // Candidate edges: intra-cycle (from → to, both in the SCC).
        let mut best: Option<(String, String, Vec<String>)> = None;
        for from in &comp {
            if let Some(deps) = edges.get(from) {
                for to in deps {
                    if !in_comp.contains(to.as_str()) {
                        continue;
                    }
                    let via = edge_via(graphs, from, to);
                    let better = match &best {
                        None => true,
                        Some((bf, bt, bv)) => {
                            (via.len(), from.as_str(), to.as_str())
                                < (bv.len(), bf.as_str(), bt.as_str())
                        }
                    };
                    if better {
                        best = Some((from.clone(), to.clone(), via));
                    }
                }
            }
        }
        if let Some((cut_from, cut_to, via)) = best {
            let rationale = if via.is_empty() {
                format!("cut `{cut_from}{cut_to}` (fewest crates)")
            } else if via.len() == 1 {
                format!(
                    "`{cut_from}{cut_to}` rides on one crate (`{}`); extract it into a leaf crate both depend on, or make the dep optional/dev-only",
                    via[0]
                )
            } else {
                format!(
                    "`{cut_from}{cut_to}` rides on {} crates ({}); extract them into a shared leaf crate, or make the dep optional/dev-only",
                    via.len(),
                    via.join(", ")
                )
            };
            advice.push(CycleAdvice { members: comp, cut_from, cut_to, via, rationale });
        }
    }
    advice
}

// ─────────────────────── report ───────────────────────

/// One repo→repo dependency edge: `from` depends on `to` because `to` produces
/// one of the crates `from` declares. Carries the `via` crates so the 🧬 release
/// dashboard can label the edge. This is the same relation `repo_edges` computes
/// for the topo/blast analysis, exposed so the dashboard draws the SAME graph
/// without re-scanning Cargo.tomls.
#[derive(Debug, Clone, Serialize)]
pub struct RepoEdge {
    pub from: String,
    pub to: String,
    pub via: Vec<String>,
}

/// The repo→repo dependency edges (with the `via` crates), as a flat list — the
/// graph the 🧬 dashboard paints. Pure: derived from the gathered repo graphs.
pub fn repo_dep_edges(graphs: &[RepoGraph]) -> Vec<RepoEdge> {
    let mut out = Vec::new();
    for a in graphs {
        for b in graphs {
            if a.repo == b.repo {
                continue;
            }
            let mut via: Vec<String> =
                b.produces.iter().filter(|c| a.deps.contains(*c)).cloned().collect();
            if !via.is_empty() {
                via.sort();
                out.push(RepoEdge { from: a.repo.clone(), to: b.repo.clone(), via });
            }
        }
    }
    out.sort_by(|x, y| (&x.from, &x.to).cmp(&(&y.from, &y.to)));
    out
}

// ───────── master-of-deps: kind-tagged cross-repo sections ─────────

/// A cross-repo DEV-dependency edge — `from` dev-depends on a crate `to` produces.
/// Deliberately EXCLUDED from publish order (a dev-dep isn't part of the published
/// crate's requirements). Listed so the exclusion is transparent.
#[derive(Debug, Clone, Serialize)]
pub struct DevEdge {
    pub from: String,
    pub to: String,
    pub via: Vec<String>,
}

/// A feature-gated (optional) cross-repo dependency — KEPT in the order graph
/// (cargo writes optional deps into the published manifest) but surfaced with the
/// enabling feature(s), e.g. `nornir --[optional, feature=facett-viz]--> facett`.
#[derive(Debug, Clone, Serialize)]
pub struct OptionalCrossDep {
    pub from: String,
    pub to: String,
    pub krate: String,
    pub features: Vec<String>,
}

/// A `[target.'cfg(…)']`-gated cross-repo dependency — a real (order-gating) dep
/// tagged with the platform cfg it's conditional on.
#[derive(Debug, Clone, Serialize)]
pub struct CfgCrossDep {
    pub from: String,
    pub to: String,
    pub krate: String,
    pub cfgs: Vec<String>,
}

/// A real dependency CYCLE that REMAINS in the order-relevant (non-dev, path) graph
/// — these are NOT silently broken; doctor reports the entangled repos and every
/// offending intra-cycle edge so the cause is explicit.
#[derive(Debug, Clone, Serialize)]
pub struct DepCycle {
    pub members: Vec<String>,
    pub edges: Vec<RepoEdge>,
}

/// Map each produced crate name → the repo that produces it (publishable crates).
fn producer_index(graphs: &[RepoGraph]) -> BTreeMap<String, String> {
    let mut idx = BTreeMap::new();
    for g in graphs {
        for c in &g.produces {
            idx.insert(c.clone(), g.repo.clone());
        }
    }
    idx
}

/// Cross-repo DEV edges (excluded from order): for each repo's `dev_deps`, the
/// producer repo of each dev-depended crate. Grouped per `from→to` with the
/// justifying crate names. Master-of-deps point #7.
pub fn excluded_dev_edges(graphs: &[RepoGraph]) -> Vec<DevEdge> {
    let producer = producer_index(graphs);
    let mut grouped: BTreeMap<(String, String), std::collections::BTreeSet<String>> = BTreeMap::new();
    for g in graphs {
        for krate in &g.dev_deps {
            if let Some(to) = producer.get(krate) {
                if *to != g.repo {
                    grouped.entry((g.repo.clone(), to.clone())).or_default().insert(krate.clone());
                }
            }
        }
    }
    grouped
        .into_iter()
        .map(|((from, to), via)| DevEdge { from, to, via: via.into_iter().collect() })
        .collect()
}

/// Feature-gated (optional) cross-repo deps with the feature(s) that enable them.
/// Master-of-deps point #4.
pub fn optional_cross_deps(graphs: &[RepoGraph]) -> Vec<OptionalCrossDep> {
    let producer = producer_index(graphs);
    let mut out = Vec::new();
    for g in graphs {
        for (krate, feats) in &g.optional_deps {
            if let Some(to) = producer.get(krate) {
                if *to != g.repo {
                    out.push(OptionalCrossDep {
                        from: g.repo.clone(),
                        to: to.clone(),
                        krate: krate.clone(),
                        features: feats.iter().cloned().collect(),
                    });
                }
            }
        }
    }
    out.sort_by(|a, b| (&a.from, &a.krate).cmp(&(&b.from, &b.krate)));
    out
}

/// Cross-repo deps a repo declares against a crates.io VERSION (no `path=`) for a
/// crate ANOTHER repo produces — e.g. `facett-matrix`'s `nornir-testmatrix = "0.2"`
/// or `nornir`'s `znippy-zoomies = "0.1.13"`. These resolve from the registry, so
/// they are NOT order-gating (the producer needn't publish first) — surfaced so the
/// path-vs-version split is visible (master-of-deps point #8). The false
/// `facett → nornir` edge that mis-ordered nornir lived here.
pub fn version_pinned_cross_deps(graphs: &[RepoGraph]) -> Vec<RepoEdge> {
    let producer = producer_index(graphs);
    let mut grouped: BTreeMap<(String, String), std::collections::BTreeSet<String>> = BTreeMap::new();
    for g in graphs {
        for krate in &g.version_pinned {
            if let Some(to) = producer.get(krate) {
                if *to != g.repo {
                    grouped.entry((g.repo.clone(), to.clone())).or_default().insert(krate.clone());
                }
            }
        }
    }
    grouped
        .into_iter()
        .map(|((from, to), via)| RepoEdge { from, to, via: via.into_iter().collect() })
        .collect()
}

/// `[target.'cfg(…)']`-gated cross-repo deps, tagged with the cfg. Point #5.
pub fn cfg_cross_deps(graphs: &[RepoGraph]) -> Vec<CfgCrossDep> {
    let producer = producer_index(graphs);
    let mut out = Vec::new();
    for g in graphs {
        for (krate, cfgs) in &g.cfg_deps {
            if let Some(to) = producer.get(krate) {
                if *to != g.repo {
                    out.push(CfgCrossDep {
                        from: g.repo.clone(),
                        to: to.clone(),
                        krate: krate.clone(),
                        cfgs: cfgs.iter().cloned().collect(),
                    });
                }
            }
        }
    }
    out.sort_by(|a, b| (&a.from, &a.krate).cmp(&(&b.from, &b.krate)));
    out
}

/// The CRATE-level order graph: crate name → owning repo, and crate name → its
/// in-workspace order-gating dep crate names (filtered to crates actually produced
/// somewhere). cargo publishes CRATES, so this is the granularity where the true
/// order + real cycles live — a repo-level mutual dep that's a clean crate-level DAG
/// (facett⇄knut: facett-pipeline→knut-popsim, knut-pipelines→facett-pipeline) is NOT
/// a real publish cycle and must not block the order.
fn crate_graph(
    graphs: &[RepoGraph],
) -> (
    BTreeMap<String, String>,
    BTreeMap<String, std::collections::BTreeSet<String>>,
) {
    use std::collections::BTreeSet;
    let mut owner: BTreeMap<String, String> = BTreeMap::new();
    let produced: BTreeSet<String> =
        graphs.iter().flat_map(|g| g.crate_deps.keys().cloned()).collect();
    let mut adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for g in graphs {
        for (c, deps) in &g.crate_deps {
            owner.entry(c.clone()).or_insert_with(|| g.repo.clone());
            let e = adj.entry(c.clone()).or_default();
            for d in deps {
                if d != c && produced.contains(d) {
                    e.insert(d.clone());
                }
            }
        }
    }
    (owner, adj)
}

/// Dependency CYCLES at CRATE granularity — Tarjan SCCs over [`crate_graph`]. Each
/// SCC>1 (or self-loop) is a REAL publish cycle (no crate-level interleaving can
/// resolve it), reported with its crates + the offending intra-cycle edges. Empty =
/// publishable as a clean crate DAG (even if repos look mutually entangled).
/// Master-of-deps point #3.
pub fn detect_cycles(graphs: &[RepoGraph]) -> Vec<DepCycle> {
    let (_owner, adj) = crate_graph(graphs);
    let mut out = Vec::new();
    for comp in sccs(&adj) {
        let in_comp: std::collections::BTreeSet<&str> = comp.iter().map(|s| s.as_str()).collect();
        let self_loop =
            comp.len() == 1 && adj.get(&comp[0]).map(|d| d.contains(&comp[0])).unwrap_or(false);
        if comp.len() < 2 && !self_loop {
            continue;
        }
        let mut cyc_edges = Vec::new();
        for from in &comp {
            if let Some(deps) = adj.get(from) {
                for to in deps {
                    if in_comp.contains(to.as_str()) {
                        cyc_edges.push(RepoEdge { from: from.clone(), to: to.clone(), via: vec![] });
                    }
                }
            }
        }
        out.push(DepCycle { members: comp, edges: cyc_edges });
    }
    out
}

/// PUBLISH order over REPOS, made cycle-proof by SCC CONDENSATION: repo-level
/// mutual deps (facett⇄knut) collapse into one super-node, the condensation DAG is
/// topo-sorted deps-first, and each super-node expands to its member repos
/// (alphabetical). A repo nothing publishable depends on (e.g. `nornir`) is a sink →
/// sorts LAST, exactly as the user expects. `cycle` carries repos on a REAL
/// crate-level cycle (from [`detect_cycles`]) — empty when the entanglement is a
/// clean interleaved crate DAG, so a repo-level SCC alone does NOT flag a "cycle".
/// Deterministic (ties by smallest member name). Master-of-deps points #2/#3.
pub fn crate_publish_order(graphs: &[RepoGraph]) -> TopoReport {
    use std::collections::BTreeSet;
    let edges = repo_edges(graphs); // from → repos it depends on
    let comps = sccs(&edges); // each: sorted member list
    let n = comps.len();
    let mut comp_of: BTreeMap<String, usize> = BTreeMap::new();
    for (i, c) in comps.iter().enumerate() {
        for r in c {
            comp_of.insert(r.clone(), i);
        }
    }
    // Condensation: comp → the comps it depends on.
    let mut cadj: Vec<BTreeSet<usize>> = vec![BTreeSet::new(); n];
    for (from, tos) in &edges {
        let cf = comp_of[from];
        for to in tos {
            let ct = comp_of[to];
            if cf != ct {
                cadj[cf].insert(ct);
            }
        }
    }
    // Kahn deps-first over the condensation. indeg(comp) = #comps it depends on.
    let mut indeg: Vec<usize> = (0..n).map(|c| cadj[c].len()).collect();
    let mut consumers: Vec<Vec<usize>> = vec![Vec::new(); n];
    for (cf, deps) in cadj.iter().enumerate() {
        for &ct in deps {
            consumers[ct].push(cf);
        }
    }
    // Ready set ordered by the comp's smallest member name → stable, readable order.
    let key = |c: usize| comps[c].first().cloned().unwrap_or_default();
    let mut ready: BTreeSet<(String, usize)> = (0..n)
        .filter(|&c| indeg[c] == 0)
        .map(|c| (key(c), c))
        .collect();
    let mut order: Vec<String> = Vec::new();
    while let Some((k, c)) = ready.iter().next().cloned() {
        ready.remove(&(k, c));
        // Expand the SCC into its member repos (already sorted).
        order.extend(comps[c].iter().cloned());
        for &con in &consumers[c] {
            indeg[con] -= 1;
            if indeg[con] == 0 {
                ready.insert((key(con), con));
            }
        }
    }
    // REAL cycles are crate-level: only those block publishability. A repo-level SCC
    // that's a clean crate DAG is fully ordered above and reported as NO cycle. Map
    // the crate-cycle members back to their owning repos for the `cycle` field.
    let owner = crate_graph(graphs).0;
    let cycle: Vec<String> = detect_cycles(graphs)
        .iter()
        .flat_map(|c| c.members.iter().filter_map(|kr| owner.get(kr).cloned()))
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect();
    TopoReport { order, cycle }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct DoctorReport {
    pub dirty: Vec<RepoDirty>,
    pub skew: Vec<CrateSkew>,
    pub topo: TopoReport,
    /// Per dirty repo → its blast radius (transitive dependents to re-validate).
    pub blast: BTreeMap<String, Vec<String>>,
    /// One suggestion per dependency cycle for how to break it. Empty = clean DAG.
    #[serde(default)]
    pub cycle_advice: Vec<CycleAdvice>,
    /// The repo→repo dependency edges (A depends on B). The 🧬 release dashboard
    /// draws its gate-overlaid graph from this. Empty = no inter-repo edges.
    #[serde(default)]
    pub repo_edges: Vec<RepoEdge>,
    /// Direct patch-fork blocks: each `[patch.crates-io]` redirect to a
    /// non-registry (`path`/`git`) fork. Empty = nothing patched to a fork.
    #[serde(default)]
    pub patch_forks: Vec<PatchForkBlock>,
    /// The TRANSITIVE promote-blocked crate set: every workspace crate that, or
    /// whose workspace-internal dep, rides a patch-fork. These are EXCLUDED from
    /// a crates.io publish. Empty = nothing blocked.
    #[serde(default)]
    pub promote_blocked: Vec<String>,
    /// Cross-repo DEV edges deliberately EXCLUDED from publish order (a dev-dep is
    /// not part of the published crate's requirements). Listed for transparency.
    #[serde(default)]
    pub excluded_dev_edges: Vec<DevEdge>,
    /// Feature-gated (optional) cross-repo deps — KEPT in the order graph, surfaced
    /// with the enabling feature(s).
    #[serde(default)]
    pub optional_cross_deps: Vec<OptionalCrossDep>,
    /// `[target.'cfg(…)']`-gated cross-repo deps, tagged with the cfg.
    #[serde(default)]
    pub cfg_cross_deps: Vec<CfgCrossDep>,
    /// Real dependency cycles remaining in the order-relevant graph. Empty = clean.
    #[serde(default)]
    pub cycles: Vec<DepCycle>,
    /// Cross-repo deps pinned to a crates.io VERSION (no path) — NOT order-gating
    /// (resolve from the registry). Surfaces the path-vs-version split.
    #[serde(default)]
    pub version_pinned_cross_deps: Vec<RepoEdge>,
    /// PUBLISH PRE-FLIGHT: publishable crates whose Normal/Build `path` deps lack a
    /// `version` — the `cargo publish` manifest-verify blocker, caught statically
    /// (no rehearse needed). Empty = every path dep is publish-ready.
    #[serde(default)]
    pub path_dep_version_gaps: Vec<PathDepVersionGap>,
}

/// Gather + analyze: dirty trees, version skew, publish order, and the blast
/// radius of each dirty repo, for the given repos.
pub fn run(repos: &[(String, PathBuf)], policy: &DepPolicy) -> Result<DoctorReport> {
    let externals = repos
        .iter()
        .map(|(name, path)| gather_repo_externals(name, path))
        .collect::<Result<Vec<_>>>()?;
    let graphs = repos
        .iter()
        .map(|(name, path)| gather_repo_graph(name, path))
        .collect::<Result<Vec<_>>>()?;

    let dirty = check_dirty(repos);
    let blast = dirty
        .iter()
        .filter(|d| d.dirty)
        .map(|d| (d.repo.clone(), blast_radius(&graphs, &d.repo)))
        .collect();

    // Read each repo's lockfile so skew hints can tell a free bump from one a
    // transitive dependency pins (e.g. `iceberg 0.9` holding `arrow` at 57).
    let repo_locks: BTreeMap<String, String> = repos
        .iter()
        .filter_map(|(name, path)| {
            std::fs::read_to_string(path.join("Cargo.lock")).ok().map(|t| (name.clone(), t))
        })
        .collect();

    let mut skew = analyze_skew(&externals, policy);
    enrich_transitive_pins(&mut skew, &repo_locks);

    // Patch-fork promote gate (CRATE-precise): scan every repo for `[patch.crates-io]`
    // redirects to a path/git fork, classify each as a FOREIGN fork (patched dep not
    // produced anywhere → hard blocker) vs a safe own-crate override, and take the
    // PER-CRATE transitive block closure against the foreign forks. This blocks only
    // crates that genuinely (transitively) depend on the forked dep — so a workspace
    // member like `znippy-common` next to `znippy-iceberg` stays publishable.
    let block = compute_promote_block(
        repos.iter().map(|(n, p)| (n.clone(), p.as_path())),
    );
    let patch_forks = block.forks;
    let promote_blocked: Vec<String> = block.blocked.into_iter().collect();

    // The publish order + cycles are computed at CRATE granularity (cargo publishes
    // crates, not repos), so a repo-level mutual dep that's a clean crate DAG doesn't
    // create a false cycle. `cycle_advice` (repo-level cut suggestions) is only
    // meaningful when a REAL crate-level cycle remains — otherwise the repo
    // entanglement resolves by publishing crates in interleaved order, no cut needed.
    let cycles = detect_cycles(&graphs);
    let cycle_advice = if cycles.is_empty() { Vec::new() } else { cycle_advice(&graphs) };

    Ok(DoctorReport {
        dirty,
        skew,
        topo: crate_publish_order(&graphs),
        blast,
        cycle_advice,
        repo_edges: repo_dep_edges(&graphs),
        patch_forks,
        promote_blocked,
        excluded_dev_edges: excluded_dev_edges(&graphs),
        optional_cross_deps: optional_cross_deps(&graphs),
        cfg_cross_deps: cfg_cross_deps(&graphs),
        cycles,
        version_pinned_cross_deps: version_pinned_cross_deps(&graphs),
        path_dep_version_gaps: scan_path_dep_version_gaps(repos),
    })
}

/// Human-readable advisory report (the CLI-parity table). All hints, no mutation.
pub fn format_report(report: &DoctorReport) -> String {
    let mut s = String::new();
    s.push_str("nornir release doctor — advisory\n\n");

    s.push_str("Working trees:\n");
    let dirty: Vec<_> = report.dirty.iter().filter(|d| d.dirty).collect();
    if dirty.is_empty() {
        s.push_str("  ✅ all clean\n");
    } else {
        for d in &dirty {
            s.push_str(&format!("  🟡 {} — uncommitted changes\n", d.repo));
        }
    }
    for d in report.dirty.iter().filter(|d| d.error.is_some()) {
        s.push_str(&format!("{}{}\n", d.repo, d.error.as_deref().unwrap_or("")));
    }

    // Publish pre-flight: the exact `cargo publish` manifest blocker, found up front.
    s.push_str("\nPublish preflight — path deps need a version:\n");
    if report.path_dep_version_gaps.is_empty() {
        s.push_str("  ✅ every path dep of a publishable crate carries a version\n");
    } else {
        let fixable: Vec<_> =
            report.path_dep_version_gaps.iter().filter(|g| g.dep_owner.is_some()).collect();
        let decide: Vec<_> =
            report.path_dep_version_gaps.iter().filter(|g| g.dep_owner.is_none()).collect();
        if !fixable.is_empty() {
            s.push_str("  auto-fixable (member-owned — add version=):\n");
            for g in &fixable {
                let ver = g
                    .suggested_version
                    .as_deref()
                    .map(|v| format!("version = \"{v}\""))
                    .unwrap_or_else(|| "version = \"<its version>\"".to_string());
                let ws = if g.via_workspace { " [via workspace.dependencies]" } else { "" };
                s.push_str(&format!(
                    "    🔧 {}/{}: {}{}  💡 {}{}\n",
                    g.repo, g.manifest, g.crate_name, g.dep, ver, ws
                ));
            }
        }
        if !decide.is_empty() {
            s.push_str(
                "  ⛔ needs decision (NON-member dep — join the release cascade or publish it first):\n",
            );
            for g in &decide {
                s.push_str(&format!(
                    "{}/{}: {}{}  (not a release member)\n",
                    g.repo, g.manifest, g.crate_name, g.dep
                ));
            }
        }
    }

    s.push_str("\nExternal dependency skew:\n");
    if report.skew.is_empty() {
        s.push_str("  ✅ no divergence\n");
    } else {
        for c in &report.skew {
            let forbidden = c.entries.iter().any(|e| e.status == SkewStatus::Forbidden);
            s.push_str(&format!("  {} (target {})", c.crate_name, c.target));
            if forbidden {
                s.push_str("  ⚠ FORBIDDEN version present");
            }
            s.push('\n');
            for e in &c.entries {
                let mark = match e.status {
                    SkewStatus::Ok => "",
                    SkewStatus::Behind if e.held_by_transitive_pin => "",
                    SkewStatus::Behind => "·",
                    SkewStatus::Forbidden => "",
                };
                let note = if e.held_by_transitive_pin {
                    format!("  (held: lock already resolves {}, a transitive dep pins {})", c.target, e.version)
                } else {
                    String::new()
                };
                s.push_str(&format!("      {} {} {}{}\n", mark, e.repo, e.version, note));
            }
            // Split the bump hint: repos that can bump freely vs ones a transitive
            // pin holds back (where a manifest bump alone won't take).
            let held: Vec<&str> = c
                .entries
                .iter()
                .filter(|e| e.status == SkewStatus::Behind && e.held_by_transitive_pin)
                .map(|e| e.repo.as_str())
                .collect();
            let free: Vec<&str> = c
                .entries
                .iter()
                .filter(|e| e.status != SkewStatus::Ok && !e.held_by_transitive_pin)
                .map(|e| e.repo.as_str())
                .collect();
            if !free.is_empty() {
                s.push_str(&format!("    💡 bump → {}: {}\n", c.target, free.join(", ")));
            }
            if !held.is_empty() {
                s.push_str(&format!(
                    "    ⛔ blocked → {}: a transitive dep pins {} (run `cargo tree -i {}` to find it)\n",
                    held.join(", "),
                    c.crate_name,
                    c.crate_name,
                ));
            }
        }
    }

    s.push_str("\nPublish order (dependencies first):\n");
    if report.topo.order.is_empty() {
        s.push_str("  (no repos)\n");
    } else {
        s.push_str(&format!("  {}\n", report.topo.order.join("")));
    }
    if !report.topo.cycle.is_empty() {
        s.push_str(&format!("  ⚠ dependency cycle, unordered: {}\n", report.topo.cycle.join(", ")));
    }
    if !report.cycle_advice.is_empty() {
        s.push_str("\nBreak the cycle (suggested cuts):\n");
        for a in &report.cycle_advice {
            s.push_str(&format!("{} — 💡 {}\n", a.members.join(""), a.rationale));
        }
    }

    // Cycles: empty = good. Otherwise the offending edges, made explicit (never
    // silently broken). Detected at CRATE granularity — a repo-level mutual dep that
    // publishes fine as an interleaved crate DAG is NOT reported as a cycle.
    s.push_str("\nCycles (crate-level publish graph):\n");
    if report.cycles.is_empty() {
        s.push_str("  ✅ none\n");
    } else {
        for c in &report.cycles {
            s.push_str(&format!("{}\n", c.members.join("")));
            for e in &c.edges {
                let via = if e.via.is_empty() { String::new() } else { format!(" (via {})", e.via.join(", ")) };
                s.push_str(&format!("      {}{}{}\n", e.from, e.to, via));
            }
        }
    }

    // Excluded dev-dep cross-repo edges — transparency for what is NOT order-gating.
    if !report.excluded_dev_edges.is_empty() {
        s.push_str("\nExcluded dev-dep cross-repo edges (not order-gating):\n");
        for e in &report.excluded_dev_edges {
            let via = if e.via.is_empty() { String::new() } else { format!(" [{}]", e.via.join(", ")) };
            s.push_str(&format!("  {} --dev--> {}{}\n", e.from, e.to, via));
        }
    }

    // Feature-gated / optional cross-repo deps (kept in order, surfaced).
    if !report.optional_cross_deps.is_empty() {
        s.push_str("\nFeature-gated / optional cross-repo deps:\n");
        for d in &report.optional_cross_deps {
            let feats = if d.features.is_empty() {
                "optional".to_string()
            } else {
                format!("optional, feature={}", d.features.join("|"))
            };
            s.push_str(&format!("  {} --[{}]--> {} ({})\n", d.from, feats, d.krate, d.to));
        }
    }

    // target-cfg cross-repo deps.
    if !report.cfg_cross_deps.is_empty() {
        s.push_str("\nTarget-cfg cross-repo deps:\n");
        for d in &report.cfg_cross_deps {
            s.push_str(&format!("  {} --[{}]--> {} ({})\n", d.from, d.cfgs.join(" | "), d.krate, d.to));
        }
    }

    // crates.io-pinned cross-repo deps — the path-vs-version split (point #8).
    if !report.version_pinned_cross_deps.is_empty() {
        s.push_str("\nCrates.io version-pinned cross-repo deps (not order-gating):\n");
        for e in &report.version_pinned_cross_deps {
            s.push_str(&format!("  {} --version--> {} [{}]\n", e.from, e.to, e.via.join(", ")));
        }
    }

    if !report.patch_forks.is_empty() {
        s.push_str("\nPatch-fork promote gate:\n");
        let kind_of = |b: &PatchForkBlock| match b.fork_kind {
            ForkKind::Path => "path",
            ForkKind::Git => "git",
        };
        // A fork whose patched dep we don't (re)publish ourselves is a HARD blocker:
        // either a third-party crate we forked (iceberg) or one of our own crates that
        // itself rides the fork (skade) — both leave stock resolution incompatible.
        let foreign: Vec<&PatchForkBlock> =
            report.patch_forks.iter().filter(|b| b.is_foreign_fork).collect();
        for b in &foreign {
            s.push_str(&format!(
                "  ⛔ promote-blocked: {} rides a patch-fork ({}{} [{}]); \
                 publishing strips it → stock {} would be incompatible. \
                 Unblock: publish {}'s real version, or wait for upstream.\n",
                b.crate_name, b.patched_dep, b.source, kind_of(b), b.patched_dep, b.patched_dep,
            ));
        }
        // Own-crate path/git overrides are SAFE — publish-order covers them.
        let overrides: Vec<&PatchForkBlock> =
            report.patch_forks.iter().filter(|b| !b.is_foreign_fork).collect();
        for b in &overrides {
            s.push_str(&format!(
                "  ℹ️  local dev override (safe): {}{} [{}] — our own crate; \
                 stripped on publish, publish-order resolves it.\n",
                b.patched_dep, b.source, kind_of(b),
            ));
        }
        // The full transitive crate set the foreign forks hold from crates.io.
        if !report.promote_blocked.is_empty() {
            s.push_str(&format!(
                "  ⛔ held from crates.io ({} crate(s) that transitively need a forked dep): {}\n",
                report.promote_blocked.len(),
                report.promote_blocked.join(", "),
            ));
        }
        // Only safe overrides, nothing genuinely held → say so explicitly.
        if foreign.is_empty() && report.promote_blocked.is_empty() {
            s.push_str("  ✅ no foreign forks — all crates promotable\n");
        }
    }

    let blast: Vec<_> = report.blast.iter().filter(|(_, d)| !d.is_empty()).collect();
    if !blast.is_empty() {
        s.push_str("\nBlast radius of dirty repos (re-validate on change):\n");
        for (repo, deps) in blast {
            s.push_str(&format!("  {}{}\n", repo, deps.join(", ")));
        }
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;

    fn repo(name: &str, deps: &[(&str, &str)]) -> RepoExternals {
        RepoExternals {
            repo: name.to_string(),
            deps: deps.iter().map(|(c, v)| (c.to_string(), v.to_string())).collect(),
        }
    }

    /// ACCEPTANCE: reproduce the 2026-06-19 arrow-58 hand analysis automatically —
    /// znippy on 58 (target), skade/nornir/knut on 57 (behind), facett/korp on 56
    /// (behind + FORBIDDEN), and the bump set = everyone but znippy.
    #[test]
    fn arrow58_case_matches_hand_analysis() {
        let repos = [
            repo("znippy", &[("arrow", "58.3.0"), ("serde", "1")]),
            repo("skade", &[("arrow", "57.1"), ("serde", "1")]),
            repo("nornir", &[("arrow", "57"), ("serde", "1")]),
            repo("knut", &[("arrow", "57"), ("serde", "1")]),
            repo("facett", &[("arrow", "56"), ("serde", "1")]),
            repo("korp", &[("arrow", "56"), ("serde", "1")]),
        ];
        let policy = DepPolicy {
            forbidden: vec![ForbiddenDep { crate_name: "arrow".into(), version: "56".into() }],
        };

        let skew = analyze_skew(&repos, &policy);

        // serde is identical everywhere → not surfaced. Only arrow skews.
        assert_eq!(skew.len(), 1, "only arrow should be flagged");
        let arrow = &skew[0];
        assert_eq!(arrow.crate_name, "arrow");
        assert_eq!(arrow.target, "58.3.0", "target = highest declared (znippy)");
        assert!(arrow.diverged);

        let status = |r: &str| {
            arrow.entries.iter().find(|e| e.repo == r).map(|e| e.status.clone()).unwrap()
        };
        assert_eq!(status("znippy"), SkewStatus::Ok);
        assert_eq!(status("skade"), SkewStatus::Behind);
        assert_eq!(status("nornir"), SkewStatus::Behind);
        assert_eq!(status("knut"), SkewStatus::Behind);
        assert_eq!(status("facett"), SkewStatus::Forbidden);
        assert_eq!(status("korp"), SkewStatus::Forbidden);

        let mut bump = arrow.bump_repos();
        bump.sort();
        assert_eq!(bump, vec!["facett", "knut", "korp", "nornir", "skade"]);
    }

    /// Bug #19: a `0.x` forbid must ban only that minor line, not every `0.x`.
    #[test]
    fn forbidden_zero_x_compares_on_minor() {
        let policy = DepPolicy {
            forbidden: vec![ForbiddenDep { crate_name: "tokio".into(), version: "0.9".into() }],
        };
        // 0.9.x is forbidden…
        assert!(is_forbidden("tokio", "0.9.3", &policy));
        // …but a DIFFERENT 0.x minor (0.10) is NOT.
        assert!(!is_forbidden("tokio", "0.10.1", &policy));
        // A >=1.0 forbid still bans on major alone.
        let p1 = DepPolicy {
            forbidden: vec![ForbiddenDep { crate_name: "arrow".into(), version: "56".into() }],
        };
        assert!(is_forbidden("arrow", "56.2.1", &p1));
        assert!(!is_forbidden("arrow", "57.0.0", &p1));
    }

    #[test]
    fn no_skew_when_all_agree() {
        let repos = [repo("a", &[("arrow", "58")]), repo("b", &[("arrow", "58")])];
        assert!(analyze_skew(&repos, &DepPolicy::default()).is_empty());
    }

    #[test]
    fn forbidden_surfaces_even_without_divergence() {
        // Both on 56 (no divergence) but 56 is forbidden → still flagged.
        let repos = [repo("a", &[("arrow", "56")]), repo("b", &[("arrow", "56")])];
        let policy = DepPolicy {
            forbidden: vec![ForbiddenDep { crate_name: "arrow".into(), version: "56".into() }],
        };
        let skew = analyze_skew(&repos, &policy);
        assert_eq!(skew.len(), 1);
        assert!(skew[0].entries.iter().all(|e| e.status == SkewStatus::Forbidden));
    }

    #[test]
    fn crate_majors_in_lock_collects_all_majors() {
        let lock = r#"
[[package]]
name = "arrow"
version = "57.3.1"

[[package]]
name = "arrow"
version = "58.3.0"

[[package]]
name = "serde"
version = "1.0.2"
"#;
        assert_eq!(crate_majors_in_lock(lock, "arrow"), [57u64, 58].into_iter().collect());
        assert_eq!(crate_majors_in_lock(lock, "serde"), [1u64].into_iter().collect());
        assert!(crate_majors_in_lock(lock, "absent").is_empty());
    }

    /// The real nornir/arrow case: nornir declares arrow 57 (behind znippy's 58.3.0)
    /// but its lock resolves BOTH 57 and 58 (58 pulled transitively via znippy), so a
    /// manifest bump alone can't take — `iceberg 0.9` pins 57. Mark it held.
    #[test]
    fn transitive_pin_marks_dual_major_behind_repo() {
        let repos = [
            repo("znippy", &[("arrow", "58.3.0")]),
            repo("nornir", &[("arrow", "57")]),
        ];
        let mut skew = analyze_skew(&repos, &DepPolicy::default());
        let nornir_lock = r#"
[[package]]
name = "arrow"
version = "57.3.1"

[[package]]
name = "arrow"
version = "58.3.0"
"#;
        // znippy's lock has only 58 → its Ok entry is untouched anyway.
        let locks: BTreeMap<String, String> =
            [("nornir".to_string(), nornir_lock.to_string())].into_iter().collect();
        enrich_transitive_pins(&mut skew, &locks);

        let arrow = skew.iter().find(|c| c.crate_name == "arrow").unwrap();
        let nornir = arrow.entries.iter().find(|e| e.repo == "nornir").unwrap();
        assert_eq!(nornir.status, SkewStatus::Behind);
        assert!(nornir.held_by_transitive_pin, "dual-major lock ⇒ held by transitive pin");

        // A behind repo whose lock does NOT yet pull the target is a free bump.
        let mut skew2 = analyze_skew(&repos, &DepPolicy::default());
        let only_57 = "[[package]]\nname = \"arrow\"\nversion = \"57.3.1\"\n";
        let locks2: BTreeMap<String, String> =
            [("nornir".to_string(), only_57.to_string())].into_iter().collect();
        enrich_transitive_pins(&mut skew2, &locks2);
        let nornir2 = skew2[0].entries.iter().find(|e| e.repo == "nornir").unwrap();
        assert!(!nornir2.held_by_transitive_pin, "single-major lock ⇒ free bump");
    }

    #[test]
    fn version_key_tolerates_partials_and_operators() {
        assert_eq!(version_key("58.3.0"), (58, 3, 0));
        assert_eq!(version_key("57"), (57, 0, 0));
        assert_eq!(version_key("^1.2"), (1, 2, 0));
        assert_eq!(version_key(">=0.9.0"), (0, 9, 0));
        assert_eq!(version_key("=56.2.1"), (56, 2, 1));
    }

    #[test]
    fn gatherer_reads_external_versions_and_skips_path_deps() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            r#"
[package]
name = "demo"
[dependencies]
arrow = "58.3.0"
serde = { version = "1.0", features = ["derive"] }
znippy-common = { version = "0.9.4", path = "../znippy-common" }
gitdep = { git = "https://example.com/x" }
"#,
        )
        .unwrap();

        let ext = gather_repo_externals("demo", dir.path()).unwrap();
        assert_eq!(ext.deps.get("arrow").map(String::as_str), Some("58.3.0"));
        assert_eq!(ext.deps.get("serde").map(String::as_str), Some("1.0"));
        assert!(!ext.deps.contains_key("znippy-common"), "path dep is workspace-internal");
        assert!(!ext.deps.contains_key("gitdep"), "git dep has no version");
    }

    /// Build a workspace member manifest under `root/<name>/Cargo.toml`.
    fn member(root: &Path, name: &str, deps: &[&str]) {
        let dir = root.join(name);
        std::fs::create_dir_all(&dir).unwrap();
        let mut t = format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\n[dependencies]\n");
        for d in deps {
            t.push_str(&format!("{d} = \"1\"\n"));
        }
        std::fs::write(dir.join("Cargo.toml"), t).unwrap();
    }

    #[test]
    fn precise_gate_blocks_only_crates_that_reach_the_foreign_fork() {
        // crate_deps: a workspace where only some crates touch the forked `iceberg`.
        //   skade        → iceberg (FOREIGN fork)         ⇒ blocked
        //   znippy-iceberg → iceberg                       ⇒ blocked
        //   nornir       → skade                           ⇒ blocked (transitive)
        //   znippy-common → (nothing forky)                ⇒ FREE
        //   lgz          → (nothing forky)                 ⇒ FREE
        let mut cd: BTreeMap<String, std::collections::BTreeSet<String>> = BTreeMap::new();
        let set = |xs: &[&str]| xs.iter().map(|s| s.to_string()).collect();
        cd.insert("skade".into(), set(&["iceberg", "serde"]));
        cd.insert("znippy-iceberg".into(), set(&["iceberg"]));
        cd.insert("nornir".into(), set(&["skade", "clap"]));
        cd.insert("znippy-common".into(), set(&["serde"]));
        cd.insert("lgz".into(), set(&["znippy-common"]));

        let foreign: std::collections::BTreeSet<String> =
            ["iceberg".to_string()].into_iter().collect();
        let blocked = promote_blocked_crates_precise(&cd, &foreign);

        assert!(blocked.contains("skade"), "skade rides the fork");
        assert!(blocked.contains("znippy-iceberg"), "znippy-iceberg rides the fork");
        assert!(blocked.contains("nornir"), "nornir → skade → iceberg (transitive)");
        assert!(!blocked.contains("znippy-common"), "znippy-common never touches iceberg → FREE");
        assert!(!blocked.contains("lgz"), "lgz → znippy-common only → FREE");
    }

    #[test]
    fn compute_promote_block_classifies_foreign_vs_own_overrides() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();

        // A workspace ("nordic") whose ROOT patches both a FOREIGN crate (iceberg → a
        // local fork) and an OWN sibling (skade → ../skade, a dev override). Members:
        // skade (uses iceberg), znippy-common (clean), znippy-iceberg (uses iceberg).
        let ws = root.join("nordic");
        std::fs::create_dir_all(&ws).unwrap();
        std::fs::write(
            ws.join("Cargo.toml"),
            r#"
[workspace]
members = ["skade", "znippy-common", "znippy-iceberg"]
[patch.crates-io]
iceberg = { path = "../iceberg-arrow58" }
skade = { path = "../skade" }
"#,
        )
        .unwrap();
        member(&ws, "skade", &["iceberg"]);
        member(&ws, "znippy-common", &["serde"]);
        member(&ws, "znippy-iceberg", &["iceberg", "znippy-common"]);

        let repos = vec![("nordic".to_string(), ws.clone())];
        let block = compute_promote_block(repos.iter().map(|(n, p)| (n.clone(), p.as_path())));

        // iceberg is foreign (not produced here); skade is OUR crate → safe override.
        assert!(block.foreign_forks.contains("iceberg"), "iceberg is a foreign fork");
        assert!(!block.foreign_forks.contains("skade"), "skade is our own crate, not foreign");
        let iceberg_block = block.forks.iter().find(|b| b.patched_dep == "iceberg").unwrap();
        assert!(iceberg_block.is_foreign_fork);
        let skade_block = block.forks.iter().find(|b| b.patched_dep == "skade").unwrap();
        assert!(!skade_block.is_foreign_fork, "skade override is safe, not a blocker");

        // The block holds only iceberg-touchers; znippy-common stays publishable.
        assert!(block.blocked.contains("skade"));
        assert!(block.blocked.contains("znippy-iceberg"));
        assert!(!block.blocked.contains("znippy-common"), "clean sibling is FREE");
    }

    fn graph(repo: &str, produces: &[&str], deps: &[&str]) -> RepoGraph {
        RepoGraph {
            repo: repo.to_string(),
            produces: produces.iter().map(|s| s.to_string()).collect(),
            deps: deps.iter().map(|s| s.to_string()).collect(),
            ..Default::default()
        }
    }

    /// Publish order is dependencies-first, computed from who-produces-what:
    /// nornir depends on znippy-common + skade-katalog, so znippy & skade precede it.
    #[test]
    fn publish_order_is_dependencies_first() {
        let graphs = [
            graph("znippy", &["znippy-common", "lgz"], &["serde"]),
            graph("skade", &["skade-katalog"], &["arrow"]),
            graph("nornir", &["nornir"], &["znippy-common", "skade-katalog", "serde"]),
        ];
        let topo = publish_order(&graphs);
        assert!(topo.cycle.is_empty(), "clean DAG");
        let pos = |r: &str| topo.order.iter().position(|x| x == r).unwrap();
        assert!(pos("znippy") < pos("nornir"), "znippy before nornir");
        assert!(pos("skade") < pos("nornir"), "skade before nornir");
        assert_eq!(topo.order.len(), 3);
    }

    #[test]
    fn blast_radius_is_transitive_dependents() {
        let graphs = [
            graph("skade", &["skade-katalog"], &[]),
            graph("nornir", &["nornir"], &["skade-katalog"]),
            graph("cli", &["cli"], &["nornir"]),
        ];
        let mut radius = blast_radius(&graphs, "skade");
        radius.sort();
        assert_eq!(radius, vec!["cli", "nornir"], "changing skade re-validates nornir + cli");
    }

    #[test]
    fn publish_order_flags_cycle() {
        let graphs = [
            graph("a", &["a-crate"], &["b-crate"]),
            graph("b", &["b-crate"], &["a-crate"]),
        ];
        let topo = publish_order(&graphs);
        assert!(topo.order.is_empty(), "all on a cycle → none ordered");
        assert_eq!(topo.cycle.len(), 2);
    }

    #[test]
    fn cycle_advice_empty_on_clean_dag() {
        let graphs = [
            graph("znippy", &["znippy-common"], &["serde"]),
            graph("nornir", &["nornir"], &["znippy-common"]),
        ];
        assert!(cycle_advice(&graphs).is_empty(), "a DAG has no cycle to break");
    }

    #[test]
    fn cycle_advice_two_node_picks_deterministic_edge() {
        let graphs = [
            graph("a", &["a-crate"], &["b-crate"]),
            graph("b", &["b-crate"], &["a-crate"]),
        ];
        let advice = cycle_advice(&graphs);
        assert_eq!(advice.len(), 1, "one cycle");
        let c = &advice[0];
        assert_eq!(c.members, vec!["a", "b"]);
        // Both edges ride one crate → tie broken by (len, from, to): a→b wins.
        assert_eq!((c.cut_from.as_str(), c.cut_to.as_str()), ("a", "b"));
        assert_eq!(c.via, vec!["b-crate"]);
    }

    #[test]
    fn cycle_advice_cuts_the_cheapest_edge() {
        // x→y rides on TWO crates, y→x on ONE → cut y→x (cheaper to untangle).
        let graphs = [
            graph("x", &["x1"], &["y1", "y2"]),
            graph("y", &["y1", "y2"], &["x1"]),
        ];
        let advice = cycle_advice(&graphs);
        assert_eq!(advice.len(), 1);
        let c = &advice[0];
        assert_eq!((c.cut_from.as_str(), c.cut_to.as_str()), ("y", "x"));
        assert_eq!(c.via, vec!["x1"], "the single-crate edge is the cut");
    }

    // ─── patch-fork promote gate ───

    #[test]
    fn patch_fork_detects_path_and_git_but_not_registry_pin() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(root.join("Cargo.toml"), r#"[package]
name = "skade"
version = "0.1.0"

[dependencies]
iceberg = "0.9"

[patch.crates-io]
iceberg = { path = "../iceberg-arrow58" }
forkgit = { git = "https://example.com/forkgit" }
serde = "1.0.200"
toml = { version = "0.8" }
"#).unwrap();

        let blocks = patch_fork_blockers(root);
        // iceberg (path) + forkgit (git) → 2 blocks; serde + toml registry no-ops skipped.
        assert_eq!(blocks.len(), 2, "{blocks:#?}");
        let iceberg = blocks.iter().find(|b| b.patched_dep == "iceberg").unwrap();
        assert_eq!(iceberg.fork_kind, ForkKind::Path);
        assert_eq!(iceberg.crate_name, "skade");
        assert!(iceberg.source.contains("iceberg-arrow58"));
        let git = blocks.iter().find(|b| b.patched_dep == "forkgit").unwrap();
        assert_eq!(git.fork_kind, ForkKind::Git);
        assert!(!blocks.iter().any(|b| b.patched_dep == "serde"));
        assert!(!blocks.iter().any(|b| b.patched_dep == "toml"));
    }

    #[test]
    fn patch_fork_registry_only_patch_is_not_blocked() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(root.join("Cargo.toml"), r#"[package]
name = "clean"
version = "0.1.0"

[patch.crates-io]
foo = "1.2"
bar = { version = "2.0" }
"#).unwrap();
        assert!(patch_fork_blockers(root).is_empty(), "registry-version patches are publishable");
    }

    #[test]
    fn promote_block_is_transitive_over_workspace_deps() {
        // skade rides the iceberg fork → directly blocked. nornir depends on
        // skade-katalog (which skade produces) → transitively blocked. facett is
        // independent → publishable.
        let graphs = [
            graph("skade", &["skade-katalog"], &["iceberg"]),
            graph("nornir", &["nornir"], &["skade-katalog"]),
            graph("facett", &["facett"], &["serde"]),
        ];
        let directly: std::collections::BTreeSet<String> =
            ["skade-katalog".to_string()].into_iter().collect();
        let blocked = promote_blocked_crates(&graphs, &directly);
        assert!(blocked.contains("skade-katalog"), "the fork rider is blocked");
        assert!(blocked.contains("nornir"), "nornir depends on skade-katalog → blocked");
        assert!(!blocked.contains("facett"), "facett is independent → publishable");
    }

    #[test]
    fn cycle_advice_handles_three_node_cycle() {
        let graphs = [
            graph("a", &["a-c"], &["b-c"]),
            graph("b", &["b-c"], &["c-c"]),
            graph("c", &["c-c"], &["a-c"]),
        ];
        let advice = cycle_advice(&graphs);
        assert_eq!(advice.len(), 1, "one 3-node SCC");
        assert_eq!(advice[0].members, vec!["a", "b", "c"]);
    }
}