nornir 0.4.54

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
//! `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::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 {
    let major = version_key(version).0;
    policy
        .forbidden
        .iter()
        .any(|f| f.crate_name == crate_name && version_key(&f.version).0 == major)
}

/// 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
}

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

/// What a repo produces (its package names) and every crate name it depends on —
/// 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).
#[derive(Debug, Clone)]
pub struct RepoGraph {
    pub repo: String,
    pub produces: std::collections::BTreeSet<String>,
    pub deps: std::collections::BTreeSet<String>,
}

/// Scan a repo's Cargo.tomls for the crates it produces (`[package].name`) and
/// every declared dependency name (internal + external, incl. build-deps).
pub fn gather_repo_graph(repo: &str, root: &Path) -> Result<RepoGraph> {
    use std::collections::BTreeSet;
    let mut produces = BTreeSet::new();
    let mut deps = BTreeSet::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");
        // Skip `publish = false` crates (xtask, internal test helpers): they ship
        // nothing and their dev/tooling deps must not constrain publish order
        // (that's what turns the nornir↔znippy tooling link into a false cycle).
        let publishable = package
            .and_then(|p| p.get("publish"))
            .and_then(|v| v.as_bool())
            .unwrap_or(true);
        if !publishable {
            continue;
        }
        if let Some(n) = package.and_then(|p| p.get("name")).and_then(|n| n.as_str()) {
            produces.insert(n.to_string());
        }
        // Edges come only from REAL package dep tables — not `[workspace.dependencies]`
        // (those are version declarations a member must opt into, not edges) — and
        // skip OPTIONAL (feature-gated) deps (e.g. nornir's `dep:znippy-common`).
        for key in ["dependencies", "build-dependencies"] {
            if let Some(t) = doc.get(key).and_then(|t| t.as_table()) {
                for (name, 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 {
                        deps.insert(name.clone());
                    }
                }
            }
        }
    }
    Ok(RepoGraph { repo: repo.to_string(), produces, deps })
}

/// 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, 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
}

#[derive(Debug, Clone, 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>,
}

/// 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();

    Ok(DoctorReport {
        dirty,
        skew,
        topo: publish_order(&graphs),
        blast,
        cycle_advice: cycle_advice(&graphs),
        repo_edges: repo_dep_edges(&graphs),
        patch_forks,
        promote_blocked,
    })
}

/// 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("")));
    }

    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));
        }
    }

    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"]);
    }

    #[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(),
        }
    }

    /// 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"]);
    }
}