nornir 0.5.2

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
//! Pre-cascade validation for `release doctor --publish`.
//!
//! `cargo publish` is IRREVERSIBLE: once a `<crate>@<version>` is on crates.io it
//! is immutable forever. A cascade that fail-stops halfway leaves the already-shipped
//! crates permanently live while the rest never ship — a torn release. Preflight
//! moves every catchable failure BEFORE the first real upload, so the operator sees
//! ALL blockers at once ("preflight: N blocking issue(s)") with the exact fix per
//! issue, and nothing goes to the registry until the plan is clean.
//!
//! Checks (all best-effort — a check whose tooling is unavailable degrades to a
//! note, never a false block):
//!   1. every planned crate is a MEMBER of its repo-root workspace (the detached
//!      `[workspace]` bug — a bench/vendored/sub-workspace crate handed to
//!      `cargo publish -p` from the wrong root errors 101 "did not match any packages");
//!   2. required crates.io METADATA present per crate (description, license/license-file,
//!      repository);
//!   3. the "dependency edited without a version bump" trap, caught UP FRONT via
//!      `cargo publish -p <crate> --dry-run` (verify build against the registry) — a
//!      compile error citing an already-published sibling is a real blocker; a mere
//!      "sibling not on the registry yet" is expected mid-cascade and is NOT flagged.
//!      BUMP-AWARE (item #7): when the cascade will itself publish the blamed
//!      sibling forward (it is in the planned publish set, e.g. every crate under
//!      `--bump patch`), the verify skew is cascade-resolvable — the cascade bumps
//!      and publishes that sibling BEFORE its dependents — so it is a NOTE, not a
//!      blocker. Only a skew blaming a crate the cascade will NOT republish
//!      (external / not in the release set) still blocks. This is what lets
//!      `doctor --publish --bump patch` pass preflight WITHOUT `--force`;
//!   4. DETACHED `[workspace]` roots listed, so the operator knows they're intentionally
//!      excluded;
//!   5. VERSION/registry consistency — for a real bump, the target version must not
//!      already be live on crates.io (an immutable clash); for `--bump keep`, a version
//!      already on the registry is a benign idempotent skip.

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

use crate::release::cargo;
use crate::release::publish::{classify_publish_failure, PublishFailure};
use crate::release::registry::{classify, RegistryBackend, RegistryState};

/// The class of a blocking preflight issue.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum IssueKind {
    /// Planned `-p` target is not a member of its repo-root workspace.
    NonMember,
    /// Missing required crates.io metadata field(s).
    MissingMetadata,
    /// `cargo publish --dry-run` verify build failed on dep-API skew.
    VerifyFailed,
    /// The version to publish is already live on crates.io (immutable clash).
    RegistrySkew,
    /// The LOCAL version is BEHIND the registry's published max (a desync/
    /// downgrade) — a dependent will verify against the newer published API and
    /// break. See [`crate::release::registry`].
    RegistryDesync,
}

/// One blocking issue: a short, specific "why" plus the exact "fix".
#[derive(Debug, Clone)]
pub struct Issue {
    pub repo: String,
    pub krate: String,
    pub kind: IssueKind,
    pub detail: String,
    pub fix: String,
    /// Crate(s) this issue's error explicitly BLAMES as the un-published
    /// upstream — set for `VerifyFailed` (the dep whose new API isn't on the
    /// registry). Feeds topological root-cause analysis so the true root is
    /// named even when it was skipped and never became its own issue. Empty
    /// for self-contained issues (metadata/version/non-member).
    #[allow(dead_code)]
    pub blames: Vec<String>,
}

/// Aggregated preflight verdict: blocking `issues` (must be empty to proceed) plus
/// informational `notes` (detached workspaces excluded, checks skipped, etc.).
#[derive(Debug, Default)]
pub struct PreflightReport {
    pub issues: Vec<Issue>,
    pub notes: Vec<String>,
    pub checked_crates: usize,
}

impl PreflightReport {
    /// Clean ⟺ zero blocking issues ⟹ safe to start the irreversible cascade.
    pub fn is_clean(&self) -> bool {
        self.issues.is_empty()
    }

    fn push(&mut self, i: Issue) {
        self.issues.push(i);
    }

    /// Human-readable consolidated summary — every issue with its fix, then the
    /// notes. The header is `preflight: clean` or `preflight: N blocking issue(s)`.
    pub fn format(&self) -> String {
        let mut s = String::new();
        if self.is_clean() {
            s.push_str(&format!(
                "\npreflight: clean — {} crate(s) checked; safe to publish.\n",
                self.checked_crates
            ));
        } else {
            s.push_str(&format!(
                "\npreflight: {} blocking issue(s) — resolve before publishing \
                 (or re-run with --force to override):\n",
                self.issues.len()
            ));
            for i in &self.issues {
                let tag = match i.kind {
                    IssueKind::NonMember => "non-member",
                    IssueKind::MissingMetadata => "metadata",
                    IssueKind::VerifyFailed => "verify",
                    IssueKind::RegistrySkew => "version",
                    IssueKind::RegistryDesync => "desync",
                };
                s.push_str(&format!("  ⛔ [{tag}] {}/{}: {}\n", i.repo, i.krate, i.detail));
                s.push_str(&format!("       fix: {}\n", i.fix));
            }
        }
        for n in &self.notes {
            s.push_str(&format!("  · {n}\n"));
        }
        s
    }
}

/// A repo to preflight: its config name, on-disk root, and the crate set that WILL
/// be published (publishable minus gate-held). The caller derives `publish_set`
/// exactly as the promote path does, so preflight checks precisely what ships.
#[derive(Debug, Clone)]
pub struct RepoPlan {
    pub name: String,
    pub root: PathBuf,
    /// Crate names slated to publish, with the version each will carry.
    pub publish_set: Vec<(String, String)>,
}

/// Injectable registry probe so the version/consistency check is deterministically
/// testable without hitting crates.io. `Some(true)` = version live, `Some(false)` =
/// absent, `None` = couldn't determine (network down) → the check degrades to a note.
pub trait RegistryProbe {
    fn version_live(&self, krate: &str, version: &str) -> Option<bool>;
}

/// Live crates.io probe (sparse index) reusing the vendored `ureq` client — same
/// pattern as [`crate::release::publish::wait_for_index`].
pub struct CratesIoProbe;

impl RegistryProbe for CratesIoProbe {
    fn version_live(&self, krate: &str, version: &str) -> Option<bool> {
        let url = format!("https://crates.io/api/v1/crates/{krate}");
        let agent = "nornir-release-bot/0.1 (cargo-pipeline; +https://crates.io)";
        let resp = ureq::get(&url)
            .set("User-Agent", agent)
            .timeout(std::time::Duration::from_secs(10))
            .call()
            .ok()?;
        let body = resp.into_string().ok()?;
        let json: serde_json::Value = serde_json::from_str(&body).ok()?;
        let versions = json.get("versions").and_then(|v| v.as_array())?;
        Some(versions.iter().any(|e| e.get("num").and_then(|n| n.as_str()) == Some(version)))
    }
}

/// Whether cargo will run a dry-run verify build during preflight.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerifyMode {
    /// Run `cargo publish -p <crate> --dry-run` for each crate and flag dep-API skew.
    On,
    /// Skip the verify build (fast preflight — used for `--publish-dry-run`).
    Off,
}

/// Run the full preflight over `plans`. `bump_keep` is true for `--bump keep|none`
/// (idempotent resume: a version already on the registry is a benign skip, not a
/// clash). `verify` gates the expensive dry-run compile. `probe` answers "is this
/// version already live?"; `backend` answers "what is the max PUBLISHED version?"
/// for the registry-state desync check (item #10).
///
/// `cascade_publishes` is the BUMP-AWARE planned map (item #7): every crate the
/// cascade WILL publish forward, mapped to the version it will carry. A dry-run
/// verify skew (check 3) that blames a crate in THIS map is cascade-resolvable —
/// the cascade bumps and publishes that crate before its dependents — so it is
/// recorded as a NOTE, not a blocker. A skew blaming a crate NOT in the map
/// (external, or a crate the cascade won't republish) still blocks. Pass an empty
/// map to get the strict, non-bump-aware behavior (used by `--bump keep`).
pub fn run(
    plans: &[RepoPlan],
    bump_keep: bool,
    verify: VerifyMode,
    probe: &dyn RegistryProbe,
    backend: &dyn RegistryBackend,
    cascade_publishes: &BTreeMap<String, String>,
) -> PreflightReport {
    let mut report = PreflightReport::default();
    for plan in plans {
        // (4) list detached `[workspace]` roots so exclusions are visible.
        let members = cargo::root_workspace_members(&plan.root);
        if let Some(members) = &members {
            let detached = detached_workspace_crates(&plan.root, members);
            if !detached.is_empty() {
                report.notes.push(format!(
                    "{}: {} detached-[workspace] crate(s) excluded from publish: {}",
                    plan.name,
                    detached.len(),
                    detached.into_iter().collect::<Vec<_>>().join(", ")
                ));
            }
        } else {
            report.notes.push(format!(
                "{}: cargo metadata unavailable — root-member check skipped (best-effort)",
                plan.name
            ));
        }

        for (krate, version) in &plan.publish_set {
            report.checked_crates += 1;

            // (1) member of the repo-root workspace?
            if let Some(members) = &members {
                if !members.contains(krate) {
                    report.push(Issue {
                        repo: plan.name.clone(),
                        krate: krate.clone(),
                        kind: IssueKind::NonMember,
                        detail: format!(
                            "not a member of the workspace at {} (detached [workspace])",
                            plan.root.display()
                        ),
                        fix: "mark it `publish = false`, or publish it from its own \
                              workspace directory"
                            .to_string(),
                        blames: Vec::new(),
                    });
                    // A non-member can't be metadata/verify-checked from this root; skip.
                    continue;
                }
            }

            // (2) required crates.io metadata.
            let missing = crate_metadata_gaps(&plan.root, krate);
            if !missing.is_empty() {
                report.push(Issue {
                    repo: plan.name.clone(),
                    krate: krate.clone(),
                    kind: IssueKind::MissingMetadata,
                    detail: format!("missing crates.io metadata: {}", missing.join(", ")),
                    fix: format!(
                        "add the field(s) to [package] in {}'s Cargo.toml",
                        krate
                    ),
                    blames: Vec::new(),
                });
            }

            // (5) version/registry consistency.
            if let Some(issue) = registry_skew_issue(
                &plan.name,
                krate,
                version,
                bump_keep,
                probe.version_live(krate, version),
            ) {
                report.push(issue);
            }

            // (6) REGISTRY-STATE desync — ask the backend the max PUBLISHED
            // version and flag a local tree that is BEHIND it (the
            // gatling-0.1.4-local vs 0.1.6-published class): a dependent would
            // verify against the newer published API and break mid-cascade.
            if let Some(issue) = registry_desync_issue(
                &plan.name,
                krate,
                version,
                backend.published_max_version(krate).as_deref(),
            ) {
                report.push(issue);
            }
        }

        // (3) dep-API skew via dry-run verify — expensive, so one pass per repo.
        if verify == VerifyMode::On {
            for (krate, _) in &plan.publish_set {
                if members.as_ref().map(|m| !m.contains(krate)).unwrap_or(false) {
                    continue; // non-member already flagged
                }
                match verify_one(&plan.name, &plan.root, krate, cascade_publishes) {
                    VerifyOutcome::Clean => {}
                    VerifyOutcome::Blocker(issue) => report.push(issue),
                    VerifyOutcome::CascadeResolvable { dep, planned } => {
                        // The cascade itself publishes `dep` forward before this
                        // crate — the skew is expected mid-cascade, NOT a blocker.
                        report.notes.push(format!(
                            "{}/{krate}: verify skew against `{dep}` is cascade-resolvable \
                             ({dep} will be published at {planned} earlier in the wave) — \
                             not a blocker",
                            plan.name
                        ));
                    }
                }
            }
        }
    }
    report
}

/// Packages under `repo_root` that the toml-walk finds but that are NOT members of
/// the root workspace — i.e. they live in a detached `[workspace]`. Pure over the
/// injected `members` set.
fn detached_workspace_crates(repo_root: &Path, members: &BTreeSet<String>) -> BTreeSet<String> {
    let walked = cargo::publishable_crate_versions_walk(repo_root).unwrap_or_default();
    walked
        .into_iter()
        .map(|(n, _)| n)
        .filter(|n| !members.contains(n))
        .collect()
}

/// Required-metadata gap for one crate, resolving `field.workspace = true`
/// inheritance against the root `[workspace.package]`. Returns the missing field
/// labels (empty ⇒ complete). `license` is satisfied by EITHER `license` or
/// `license-file`.
pub fn crate_metadata_gaps(repo_root: &Path, krate: &str) -> Vec<String> {
    // Inheritance source is the ROOT workspace's [workspace.package] ONLY. A
    // DETACHED sub-workspace under the tree (e.g. facett's `facett-py/Cargo.toml`
    // with `[workspace] package = {}`, or `bench/`) must NOT clobber it: the old
    // last-write-wins walk let an EMPTY sub-workspace table win whenever the
    // unordered `read_dir` happened to visit it after the root, making every
    // `license.workspace = true` / `repository.workspace = true` resolve to
    // "missing" — a FLAKY false blocker that flipped with directory order between
    // runs. Publish-set members inherit from the root by cargo's own rules and are
    // filtered to root-workspace members anyway, so only the root table is valid.
    let ws_package = std::fs::read_to_string(repo_root.join("Cargo.toml"))
        .ok()
        .and_then(|t| t.parse::<toml::Value>().ok())
        .and_then(|d| d.get("workspace").and_then(|w| w.get("package")).cloned());

    // Find the crate's own manifest.
    let mut pkg_doc: Option<toml::Value> = None;
    let _ = cargo::for_each_cargo_toml(repo_root, &mut |doc: &toml::Value| {
        if doc
            .get("package")
            .and_then(|p| p.get("name"))
            .and_then(|n| n.as_str())
            == Some(krate)
        {
            pkg_doc = doc.get("package").cloned();
        }
    });
    let Some(pkg) = pkg_doc else { return Vec::new() };
    missing_metadata_fields(&pkg, ws_package.as_ref())
}

/// Pure metadata-completeness check over a `[package]` table (and the optional
/// `[workspace.package]` for inheritance). A field counts as present when it's a
/// non-empty string in `[package]`, when it inherits (`field.workspace = true`) and
/// the workspace provides it, or — for license — when `license-file` is set instead.
pub fn missing_metadata_fields(
    pkg: &toml::Value,
    ws_package: Option<&toml::Value>,
) -> Vec<String> {
    let present = |field: &str| -> bool {
        field_present(pkg, ws_package, field)
    };
    let mut missing = Vec::new();
    if !present("description") {
        missing.push("description".to_string());
    }
    if !present("license") && !present("license-file") {
        missing.push("license".to_string());
    }
    if !present("repository") {
        missing.push("repository".to_string());
    }
    missing
}

/// Whether `field` is satisfied on `pkg` — a non-empty string, or an inherited
/// `{ workspace = true }` that the workspace root actually provides.
fn field_present(pkg: &toml::Value, ws_package: Option<&toml::Value>, field: &str) -> bool {
    match pkg.get(field) {
        Some(toml::Value::String(s)) => !s.trim().is_empty(),
        Some(toml::Value::Table(t)) => {
            // `field.workspace = true` inherits from [workspace.package].
            let inherits = t.get("workspace").and_then(|v| v.as_bool()).unwrap_or(false);
            inherits
                && ws_package
                    .and_then(|wp| wp.get(field))
                    .and_then(|v| match v {
                        toml::Value::String(s) => Some(!s.trim().is_empty()),
                        _ => Some(true),
                    })
                    .unwrap_or(false)
        }
        _ => false,
    }
}

/// Pure version/registry-consistency decision. For a real bump, a target version
/// already live on crates.io is an immutable clash (blocker). For `--bump keep`, a
/// live version is a benign idempotent skip. `None` (couldn't probe) never blocks.
pub fn registry_skew_issue(
    repo: &str,
    krate: &str,
    version: &str,
    bump_keep: bool,
    live: Option<bool>,
) -> Option<Issue> {
    if bump_keep {
        return None; // keep-cascade: already-published is intentional & idempotent.
    }
    match live {
        Some(true) => Some(Issue {
            repo: repo.to_string(),
            krate: krate.to_string(),
            kind: IssueKind::RegistrySkew,
            detail: format!("{krate} {version} is already live on crates.io (immutable)"),
            fix: format!(
                "bump {krate} past {version} (crates.io versions can't be overwritten), \
                 or use --bump keep to skip already-published crates"
            ),
            blames: Vec::new(),
        }),
        _ => None,
    }
}

/// Pure registry-STATE decision (item #10): classify the crate's local `version`
/// against the registry's max `published` version and, when the local tree is
/// BEHIND the registry ([`RegistryState::Desync`]), return a blocking issue
/// naming the crate and BOTH versions. `WillPublish`/`AlreadyPublished`/
/// `Unpublished`/`Unknown` are never blockers here (they're expected or
/// unprobable). This is the gatling-0.1.4-local vs 0.1.6-published class: a
/// dependent would verify against the newer published API and break mid-cascade.
pub fn registry_desync_issue(
    repo: &str,
    krate: &str,
    version: &str,
    published: Option<&str>,
) -> Option<Issue> {
    match classify(version, published) {
        RegistryState::Desync => {
            let pub_v = published.unwrap_or("?");
            Some(Issue {
                repo: repo.to_string(),
                krate: krate.to_string(),
                kind: IssueKind::RegistryDesync,
                detail: format!(
                    "local {krate} {version} is BEHIND the registry (published {pub_v}) — \
                     dependents verify against the newer published API and break"
                ),
                fix: format!(
                    "bump {krate} to at least {pub_v} (ideally past it) so the local tree \
                     matches or leads the registry before starting the cascade"
                ),
                blames: Vec::new(),
            })
        }
        _ => None,
    }
}

/// The outcome of a single dry-run verify. A [`Blocker`](VerifyOutcome::Blocker)
/// stops the cascade; a [`CascadeResolvable`](VerifyOutcome::CascadeResolvable)
/// skew is one the cascade itself fixes (the blamed dep is bumped+published
/// earlier in the wave) and is reported only as a note; [`Clean`](VerifyOutcome::Clean)
/// verified fine.
#[derive(Debug, Clone, PartialEq, Eq)]
enum VerifyOutcome {
    /// The crate verified cleanly (or the failure wasn't a preflight-catchable class).
    Clean,
    /// A real blocker — the crate cannot publish as-is.
    Blocker(Issue),
    /// Dep-API skew whose blamed crate the cascade WILL republish forward, so it
    /// resolves as the cascade runs. Not a blocker (item #7, bump-aware).
    CascadeResolvable { dep: String, planned: String },
}

// `Issue` has no `Eq`/`PartialEq`, so hand-derive `VerifyOutcome` equality only
// over the variants the tests compare (Clean / CascadeResolvable); Blocker is
// compared by its issue kind + blamed dep where needed.
impl PartialEq for Issue {
    fn eq(&self, other: &Self) -> bool {
        self.repo == other.repo
            && self.krate == other.krate
            && self.kind == other.kind
            && self.blames == other.blames
    }
}
impl Eq for Issue {}

/// Pure BUMP-AWARE decision (item #7): given the crate the dry-run verify blamed
/// (`dep`; `None` ⇒ the classifier couldn't name it) and the cascade's planned
/// publish map, decide whether the skew is cascade-resolvable. Returns
/// `Some(planned_version)` when the blamed dep is one the cascade WILL publish
/// forward (⇒ NOT a blocker — it will exist at that version before this crate is
/// verified in the real cascade); `None` when the dep is external / not in the
/// release set (⇒ a real blocker). An unnamed dep (`None`) is conservatively a
/// blocker — we can't prove the cascade covers it.
pub fn skew_is_cascade_resolvable(
    dep: Option<&str>,
    cascade_publishes: &BTreeMap<String, String>,
) -> Option<String> {
    let d = dep?;
    if let Some(v) = cascade_publishes.get(d) {
        return Some(v.clone());
    }
    // The blamed name comes from a rustc verify error, which cites the LIB name
    // (a crate's `-` becomes `_`, e.g. `facett_core`); `cascade_publishes` is
    // keyed by the PACKAGE name (`facett-core`). Match with separators unified so
    // a hyphenated crate the cascade WILL republish is correctly recognised as
    // cascade-resolvable instead of a false hard blocker (the facett-core trap).
    let canon = |s: &str| s.replace('_', "-");
    let dc = canon(d);
    cascade_publishes.iter().find(|(k, _)| canon(k) == dc).map(|(_, v)| v.clone())
}

/// Run `cargo publish -p <krate> --dry-run --allow-dirty` and classify a dep-API
/// skew (a compile error citing an already-published dependency). BUMP-AWARE
/// (item #7): if the skew blames a crate the cascade will itself publish forward
/// (`cascade_publishes`), it is [`CascadeResolvable`](VerifyOutcome::CascadeResolvable),
/// not a blocker — the real cascade bumps+publishes that crate first. A skew
/// blaming an external / not-republished crate is a [`Blocker`](VerifyOutcome::Blocker).
/// A pure resolution/ordering failure (sibling not yet on the registry — expected
/// mid-cascade) is not flagged, so preflight doesn't cry wolf.
fn verify_one(
    repo: &str,
    repo_root: &Path,
    krate: &str,
    cascade_publishes: &BTreeMap<String, String>,
) -> VerifyOutcome {
    let Ok(out) = std::process::Command::new("cargo")
        .args(["publish", "-p", krate, "--dry-run", "--allow-dirty"])
        .current_dir(repo_root)
        .output()
    else {
        return VerifyOutcome::Clean; // cargo unavailable → best-effort, never a false block
    };
    if out.status.success() {
        return VerifyOutcome::Clean;
    }
    let stderr = String::from_utf8_lossy(&out.stderr);
    match classify_publish_failure(krate, &stderr) {
        PublishFailure::DepApiSkew { dep } => {
            // BUMP-AWARE gate: does the cascade itself publish the blamed dep?
            if let Some(planned) = skew_is_cascade_resolvable(dep.as_deref(), cascade_publishes) {
                let d = dep.unwrap_or_default();
                return VerifyOutcome::CascadeResolvable { dep: d, planned };
            }
            let d = dep.as_deref().unwrap_or("a dependency");
            VerifyOutcome::Blocker(Issue {
                repo: repo.to_string(),
                krate: krate.to_string(),
                kind: IssueKind::VerifyFailed,
                detail: format!(
                    "verify build uses API from `{d}` not in the published `{d}`"
                ),
                fix: format!("bump `{d}` and publish it before `{krate}`"),
                // Blame the exact dep whose un-published API broke the verify —
                // the root-cause analyzer promotes it to the root even if it was
                // skipped (AlreadyPublished) and never became its own issue.
                blames: dep.iter().cloned().collect(),
            })
        }
        // Non-member surfaces via check (1); metadata via check (2). A resolution/
        // ordering failure or anything unclassified is not a preflight blocker.
        _ => VerifyOutcome::Clean,
    }
}

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

    struct FakeProbe(Option<bool>);
    impl RegistryProbe for FakeProbe {
        fn version_live(&self, _k: &str, _v: &str) -> Option<bool> {
            self.0
        }
    }

    /// A registry backend that reports a fixed published max version for every
    /// crate (or `None` = unpublished/unreachable).
    struct FakeBackend(Option<&'static str>);
    impl RegistryBackend for FakeBackend {
        fn published_max_version(&self, _krate: &str) -> Option<String> {
            self.0.map(str::to_string)
        }
    }

    #[test]
    fn missing_metadata_fields_respects_inheritance_and_license_file() {
        // Complete via explicit strings.
        let full: toml::Value = toml::from_str(
            r#"name = "x"
version = "0.1.0"
description = "d"
license = "Apache-2.0"
repository = "https://example.com"
"#,
        )
        .unwrap();
        assert!(missing_metadata_fields(&full, None).is_empty());

        // license-file satisfies the license requirement.
        let lf: toml::Value = toml::from_str(
            r#"name = "x"
description = "d"
license-file = "LICENSE"
repository = "r"
"#,
        )
        .unwrap();
        assert!(missing_metadata_fields(&lf, None).is_empty(), "license-file counts");

        // Missing everything.
        let bare: toml::Value = toml::from_str("name = \"x\"\nversion = \"0.1.0\"\n").unwrap();
        let miss = missing_metadata_fields(&bare, None);
        assert_eq!(miss, vec!["description", "license", "repository"]);

        // Inheritance: `field.workspace = true` + a workspace that provides it.
        let inh: toml::Value = toml::from_str(
            r#"name = "x"
description = { workspace = true }
license = { workspace = true }
repository = { workspace = true }
"#,
        )
        .unwrap();
        let wp: toml::Value = toml::from_str(
            r#"description = "d"
license = "Apache-2.0"
repository = "r"
"#,
        )
        .unwrap();
        assert!(missing_metadata_fields(&inh, Some(&wp)).is_empty(), "inherited fields present");
        // Inherits but the workspace DOESN'T provide it → still missing.
        assert_eq!(missing_metadata_fields(&inh, None), vec!["description", "license", "repository"]);
    }

    #[test]
    fn registry_skew_blocks_real_bump_but_not_keep() {
        // Real bump onto a version already live → blocker.
        let i = registry_skew_issue("facett", "facett-core", "0.4.53", false, Some(true));
        assert!(i.is_some());
        let i = i.unwrap();
        assert_eq!(i.kind, IssueKind::RegistrySkew);
        assert!(i.detail.contains("already live"));
        // Version absent → fine.
        assert!(registry_skew_issue("facett", "facett-core", "0.4.53", false, Some(false)).is_none());
        // keep-cascade → already-live is intentional, never a blocker.
        assert!(registry_skew_issue("facett", "facett-core", "0.4.53", true, Some(true)).is_none());
        // Couldn't probe → never a false block.
        assert!(registry_skew_issue("facett", "facett-core", "0.4.53", false, None).is_none());
    }

    /// The aggregation contract: multiple repos/crates, several issue classes, and
    /// notes fold into ONE report; `is_clean` is false; `format` names every fix.
    #[test]
    fn preflight_aggregates_all_issues_at_once() {
        // A one-crate repo missing ALL metadata + slated onto a live version.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"solo\"\nversion = \"0.2.0\"\nedition = \"2021\"\n",
        )
        .unwrap();

        let plans = vec![RepoPlan {
            name: "solo".to_string(),
            root: root.to_path_buf(),
            publish_set: vec![("solo".to_string(), "0.2.0".to_string())],
        }];
        // Real bump (not keep), version reported already live, verify OFF (no cargo).
        // Backend reports NONE (unpublished) so the desync check stays silent here.
        let report = run(
            &plans,
            false,
            VerifyMode::Off,
            &FakeProbe(Some(true)),
            &FakeBackend(None),
            &BTreeMap::new(),
        );

        assert!(!report.is_clean(), "issues present ⇒ not clean");
        // solo lacks description/license/repository (one MissingMetadata issue) AND
        // its 0.2.0 is already live (one RegistrySkew issue).
        assert!(
            report.issues.iter().any(|i| i.kind == IssueKind::MissingMetadata),
            "metadata gap flagged"
        );
        assert!(
            report.issues.iter().any(|i| i.kind == IssueKind::RegistrySkew),
            "registry clash flagged"
        );
        assert_eq!(report.checked_crates, 1);
        let text = report.format();
        assert!(text.contains("blocking issue(s)"), "header counts issues: {text}");
        assert!(text.contains("fix:"), "every issue carries a fix: {text}");

        // Clean case: complete metadata, version not live.
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"solo\"\nversion = \"0.2.0\"\n\
             description = \"d\"\nlicense = \"Apache-2.0\"\nrepository = \"r\"\n",
        )
        .unwrap();
        let clean = run(
            &plans,
            false,
            VerifyMode::Off,
            &FakeProbe(Some(false)),
            &FakeBackend(None),
            &BTreeMap::new(),
        );
        assert!(clean.is_clean(), "complete metadata + fresh version ⇒ clean: {:?}", clean.issues);
        assert!(clean.format().contains("preflight: clean"));
    }

    #[test]
    fn registry_desync_blocks_only_when_local_is_behind() {
        // Local BEHIND registry (the gatling incident) → blocker naming both versions.
        let i = registry_desync_issue("znippy", "gatling", "0.1.4", Some("0.1.6"));
        assert!(i.is_some());
        let i = i.unwrap();
        assert_eq!(i.kind, IssueKind::RegistryDesync);
        assert!(i.detail.contains("gatling 0.1.4"), "{}", i.detail);
        assert!(i.detail.contains("0.1.6"), "{}", i.detail);
        // local AHEAD → WillPublish, not a blocker.
        assert!(registry_desync_issue("z", "gatling", "0.1.7", Some("0.1.6")).is_none());
        // local == published → AlreadyPublished, not a blocker.
        assert!(registry_desync_issue("z", "gatling", "0.1.6", Some("0.1.6")).is_none());
        // unpublished / unprobable → never a false block.
        assert!(registry_desync_issue("z", "gatling", "0.1.6", None).is_none());
    }

    /// End-to-end: a crate whose local version is BEHIND the backend's published
    /// max surfaces a RegistryDesync issue in the aggregated report.
    #[test]
    fn run_flags_registry_desync_from_backend() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        std::fs::write(
            root.join("Cargo.toml"),
            "[package]\nname = \"gatling\"\nversion = \"0.1.4\"\n\
             description = \"d\"\nlicense = \"Apache-2.0\"\nrepository = \"r\"\n",
        )
        .unwrap();
        let plans = vec![RepoPlan {
            name: "znippy".to_string(),
            root: root.to_path_buf(),
            publish_set: vec![("gatling".to_string(), "0.1.4".to_string())],
        }];
        // Registry already serves 0.1.6 — local 0.1.4 is a desync.
        let report = run(
            &plans,
            false,
            VerifyMode::Off,
            &FakeProbe(Some(false)),
            &FakeBackend(Some("0.1.6")),
            &BTreeMap::new(),
        );
        assert!(
            report.issues.iter().any(|i| i.kind == IssueKind::RegistryDesync),
            "desync flagged: {:?}",
            report.issues
        );
        assert!(report.format().contains("[desync]"), "{}", report.format());
    }

    /// BUMP-AWARE verify (item #7): a dep-API skew blaming a SIBLING that the
    /// cascade will itself publish forward is cascade-resolvable (not a blocker),
    /// while a skew blaming an EXTERNAL crate the cascade does NOT republish still
    /// blocks. This is the fixture the release needed `--force` for: crate B needs
    /// A's bumped version — with A in the planned publish map, that skew clears.
    #[test]
    fn skew_is_cascade_resolvable_only_for_in_release_deps() {
        // The planned publish map: the cascade bumps A and B to 0.1.2 (as under
        // `--bump patch`). `facett_core` is the classic ~30-member root.
        let mut planned = BTreeMap::new();
        planned.insert("facett_core".to_string(), "0.1.2".to_string());
        planned.insert("gatling".to_string(), "0.1.2".to_string());

        // A skew blaming `facett_core` (IN the release set) → cascade-resolvable,
        // carrying the version the cascade will publish it at.
        assert_eq!(
            skew_is_cascade_resolvable(Some("facett_core"), &planned),
            Some("0.1.2".to_string()),
            "a sibling the cascade republishes must NOT block preflight",
        );
        assert_eq!(
            skew_is_cascade_resolvable(Some("gatling"), &planned),
            Some("0.1.2".to_string()),
        );

        // A skew blaming an EXTERNAL crate (NOT in the release set) → real blocker.
        assert_eq!(
            skew_is_cascade_resolvable(Some("serde"), &planned),
            None,
            "a dep the cascade does NOT publish is still a genuine blocker",
        );
        // An unnamed dep → conservatively a blocker (can't prove the cascade covers it).
        assert_eq!(skew_is_cascade_resolvable(None, &planned), None);
        // Empty planned map (the strict / `--bump keep` path) → nothing is
        // suppressed, so every skew stays a blocker (preserves item #9/#10 resume
        // semantics where an AlreadyPublished/edited-but-unbumped dep must block).
        assert_eq!(
            skew_is_cascade_resolvable(Some("facett_core"), &BTreeMap::new()),
            None,
        );
    }

    /// The real production shape: the map is keyed by PACKAGE name (hyphens, from
    /// `Cargo.toml` `package.name`) but the blamed dep comes from a rustc verify
    /// error that cites the LIB name (hyphens → underscores). They must still match
    /// so a hyphenated sibling the cascade republishes (facett-core, its ~30
    /// dependents) is NOT falsely blocked. Regression guard for the false-blocker
    /// that refused release #2.
    #[test]
    fn skew_resolvable_across_hyphen_underscore_separators() {
        let mut planned = BTreeMap::new();
        planned.insert("facett-core".to_string(), "0.1.11".to_string()); // package name
        planned.insert("facett-graphview".to_string(), "0.1.11".to_string());
        // rustc blames the LIB name (underscores) — must resolve to the package.
        assert_eq!(
            skew_is_cascade_resolvable(Some("facett_core"), &planned),
            Some("0.1.11".to_string()),
            "lib-name `facett_core` must match package `facett-core`",
        );
        assert_eq!(
            skew_is_cascade_resolvable(Some("facett_graphview"), &planned),
            Some("0.1.11".to_string()),
        );
        // A genuinely absent crate still blocks.
        assert_eq!(skew_is_cascade_resolvable(Some("serde_json"), &planned), None);
    }

    /// The `VerifyOutcome` a bump-aware `verify_one` would emit for each class,
    /// asserted against the pure decision so the wiring in `run` (note vs push)
    /// is pinned without needing a real `cargo publish --dry-run`.
    #[test]
    fn cascade_resolvable_skew_becomes_a_note_not_an_issue() {
        let mut planned = BTreeMap::new();
        planned.insert("facett_core".to_string(), "0.1.11".to_string());

        // A DepApiSkew blaming an in-release sibling ⇒ CascadeResolvable ⇒ note.
        let resolvable = match skew_is_cascade_resolvable(Some("facett_core"), &planned) {
            Some(planned) => VerifyOutcome::CascadeResolvable {
                dep: "facett_core".to_string(),
                planned,
            },
            None => VerifyOutcome::Blocker(Issue {
                repo: "facett".into(),
                krate: "facett-graphnav".into(),
                kind: IssueKind::VerifyFailed,
                detail: String::new(),
                fix: String::new(),
                blames: vec!["facett_core".into()],
            }),
        };
        assert_eq!(
            resolvable,
            VerifyOutcome::CascadeResolvable {
                dep: "facett_core".to_string(),
                planned: "0.1.11".to_string(),
            },
        );

        // A DepApiSkew blaming an external crate ⇒ Blocker (VerifyFailed).
        let blocking = match skew_is_cascade_resolvable(Some("libc"), &planned) {
            Some(planned) => VerifyOutcome::CascadeResolvable { dep: "libc".into(), planned },
            None => VerifyOutcome::Blocker(Issue {
                repo: "facett".into(),
                krate: "facett-graphnav".into(),
                kind: IssueKind::VerifyFailed,
                detail: "x".into(),
                fix: "y".into(),
                blames: vec!["libc".into()],
            }),
        };
        assert!(
            matches!(blocking, VerifyOutcome::Blocker(ref i) if i.kind == IssueKind::VerifyFailed),
            "external dep skew must remain a blocker",
        );
    }
}