nornir 0.5.4

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
//! `release doctor` — the **advisory** release report. Read-only, no mutation.
//!
//! Doctrine (2026-07-14 — *release is a build op*): nornir performs NO releases,
//! so the release-doctor CORE — the engine-agnostic PODs (`RepoGraph`, `CrateSkew`,
//! the patch-fork promote gate, `Issue`/`IssueKind`) and the warehouse-FREE
//! read-analysis (skew, publish order, cycles, blast, the `run`/`format_report`
//! report path) — lives in the forge, [`dwarves::release_doctor`]. nornir depends on
//! dwarves (`features = ["release"]`), so there is exactly ONE copy and NO cycle.
//!
//! This module is now MOSTLY a thin RE-EXPORT of `dwarves::release_doctor::{model,
//! doctor}` so every remaining `crate::release::doctor::…` call site resolves the
//! single source of truth in dwarves. What stays NORNIR-OWNED here is only what
//! genuinely needs nornir-only capabilities:
//!
//!  * the working-tree **fixers** (`fix_path_dep_versions` /
//!    `fix_versioned_path_dev_deps` / `apply_cheap_cycle_cuts` / `tidy_dirty_repos`
//!    + `scan_versioned_path_dev_deps`) — the `release doctor --fix/--auto` mutation
//!    operators the CLI still drives; not (yet) relocated to dwarves;
//!  * the ELF/binary graph cross-check (`graph_from_binary` /
//!    [`BinaryDerivedGraph`] / [`cross_check_source_vs_binary`]) — it reads nornir's
//!    own ELF extractor ([`crate::graph::extract::binary`]);
//!  * [`run_with_warehouse_semantic_blast`] — the CLI release entry that DERIVES the
//!    per-repo changed-symbol delta from a fresh syn scan (nornir's own scanner) and
//!    injects it into dwarves' [`run_with_semantic_blast`].

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

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

// ─────────────────── the unified release-doctor core (dwarves) ───────────────────
//
// The engine-agnostic PODs + promote-gate functions, and the warehouse-free
// read-analysis + report path, both live in dwarves now. Re-exported so the twin
// types unify (a value produced by `gather_repo_graph` here IS the same
// `dwarves::release_doctor::model::RepoGraph` the retired depdag/cargo/promote/undo/
// semantic_blast modules flow) and every call site keeps working unchanged.
pub use dwarves::release_doctor::model::{
    compute_promote_block, gather_crate_deps, held_fork_reasons, patch_fork_blockers,
    promote_blocked_crates_precise, CrateSkew, ForkKind, HeldExplanation, HeldFork, Issue,
    IssueKind, PatchForkBlock, PromoteBlockResult, RepoCrateStatus, RepoGraph, SkewStatus,
};
pub use dwarves::release_doctor::doctor::{
    analyze_skew, cascade_order_violations, cfg_cross_deps, crate_majors_in_lock,
    crate_publish_order, crate_publish_order_gated, cross_repo_gating_crates, cycle_advice,
    cycle_solutions, detect_cycles, enrich_transitive_pins, excluded_dev_edges, format_held_explanations,
    format_report, gather_repo_externals, gather_repo_graph, local_crate_versions,
    optional_cross_deps, publish_order, publish_waves, registry_non_gating_crates, repo_dep_edges,
    run, run_with_semantic_blast, scan_path_dep_version_gaps, symptoms, version_pinned_cross_deps,
    CfgCrossDep, CutSolutionView, CycleAdvice, CycleSolution, DepCycle, DepKind, DepPolicy,
    DevEdge, DoctorReport, ForbiddenDep, OptionalCrossDep, OrderViolation, PathDepVersionGap,
    RepoDirty, RepoEdge, RepoExternals, SemanticBlastAudit, TopoReport,
};
// `check_dirty` reads the LOCAL working tree via gix; the pure POD + gatherer live in
// dwarves, so re-export it too (used by the fixers + the warehouse-blast entry below).
pub use dwarves::release_doctor::doctor::check_dirty;

// ─────────────────── publish preflight fixers (nornir-owned) ───────────────────
//
// The `release doctor --fix/--auto` MUTATION operators: they rewrite `Cargo.toml`
// files on disk to close the exact `cargo publish` blockers the (dwarves-side)
// read-analysis surfaces. Not relocated to dwarves — these are the ACT side and stay
// with the CLI verbs for now. They reason over the re-exported dwarves PODs
// (`PathDepVersionGap`, `RepoGraph`, `RepoDirty`).

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

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

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

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

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

/// One `[dev-dependencies]` (or `[target.'cfg'.dev-dependencies]`) entry that
/// carries BOTH a `path` and a `version` on a workspace sibling — the
/// `VersionedPathDevDep` blocker (preflight #6). cargo strips dev-deps on publish
/// but still RESOLVES a versioned one during `cargo publish --verify`, fail-
/// stopping if that sibling isn't live on crates.io. The fix is to DROP the
/// `version` (a path-only dev-dep is stripped cleanly and resolves locally).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VersionedPathDevDep {
    pub repo: String,
    /// Repo-relative manifest path.
    pub manifest: PathBuf,
    /// The dep name carrying both path + version.
    pub dep: String,
}

/// Scan every repo for `[dev-dependencies]` entries with BOTH `path` and
/// `version` (incl. `[target.'cfg'.dev-dependencies]`). Pure read; the
/// counterpart auto-fix is [`fix_versioned_path_dev_deps`]. This is the
/// nornir-owned healer for the exact blocker class the workspace-wide dry-run
/// surfaced across facett/skade/nornir/znippy.
pub fn scan_versioned_path_dev_deps(repos: &[(String, PathBuf)]) -> Vec<VersionedPathDevDep> {
    let mut out = Vec::new();
    for (repo, root) in repos {
        for path in find_cargo_tomls(root, 4) {
            let Ok(txt) = std::fs::read_to_string(&path) else { continue };
            let Ok(doc) = txt.parse::<toml::Value>() else { continue };
            let rel = path.strip_prefix(root).unwrap_or(&path).to_path_buf();
            let mut collect = |tbl: &toml::Value| {
                if let Some(deps) = tbl.get("dev-dependencies").and_then(|d| d.as_table()) {
                    for (name, v) in deps {
                        let Some(t) = v.as_table() else { continue };
                        let has_path = t.get("path").and_then(|p| p.as_str()).is_some();
                        let has_ver = t.get("version").and_then(|v| v.as_str()).is_some();
                        if has_path && has_ver {
                            // The dep's REAL crate name (respect a `package = "…"` rename).
                            let real = t.get("package").and_then(|p| p.as_str()).unwrap_or(name);
                            out.push(VersionedPathDevDep {
                                repo: repo.clone(),
                                manifest: rel.clone(),
                                dep: real.to_string(),
                            });
                        }
                    }
                }
            };
            collect(&doc);
            if let Some(targets) = doc.get("target").and_then(|t| t.as_table()) {
                for (_cfg, t) in targets {
                    collect(t);
                }
            }
        }
    }
    out
}

/// Auto-heal every [`VersionedPathDevDep`] by REMOVING the `version` key from the
/// dev-dep entry (leaving the `path`). Formatting-preserving (`toml_edit`),
/// idempotent (an entry already stripped is simply not re-found). This is the
/// inverse operator of [`fix_path_dep_versions`] and closes the
/// `VersionedPathDevDep` blocker class in `release doctor --fix`.
pub fn fix_versioned_path_dev_deps(
    gaps: &[VersionedPathDevDep],
    repos: &[(String, PathBuf)],
) -> Result<FixOutcome> {
    let repo_root: BTreeMap<&str, &Path> =
        repos.iter().map(|(n, p)| (n.as_str(), p.as_path())).collect();
    let mut by_file: BTreeMap<PathBuf, Vec<&VersionedPathDevDep>> = BTreeMap::new();
    for g in gaps {
        let Some(root) = repo_root.get(g.repo.as_str()) else { continue };
        by_file.entry(root.join(&g.manifest)).or_default().push(g);
    }

    let mut out = FixOutcome::default();
    for (manifest, gs) in by_file {
        let text = std::fs::read_to_string(&manifest)
            .with_context(|| format!("read {}", manifest.display()))?;
        let mut doc: toml_edit::DocumentMut =
            text.parse().with_context(|| format!("parse {}", manifest.display()))?;
        let cfgs: Vec<String> = doc
            .get("target")
            .and_then(|t| t.as_table())
            .map(|t| t.iter().map(|(k, _)| k.to_string()).collect())
            .unwrap_or_default();
        // dev-dep table locators: top-level + each target cfg.
        let mut locators: Vec<Option<String>> = vec![None];
        for c in &cfgs {
            locators.push(Some(c.clone()));
        }
        let mut changed = false;
        for g in gs {
            let mut handled = false;
            for cfg in &locators {
                let Some(tbl) = dev_dep_table_mut(&mut doc, cfg.as_deref()) else { continue };
                // Find the dep key whose real name == g.dep with a path AND a version.
                let key = tbl.iter().find_map(|(k, item)| {
                    let real = item.get("package").and_then(|p| p.as_str()).unwrap_or(k);
                    let has_path = item.get("path").is_some();
                    let has_ver = item.get("version").is_some();
                    (real == g.dep && has_path && has_ver).then(|| k.to_string())
                });
                let Some(key) = key else { continue };
                if let Some(item) = tbl.get_mut(&key) {
                    if let Some(it) = item.as_inline_table_mut() {
                        it.remove("version");
                    } else if let Some(t) = item.as_table_mut() {
                        t.remove("version");
                    }
                    out.fixed += 1;
                    changed = true;
                }
                handled = true;
                break;
            }
            if !handled {
                out.skipped.push(format!(
                    "{}/{}: {} (dev-dep entry not found — already fixed?)",
                    g.repo,
                    g.manifest.display(),
                    g.dep
                ));
            }
        }
        if changed {
            std::fs::write(&manifest, doc.to_string())
                .with_context(|| format!("write {}", manifest.display()))?;
        }
    }
    Ok(out)
}

/// Mutable handle to a `[dev-dependencies]` table (top-level `cfg = None`, or a
/// `[target.'<cfg>'.dev-dependencies]`), creating nothing (returns `None` if
/// absent). Mirrors [`dep_table_mut`] for the dev-dep case.
fn dev_dep_table_mut<'a>(
    doc: &'a mut toml_edit::DocumentMut,
    cfg: Option<&str>,
) -> Option<&'a mut toml_edit::Table> {
    match cfg {
        None => doc.get_mut("dev-dependencies").and_then(|i| i.as_table_mut()),
        Some(c) => doc
            .get_mut("target")
            .and_then(|t| t.as_table_mut())
            .and_then(|t| t.get_mut(c))
            .and_then(|i| i.as_table_mut())
            .and_then(|t| t.get_mut("dev-dependencies"))
            .and_then(|i| i.as_table_mut()),
    }
}

// ─────────────── AUTO remedy executors (#18: --auto apply-fns) ───────────────
//
// `fix-versions` reuses `fix_path_dep_versions` above. These are the other AUTO
// operators the invertive planner (`graph_math::remedy_table`) emits, made
// executable so `release doctor --auto` applies them to a fixpoint instead of
// printing "apply it manually".

/// Outcome of the `tidy-dirty` AUTO remedy.
#[derive(Debug, Default)]
pub struct TidyOutcome {
    /// Noise entries (files + `.claude/` dirs) removed across all dirty repos.
    pub removed: usize,
    /// Repos that became clean after shedding noise.
    pub cleaned: Vec<String>,
    /// Repos still dirty after tidying — real (non-noise) changes remain, so the
    /// dirtiness is a DECISION (commit/stash it), not auto-tidyable.
    pub still_dirty: Vec<String>,
}

/// Working-tree NOISE a dirty repo may shed without a decision: the agent scratch
/// dir (`.claude/`) and arrow scratch files (`*.arrows`). Everything else is real
/// content — never touched.
fn is_tidy_noise_dir(name: &str) -> bool {
    name == ".claude"
}
fn is_tidy_noise_file(name: &str) -> bool {
    name.ends_with(".arrows")
}

/// Recursively delete `.claude/` dirs and `*.arrows` files under `root`, skipping
/// `.git` and `target`. Returns how many top-level noise entries were removed.
fn remove_tidy_noise(root: &Path) -> Result<usize> {
    let mut removed = 0usize;
    let mut stack = vec![root.to_path_buf()];
    while let Some(dir) = stack.pop() {
        let Ok(entries) = std::fs::read_dir(&dir) else { continue };
        for e in entries.flatten() {
            let p = e.path();
            let name = p.file_name().and_then(|n| n.to_str()).unwrap_or("").to_string();
            let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
            if is_dir {
                if name == ".git" || name == "target" {
                    continue;
                }
                if is_tidy_noise_dir(&name) {
                    std::fs::remove_dir_all(&p)
                        .with_context(|| format!("rm -r {}", p.display()))?;
                    removed += 1;
                } else {
                    stack.push(p);
                }
            } else if is_tidy_noise_file(&name) {
                std::fs::remove_file(&p).with_context(|| format!("rm {}", p.display()))?;
                removed += 1;
            }
        }
    }
    Ok(removed)
}

/// The `tidy-dirty` executor: for every DIRTY repo, shed working-tree noise
/// (`.claude/`, `*.arrows`) and re-assess. A repo whose dirtiness was pure noise
/// goes clean (closing the `Dirty` symptom); one with real uncommitted changes
/// stays dirty and is reported (a DECISION for the human). Pure filesystem +
/// gix status — no `git` subprocess.
pub fn tidy_dirty_repos(
    dirty: &[RepoDirty],
    repos: &[(String, PathBuf)],
) -> Result<TidyOutcome> {
    let root_of: BTreeMap<&str, &Path> =
        repos.iter().map(|(n, p)| (n.as_str(), p.as_path())).collect();
    let mut out = TidyOutcome::default();
    for d in dirty.iter().filter(|d| d.dirty) {
        let Some(root) = root_of.get(d.repo.as_str()) else { continue };
        out.removed += remove_tidy_noise(root)?;
        match crate::gitio::worktree_freshness(root) {
            Ok(f) if !f.dirty => out.cleaned.push(d.repo.clone()),
            _ => out.still_dirty.push(d.repo.clone()),
        }
    }
    Ok(out)
}

/// Outcome of the `cut-cycle-cheap` AUTO remedy.
#[derive(Debug, Default)]
pub struct CutOutcome {
    /// The `(from, to)` crate edges physically cut from a manifest.
    pub cut: Vec<(String, String)>,
    /// Cheap cut edges we could not locate in a manifest (reported, not fatal —
    /// e.g. the edge is a `workspace = true` inherit we don't rewrite here).
    pub unresolved: Vec<(String, String)>,
}

/// Drop the dependency on `to_crate` inside a single manifest `[dev-dependencies]`
/// table (incl. `[target.'cfg'.dev-dependencies]`). Returns `true` if removed.
fn cut_dev_edge_in_manifest(doc: &mut toml_edit::DocumentMut, to_crate: &str) -> bool {
    fn real_name<'a>(key: &'a str, item: &'a toml_edit::Item) -> &'a str {
        item.get("package").and_then(|p| p.as_str()).unwrap_or(key)
    }
    // Top-level and per-target dev-dependency tables.
    let mut cut = false;
    if let Some(tbl) = doc.get_mut("dev-dependencies").and_then(|i| i.as_table_like_mut()) {
        let key = tbl.iter().find(|(k, item)| real_name(k, item) == to_crate).map(|(k, _)| k.to_string());
        if let Some(k) = key {
            tbl.remove(&k);
            cut = true;
        }
    }
    if let Some(targets) = doc.get_mut("target").and_then(|i| i.as_table_like_mut()) {
        let cfgs: Vec<String> = targets.iter().map(|(k, _)| k.to_string()).collect();
        for cfg in cfgs {
            if let Some(tbl) = targets
                .get_mut(&cfg)
                .and_then(|i| i.get_mut("dev-dependencies"))
                .and_then(|i| i.as_table_like_mut())
            {
                let key = tbl.iter().find(|(k, item)| real_name(k, item) == to_crate).map(|(k, _)| k.to_string());
                if let Some(k) = key {
                    tbl.remove(&k);
                    cut = true;
                }
            }
        }
    }
    cut
}

/// Cut the edge on `to_crate` inside `repo_root`'s manifests. Preference order
/// matches the MFAS cost model: a **dev** edge (cost 0) is removed outright; an
/// **optional** `[dependencies]` edge (cost 1) is removed together with the
/// `[features]` references that enabled it (gate the feature off). A NORMAL hard
/// dep is NOT cut (that is a crate-split DECISION). Returns `true` if a manifest
/// was edited.
fn cut_edge_in_repo(repo_root: &Path, to_crate: &str) -> Result<bool> {
    for manifest in find_cargo_tomls(repo_root, 3) {
        let text = std::fs::read_to_string(&manifest)
            .with_context(|| format!("read {}", manifest.display()))?;
        let mut doc: toml_edit::DocumentMut =
            text.parse().with_context(|| format!("parse {}", manifest.display()))?;

        // Cost-0: drop a dev edge.
        if cut_dev_edge_in_manifest(&mut doc, to_crate) {
            std::fs::write(&manifest, doc.to_string())
                .with_context(|| format!("write {}", manifest.display()))?;
            return Ok(true);
        }

        // Cost-1: an OPTIONAL normal dep → remove it + scrub the features that
        // enabled it (gate the feature off).
        let opt_key = doc
            .get("dependencies")
            .and_then(|i| i.as_table_like())
            .and_then(|tbl| {
                tbl.iter().find_map(|(k, item)| {
                    let real = item.get("package").and_then(|p| p.as_str()).unwrap_or(k);
                    let optional = item.get("optional").and_then(|o| o.as_bool()).unwrap_or(false);
                    (real == to_crate && optional).then(|| k.to_string())
                })
            });
        if let Some(key) = opt_key {
            if let Some(tbl) = doc.get_mut("dependencies").and_then(|i| i.as_table_like_mut()) {
                tbl.remove(&key);
            }
            scrub_feature_refs(&mut doc, &key);
            std::fs::write(&manifest, doc.to_string())
                .with_context(|| format!("write {}", manifest.display()))?;
            return Ok(true);
        }
    }
    Ok(false)
}

/// Remove every `[features]` reference to the (now-dropped) optional dep `key`:
/// bare `key`, explicit `dep:key`, and weak `key?/feat` / `key/feat` activations.
/// A feature whose only member was that ref is left as an empty array (harmless)
/// rather than deleted, so an external `--features <name>` invocation still
/// resolves.
fn scrub_feature_refs(doc: &mut toml_edit::DocumentMut, key: &str) {
    let Some(features) = doc.get_mut("features").and_then(|i| i.as_table_like_mut()) else {
        return;
    };
    let feat_names: Vec<String> = features.iter().map(|(k, _)| k.to_string()).collect();
    for fname in feat_names {
        if let Some(arr) = features.get_mut(&fname).and_then(|i| i.as_array_mut()) {
            arr.retain(|v| {
                let s = v.as_str().unwrap_or("");
                let dep = s.strip_prefix("dep:").unwrap_or(s);
                let base = dep.split(['/', '?']).next().unwrap_or(dep);
                base != key
            });
        }
    }
}

/// The `cut-cycle-cheap` executor: rebuild the crate graph from the live
/// manifests, and for every CHEAP (MFAS cut cost ≤ 1) dependency cycle, apply
/// its cheapest cut by editing the manifest that declares the edge (see
/// [`cut_edge_in_repo`]). Returns the edges cut; a cheap cut whose manifest edge
/// can't be located is reported in `unresolved` (never fatal).
pub fn apply_cheap_cycle_cuts(repos: &[(String, PathBuf)]) -> Result<CutOutcome> {
    let graphs: Vec<RepoGraph> = repos
        .iter()
        .filter_map(|(n, p)| gather_repo_graph(n, p).ok())
        .collect();
    let (owner, _adj) = crate_graph(&graphs);
    let root_of: BTreeMap<&str, &Path> =
        repos.iter().map(|(n, p)| (n.as_str(), p.as_path())).collect();
    let mut out = CutOutcome::default();
    for cs in cycle_solutions(&graphs) {
        let Some(best) = cs.solutions.first() else { continue };
        if best.cost > 1 {
            continue; // not cheap → a crate-split DECISION, not an AUTO cut
        }
        for (from, to) in &best.edges {
            let located = owner
                .get(from)
                .and_then(|repo| root_of.get(repo.as_str()))
                .map(|root| cut_edge_in_repo(root, to))
                .transpose()?
                .unwrap_or(false);
            if located {
                out.cut.push((from.clone(), to.clone()));
            } else {
                out.unresolved.push((from.clone(), to.clone()));
            }
        }
    }
    Ok(out)
}

// ─────────────────────────── shared nornir-owned helpers ───────────────────────────

/// Find `Cargo.toml` files under `root` up to `max_depth`, skipping `target`,
/// `.git`, and other hidden directories. (dwarves owns its own copy for the
/// relocated gatherers; this stays for the nornir-owned fixers above.)
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();
            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
}

/// The CRATE-level order graph: crate name → owning repo, and crate name → its
/// in-workspace order-gating dep crate names (filtered to crates actually produced
/// somewhere). Used by [`apply_cheap_cycle_cuts`] to locate the manifest that
/// declares a cut edge.
fn crate_graph(
    graphs: &[RepoGraph],
) -> (
    BTreeMap<String, String>,
    BTreeMap<String, std::collections::BTreeSet<String>>,
) {
    use std::collections::BTreeSet;
    let mut owner: BTreeMap<String, String> = BTreeMap::new();
    let produced: BTreeSet<String> =
        graphs.iter().flat_map(|g| g.crate_deps.keys().cloned()).collect();
    let mut adj: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
    for g in graphs {
        for (c, deps) in &g.crate_deps {
            owner.entry(c.clone()).or_insert_with(|| g.repo.clone());
            let e = adj.entry(c.clone()).or_default();
            for d in deps {
                if d != c && produced.contains(d) {
                    e.insert(d.clone());
                }
            }
        }
    }
    (owner, adj)
}

// ─────────── ELF/binary graph cross-check (graph_math over linked binaries) ───────────

/// The ELF/binary symbol-dependency graph projected into the SAME graph_math
/// shape the source [`RepoGraph`] uses — the release doctor's second witness:
/// what the LINKED BINARIES actually reference, alongside what the SOURCE
/// manifests declare. Built by [`graph_from_binary`] over
/// [`crate::graph::extract::binary`] (the extractor the CLI `graph binary` verb
/// drives via `to_symbol_rows` / `to_call_edge_rows`).
#[derive(Debug, Clone, Default)]
pub struct BinaryDerivedGraph {
    /// object-node → the object nodes it links against (`DT_NEEDED` + resolved
    /// symbol edges) — the adjacency graph_math's Tarjan/MFAS consume.
    pub adjacency: BTreeMap<String, std::collections::BTreeSet<String>>,
    /// Non-trivial strongly-connected components (link cycles), Tarjan-sorted.
    pub cycles: Vec<Vec<String>>,
    /// Provide/need symbol facts (mirrors the source syn symbol pass).
    pub symbol_rows: Vec<crate::knowledge::symbols::SymbolRow>,
    /// PLT/GOT call edges (mirrors the source call-edge pass).
    pub call_edge_rows: Vec<crate::knowledge::symbols::CallEdgeRow>,
}

impl BinaryDerivedGraph {
    /// Project a [`WorkspaceGraph`](crate::warehouse::dep_graph::WorkspaceGraph)
    /// — the shared model
    /// [`BinaryGraph::to_workspace_graph`](crate::graph::extract::binary::BinaryGraph::to_workspace_graph)
    /// yields — onto the adjacency + cycle structure. Every node appears even with
    /// no out-edges, so an isolated object is still a graph node.
    pub fn from_workspace(wg: &crate::warehouse::dep_graph::WorkspaceGraph) -> Self {
        let mut adjacency: BTreeMap<String, std::collections::BTreeSet<String>> = BTreeMap::new();
        for name in wg.facts.keys() {
            adjacency.entry(name.clone()).or_default();
        }
        for e in &wg.edges {
            adjacency.entry(e.from.clone()).or_default().insert(e.to.clone());
            adjacency.entry(e.to.clone()).or_default();
        }
        let cycles = super::graph_math::cycles(&adjacency);
        Self { adjacency, cycles, symbol_rows: Vec::new(), call_edge_rows: Vec::new() }
    }
}

/// Extract the ELF/binary symbol graph from `paths` and project it into the
/// graph_math shape — the doctor entry over the same extractor the CLI
/// `graph binary` verb drives. Carries the `symbol_rows` / `call_edge_rows` (the
/// warehouse projection) alongside the adjacency + cycles. An unreadable /
/// non-ELF input is skipped inside the extractor, never fatal.
pub fn graph_from_binary(paths: &[PathBuf]) -> Result<BinaryDerivedGraph> {
    let bg = crate::graph::extract::binary::extract_graph(paths)?;
    let wg = bg.to_workspace_graph();
    let mut d = BinaryDerivedGraph::from_workspace(&wg);
    d.symbol_rows = bg.to_symbol_rows();
    d.call_edge_rows = bg.to_call_edge_rows();
    Ok(d)
}

/// The outcome of cross-checking the SOURCE dependency graph against the
/// ELF-derived graph: whether their cycle structure (SCC partition) and their
/// minimum-feedback-arc cut sizes agree.
#[derive(Debug, Clone, Serialize)]
pub struct GraphCrossCheck {
    /// Non-trivial SCCs (sorted node lists) present in BOTH graphs.
    pub shared_cycles: Vec<Vec<String>>,
    /// Cycles the SOURCE graph has that the binary graph does not.
    pub source_only_cycles: Vec<Vec<String>>,
    /// Cycles the BINARY graph has that the source graph does not.
    pub binary_only_cycles: Vec<Vec<String>>,
    /// Per shared cycle where the MFAS min-cut cost differs: `(members, source, binary)`.
    pub mfas_divergences: Vec<(Vec<String>, u32, u32)>,
}

impl GraphCrossCheck {
    /// The two graphs agree iff neither carries a cycle the other lacks AND every
    /// shared cycle has the same minimum-cut cost in both.
    pub fn agrees(&self) -> bool {
        self.source_only_cycles.is_empty()
            && self.binary_only_cycles.is_empty()
            && self.mfas_divergences.is_empty()
    }
}

/// Cross-check the SOURCE crate-dependency graph (`source`, e.g. from
/// [`repo_dep_edges`]) against the ELF-derived graph (`binary`, from
/// [`graph_from_binary`]'s `adjacency`): compares their cycle partition (Tarjan
/// SCCs) and, per shared cycle, the minimum feedback-arc-set cut cost. A
/// divergence means "what the manifests declare" and "what the binaries link"
/// disagree about where the release is tangled — a doctor-worthy signal that the
/// source graph and the shipped artefacts have drifted.
pub fn cross_check_source_vs_binary(
    source: &BTreeMap<String, std::collections::BTreeSet<String>>,
    binary: &BTreeMap<String, std::collections::BTreeSet<String>>,
) -> GraphCrossCheck {
    use std::collections::BTreeSet;
    let src_set: BTreeSet<Vec<String>> = super::graph_math::cycles(source).into_iter().collect();
    let bin_set: BTreeSet<Vec<String>> = super::graph_math::cycles(binary).into_iter().collect();

    let shared_cycles: Vec<Vec<String>> = src_set.intersection(&bin_set).cloned().collect();
    let source_only_cycles: Vec<Vec<String>> = src_set.difference(&bin_set).cloned().collect();
    let binary_only_cycles: Vec<Vec<String>> = bin_set.difference(&src_set).cloned().collect();

    let mut mfas_divergences = Vec::new();
    for comp in &shared_cycles {
        let s_cost = min_cut_cost(source, comp);
        let b_cost = min_cut_cost(binary, comp);
        if s_cost != b_cost {
            mfas_divergences.push((comp.clone(), s_cost, b_cost));
        }
    }
    GraphCrossCheck { shared_cycles, source_only_cycles, binary_only_cycles, mfas_divergences }
}

/// Minimum feedback-arc-set cut cost for one cyclic component `comp` under `adj`
/// — every intra-component edge classed `Normal` (a structural link cut). `0`
/// when the component carries no intra-cycle edges.
fn min_cut_cost(
    adj: &BTreeMap<String, std::collections::BTreeSet<String>>,
    comp: &[String],
) -> u32 {
    let members: std::collections::BTreeSet<&String> = comp.iter().collect();
    let edges: Vec<super::graph_math::ClassifiedEdge> = comp
        .iter()
        .flat_map(|from| {
            adj.get(from)
                .into_iter()
                .flatten()
                .filter(|to| members.contains(to))
                .map(move |to| super::graph_math::ClassifiedEdge {
                    from: from.clone(),
                    to: to.clone(),
                    via: Vec::new(),
                    class: super::graph_math::EdgeClass::Normal,
                })
        })
        .collect();
    super::graph_math::min_feedback_arc_set(comp, &edges)
        .into_iter()
        .map(|s| s.cost)
        .min()
        .unwrap_or(0)
}

// ─────────────── warehouse-aware semantic blast (nornir syn scanner) ───────────────

/// **THE CLI RELEASE ENTRY POINT** — [`run`] with `semantic_blast` actually
/// POPULATED from the warehouse, so [`crate::release::gate::semantic_link_gate`] is
/// REACHABLE in production. The plain [`run`] hard-sets an empty map (the gate could
/// never fire — the inert-gate bug); this derives the real per-repo changed-symbol
/// set from the working tree and feeds dwarves' [`run_with_semantic_blast`].
///
/// This is the NORNIR-OWNED half of the split: dwarves' `run_with_semantic_blast`
/// is INJECTABLE (the caller supplies the changed symbols), because the syn scanner
/// that DERIVES the delta ([`crate::knowledge::symbols::scan_repo`]) is nornir-owned.
///
/// For every DIRTY repo (a working tree with a pending bump) it diffs the
/// last-persisted exported surface the warehouse holds (via
/// [`crate::knowledge::query::load_latest`]) against a fresh, build-free syn scan of
/// the current tree with [`crate::release::semantic_blast::diff_exported_symbols`].
/// Removed/changed exported symbols become the bump's API-surface delta, which
/// [`run_with_semantic_blast`] resolves against the dependents' call-graph.
///
/// GRACEFUL DEGRADE — never panics, never hard-fails on missing data:
///   * no dirty repo → nothing to diff → plain [`run`] (empty blast, gate skips),
///   * a dirty repo with NO persisted warehouse surface → empty OLD side → no
///     removals derivable → it contributes nothing,
///   * a dirty repo whose surface is unchanged → empty delta → contributes nothing.
///
/// If NO repo yields a delta the result is byte-identical to the plain [`run`]
/// (empty `semantic_blast`), and the returned [`SemanticBlastAudit`] states which
/// degrade path was taken. Opening the warehouse is the CALLER's job.
pub fn run_with_warehouse_semantic_blast(
    repos: &[(String, PathBuf)],
    policy: &DepPolicy,
    wh: &dyn crate::warehouse::Warehouse,
) -> Result<(DoctorReport, SemanticBlastAudit)> {
    use crate::release::semantic_blast::{diff_exported_symbols, ChangedSymbol};

    let mut audit = SemanticBlastAudit::default();
    let dirty: Vec<String> = check_dirty(repos)
        .into_iter()
        .filter(|d| d.dirty)
        .map(|d| d.repo)
        .collect();
    audit.dirty_considered = dirty.clone();

    if dirty.is_empty() {
        audit.note =
            "no dirty repos → no pending bump to diff; semantic blast empty (link gate skipped)"
                .to_string();
        return Ok((run(repos, policy)?, audit));
    }

    // Per DIRTY repo: OLD exported surface (warehouse) vs NEW (fresh syn scan) →
    // the bump's changed/removed symbol delta.
    let mut changed_by_repo: Vec<(String, Vec<ChangedSymbol>)> = Vec::new();
    for (name, path) in repos {
        if !dirty.iter().any(|d| d == name) {
            continue;
        }
        // OLD: the last snapshot's symbols the warehouse persisted for this repo.
        // A read failure / no rows ⇒ no OLD surface to diff (degrade, not fatal).
        let old = match crate::knowledge::query::load_latest(wh, name) {
            Ok(view) => view.symbols,
            Err(_) => Vec::new(),
        };
        if old.is_empty() {
            continue;
        }
        // NEW: a fresh, build-free syn scan of the current working tree.
        let new = match crate::knowledge::symbols::scan_repo(
            path,
            name,
            uuid::Uuid::new_v4(),
            chrono::Utc::now(),
        ) {
            Ok(scan) => scan.symbols,
            Err(_) => continue,
        };
        let delta = diff_exported_symbols(&old, &new);
        if !delta.is_empty() {
            audit.changed_symbols.insert(name.clone(), delta.len());
            changed_by_repo.push((name.clone(), delta));
        }
    }

    if changed_by_repo.is_empty() {
        audit.note = format!(
            "{} dirty repo(s), but no exported-surface delta \
             (unchanged API or no persisted warehouse surface) → semantic blast empty (link gate skipped)",
            dirty.len()
        );
        return Ok((run(repos, policy)?, audit));
    }

    let refs: Vec<(&str, &[ChangedSymbol])> = changed_by_repo
        .iter()
        .map(|(r, cs)| (r.as_str(), cs.as_slice()))
        .collect();
    let report = run_with_semantic_blast(repos, policy, wh, refs)?;
    audit.populated = !report.semantic_blast.is_empty();
    audit.note = format!(
        "semantic blast: diffed {} dirty repo(s), {} with a surface delta; \
         {} carry a populated cross-crate blast (link gate LIVE)",
        dirty.len(),
        changed_by_repo.len(),
        report.semantic_blast.len(),
    );
    Ok((report, audit))
}

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

    #[test]
    fn scan_and_fix_versioned_path_dev_deps_strips_version_keeps_path() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // A crate with TWO versioned path dev-deps (one inline, one target-cfg) plus
        // a legit path-only dev-dep (must be left alone) and a normal versioned dep.
        std::fs::write(
            root.join("Cargo.toml"),
            r#"[package]
name = "consumer"
version = "0.5.0"

[dependencies]
serde = { version = "1", path = "../serde-fork" }

[dev-dependencies]
sibling-a = { path = "../sibling-a", version = "0.1" }
sibling-ok = { path = "../sibling-ok" }

[target.'cfg(unix)'.dev-dependencies]
sibling-b = { version = "0.2.1", path = "../sibling-b" }
"#,
        )
        .unwrap();

        let repos = vec![("consumer".to_string(), root.to_path_buf())];
        let mut gaps = scan_versioned_path_dev_deps(&repos);
        gaps.sort_by(|a, b| a.dep.cmp(&b.dep));
        let deps: Vec<&str> = gaps.iter().map(|g| g.dep.as_str()).collect();
        assert_eq!(deps, vec!["sibling-a", "sibling-b"], "only path+version DEV-deps");

        let out = fix_versioned_path_dev_deps(&gaps, &repos).unwrap();
        assert_eq!(out.fixed, 2);
        let after = std::fs::read_to_string(root.join("Cargo.toml")).unwrap();
        // Reparse (formatting-tolerant): the two dev-deps lost their version but
        // kept their path; the path-only dev-dep and the normal dep are untouched.
        let doc: toml::Value = after.parse().unwrap();
        let dev = |v: &toml::Value, table: &str, name: &str| -> toml::Value {
            v.get(table).and_then(|t| t.get(name)).cloned().unwrap()
        };
        let a = dev(&doc, "dev-dependencies", "sibling-a");
        assert!(a.get("version").is_none(), "sibling-a version dropped");
        assert_eq!(a.get("path").and_then(|p| p.as_str()), Some("../sibling-a"));
        let b = doc["target"]["cfg(unix)"]["dev-dependencies"]["sibling-b"].clone();
        assert!(b.get("version").is_none(), "sibling-b version dropped");
        assert_eq!(b.get("path").and_then(|p| p.as_str()), Some("../sibling-b"));
        // Untouched: the path-only dev-dep, and the NORMAL versioned path dep.
        let ok = dev(&doc, "dev-dependencies", "sibling-ok");
        assert_eq!(ok.get("path").and_then(|p| p.as_str()), Some("../sibling-ok"));
        let serde = dev(&doc, "dependencies", "serde");
        assert_eq!(serde.get("version").and_then(|v| v.as_str()), Some("1"), "normal dep kept");

        // Idempotent: a second scan finds nothing.
        assert!(scan_versioned_path_dev_deps(&repos).is_empty(), "healed → nothing left");
    }
}

#[cfg(test)]
mod semantic_blast_run_tests {
    use super::*;
    use crate::knowledge::symbols::{CallEdgeRow, SymbolRow, SymbolScan};
    use crate::warehouse::iceberg::IcebergWarehouse;

    fn write(path: &Path, body: &str) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(path, body).unwrap();
    }

    /// Seed the warehouse so `korp` calls `facett::render` (one cross-crate site).
    fn seed_korp_calls_facett(wh: &IcebergWarehouse) {
        let scan = SymbolScan {
            snapshot_id: uuid::Uuid::new_v4(),
            ts: chrono::Utc::now(),
            repo: "korp".into(),
            symbols: vec![SymbolRow {
                crate_name: "korp".into(),
                module_path: "korp::view".into(),
                item_kind: "fn".into(),
                item_name: "draw".into(),
                visibility: "pub".into(),
                file: "korp/src/view.rs".into(),
                line: 1,
                doc_lines: 0,
                signature: None,
            }],
            calls: vec![CallEdgeRow {
                crate_name: "korp".into(),
                caller_path: "korp::view::draw".into(),
                callee_ident: "facett::render".into(),
                call_kind: "call".into(),
                file: "korp/src/view.rs".into(),
                line: 40,
            }],
            features: vec![],
            tests: vec![],
        };
        wh.append_symbol_scan(&scan).unwrap();
    }

    /// `git init` a repo so [`check_dirty`]'s `gix::open` succeeds; the files stay
    /// UNTRACKED, which `worktree_freshness` reports as dirty — exactly the "pending
    /// bump" state the CLI release path diffs.
    fn git_init(root: &Path) {
        std::fs::create_dir_all(root).unwrap();
        let ok = std::process::Command::new("git")
            .arg("-C").arg(root).arg("init")
            .status().map(|s| s.success()).unwrap_or(false);
        assert!(ok, "git init failed (is git installed?)");
    }

    /// Seed one repo's persisted exported surface (the OLD side the CLI diffs a
    /// fresh working-tree scan against). Each `(name, vis)` is one `SymbolRow`.
    fn seed_symbols(wh: &IcebergWarehouse, repo: &str, syms: &[(&str, &str)]) {
        let symbols = syms
            .iter()
            .map(|(name, vis)| SymbolRow {
                crate_name: repo.into(),
                module_path: format!("{repo}::api"),
                item_kind: "fn".into(),
                item_name: (*name).into(),
                visibility: (*vis).into(),
                file: format!("{repo}/src/lib.rs"),
                line: 1,
                doc_lines: 0,
                signature: None,
            })
            .collect();
        let scan = SymbolScan {
            snapshot_id: uuid::Uuid::new_v4(),
            ts: chrono::Utc::now(),
            repo: repo.into(),
            symbols,
            calls: vec![],
            features: vec![],
            tests: vec![],
        };
        wh.append_symbol_scan(&scan).unwrap();
    }

    /// END-TO-END through the WIRED CLI entry point (the inert-gate bug fix): a
    /// DIRTY `facett` that REMOVED an exported `render` a dependent `korp` still
    /// calls. [`run_with_warehouse_semantic_blast`] diffs facett's warehouse surface
    /// against its working tree, populates `semantic_blast`, and
    /// [`crate::release::gate::semantic_link_gate`] then FIRES on the real data —
    /// where before it read an always-empty map and could never fail.
    #[test]
    fn wired_path_populates_blast_and_link_gate_fires() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let facett = root.join("facett");
        let korp = root.join("korp");

        // facett: exports `render` + `open`; a git repo (untracked ⇒ dirty). The
        // working tree DROPS `render` (the bump) — only `open` remains scannable.
        write(&facett.join("Cargo.toml"),
            "[package]\nname = \"facett\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
        write(&facett.join("src/lib.rs"), "pub fn open() {}\n");
        git_init(&facett);
        // korp depends on the facett crate → blast_radius(facett) == [korp].
        write(&korp.join("Cargo.toml"),
            "[package]\nname = \"korp\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
             [dependencies]\nfacett = { path = \"../facett\", version = \"0.1.0\" }\n");
        write(&korp.join("src/lib.rs"), "pub fn draw() {}\n");

        // Warehouse: facett's LAST-PERSISTED surface still had `render` (pub); korp
        // calls facett::render (the live cross-crate site the removal breaks).
        let wh = IcebergWarehouse::open(&root.join("wh")).unwrap();
        seed_symbols(&wh, "facett", &[("render", "pub"), ("open", "pub")]);
        seed_korp_calls_facett(&wh);

        let repos = vec![
            ("facett".to_string(), facett.clone()),
            ("korp".to_string(), korp.clone()),
        ];
        let policy = DepPolicy::default();

        let (report, audit) =
            run_with_warehouse_semantic_blast(&repos, &policy, &wh).unwrap();

        // The wiring saw facett as dirty, derived the one removed symbol, populated.
        assert!(
            audit.dirty_considered.contains(&"facett".to_string()),
            "facett must be considered dirty: {:?}", audit.dirty_considered,
        );
        assert_eq!(
            audit.changed_symbols.get("facett"), Some(&1),
            "the removed `render` is the sole surface delta: {:?}", audit.changed_symbols,
        );
        assert!(audit.populated, "semantic blast must be populated: {}", audit.note);

        let sb = report.semantic_blast.get("facett")
            .expect("facett carries a populated semantic blast");
        assert!(sb.has_link_error(), "removed `render` + a live korp call site = link error");

        // THE FIX: the gate SEES the populated map and FAILS (was inert on an empty map).
        let gate = crate::release::gate::semantic_link_gate(&report.semantic_blast);
        let fired = gate.is_err();
        let msg = gate.err().map(|e| e.to_string()).unwrap_or_default();

        nornir_testmatrix::functional_status(
            "release-doctor",
            "wired_semantic_link_gate_fires",
            fired && audit.populated && msg.contains("render"),
            &format!("note={:?} gate_msg={msg:?}", audit.note),
        );

        assert!(fired, "semantic_link_gate must FIRE on the wired blast (was inert): {}", audit.note);
        assert!(msg.contains("LINK ERROR") && msg.contains("render"),
            "gate names the removed symbol: {msg}");
    }

    /// The GRACEFUL-DEGRADE path: a dirty repo with NO persisted warehouse surface
    /// (a clean checkout against an unseeded warehouse) yields an empty blast, so the
    /// gate SKIPS — never a spurious failure, never a panic.
    #[test]
    fn wired_path_degrades_to_empty_when_no_warehouse_surface() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        let facett = root.join("facett");
        write(&facett.join("Cargo.toml"),
            "[package]\nname = \"facett\"\nversion = \"0.1.0\"\nedition = \"2021\"\n");
        write(&facett.join("src/lib.rs"), "pub fn open() {}\n");
        git_init(&facett); // dirty (untracked), but the warehouse holds nothing.

        let wh = IcebergWarehouse::open(&root.join("wh")).unwrap();
        let repos = vec![("facett".to_string(), facett.clone())];
        let policy = DepPolicy::default();

        let (report, audit) =
            run_with_warehouse_semantic_blast(&repos, &policy, &wh).unwrap();
        assert!(report.semantic_blast.is_empty(), "no OLD surface ⇒ empty blast");
        assert!(!audit.populated, "degraded, not populated: {}", audit.note);
        // And the gate trivially passes over the empty map (skipped, not failed).
        assert!(crate::release::gate::semantic_link_gate(&report.semantic_blast).is_ok());
    }

    // ─── #18 AUTO remedy executors ───

    #[test]
    fn tidy_dirty_sheds_noise_but_keeps_real_changes() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("myrepo");
        write(&root.join("Cargo.toml"), "[package]\nname=\"m\"\nversion=\"0.1.0\"\n");
        write(&root.join("src/lib.rs"), "pub fn a() {}\n");
        crate::gitio::init(&root).unwrap();
        crate::gitio::commit_all(&root, "seed").unwrap();
        assert!(!crate::gitio::worktree_freshness(&root).unwrap().dirty, "clean baseline");

        // Case 1: dirtiness is PURE noise → tidy removes it → repo goes clean.
        write(&root.join(".claude/scratch.txt"), "junk\n");
        write(&root.join("data.arrows"), "\x00arrow\n");
        write(&root.join("src/deep/nested.arrows"), "\x00\n");
        assert!(crate::gitio::worktree_freshness(&root).unwrap().dirty);
        let repos = vec![("myrepo".to_string(), root.clone())];
        let dirty = check_dirty(&repos);
        let out = tidy_dirty_repos(&dirty, &repos).unwrap();
        assert_eq!(out.removed, 3, "two .arrows files + one .claude dir");
        assert_eq!(out.cleaned, vec!["myrepo".to_string()]);
        assert!(out.still_dirty.is_empty());
        assert!(!root.join(".claude").exists());
        assert!(!root.join("data.arrows").exists());
        assert!(!crate::gitio::worktree_freshness(&root).unwrap().dirty, "clean after tidy");

        // Case 2: a REAL untracked file → tidy can't fix it → still dirty.
        write(&root.join("src/new_real.rs"), "pub fn b() {}\n");
        write(&root.join("more.arrows"), "\x00\n");
        let dirty2 = check_dirty(&repos);
        let out2 = tidy_dirty_repos(&dirty2, &repos).unwrap();
        assert_eq!(out2.removed, 1, "only the .arrows noise is shed");
        assert!(out2.cleaned.is_empty());
        assert_eq!(out2.still_dirty, vec!["myrepo".to_string()], "real change remains");
        assert!(root.join("src/new_real.rs").exists(), "real file untouched");
    }

    #[test]
    fn cut_cycle_cheap_drops_the_optional_edge_and_scrubs_features() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        // acrate → bcrate (normal path); bcrate → acrate (OPTIONAL path, gated).
        // The MFAS cheapest cut (cost 1) is the optional edge bcrate→acrate.
        write(&root.join("repoA/Cargo.toml"), r#"[package]
name = "acrate"
version = "0.1.0"
edition = "2021"

[dependencies]
bcrate = { path = "../repoB" }
"#);
        write(&root.join("repoB/Cargo.toml"), r#"[package]
name = "bcrate"
version = "0.1.0"
edition = "2021"

[dependencies]
acrate = { path = "../repoA", optional = true }

[features]
withA = ["dep:acrate"]
"#);
        let repos = vec![
            ("repoA".to_string(), root.join("repoA")),
            ("repoB".to_string(), root.join("repoB")),
        ];
        // Precondition: the crate graph really has the cheap cycle.
        let graphs: Vec<RepoGraph> =
            repos.iter().map(|(n, p)| gather_repo_graph(n, p).unwrap()).collect();
        let sols = cycle_solutions(&graphs);
        assert_eq!(sols.len(), 1, "one crate cycle: {sols:#?}");
        assert!(sols[0].solutions.first().unwrap().cost <= 1, "cheap (optional) cut");

        let out = apply_cheap_cycle_cuts(&repos).unwrap();
        assert_eq!(out.cut, vec![("bcrate".to_string(), "acrate".to_string())]);
        assert!(out.unresolved.is_empty(), "{:#?}", out.unresolved);

        // repoB no longer declares acrate, and the feature no longer references it.
        let b = std::fs::read_to_string(root.join("repoB/Cargo.toml")).unwrap();
        assert!(!b.contains("acrate = {"), "optional dep removed:\n{b}");
        assert!(!b.contains("dep:acrate"), "feature ref scrubbed:\n{b}");
        // And the cycle is gone.
        let graphs2: Vec<RepoGraph> =
            repos.iter().map(|(n, p)| gather_repo_graph(n, p).unwrap()).collect();
        assert!(cycle_solutions(&graphs2).is_empty(), "cycle broken");
    }
}

#[cfg(test)]
mod binary_graph_cross_check_tests {
    use super::*;
    use crate::warehouse::dep_graph::{CrossRepoEdge, WorkspaceGraph};
    use std::collections::BTreeSet;

    fn adj(pairs: &[(&str, &str)]) -> BTreeMap<String, BTreeSet<String>> {
        let mut m: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
        for (a, b) in pairs {
            m.entry(a.to_string()).or_default().insert(b.to_string());
            m.entry(b.to_string()).or_default();
        }
        m
    }

    /// The ELF-derived graph, built through the SAME projection production uses
    /// (`BinaryGraph::to_workspace_graph` → `BinaryDerivedGraph::from_workspace`),
    /// matches the source graph's cycle structure AND its MFAS min-cut cost when
    /// the two constellations carry the same link cycle.
    #[test]
    fn binary_derived_scc_and_mfas_match_source() {
        // Source crate graph: a ⇄ b cycle, plus a→c tail (c is a clean leaf).
        let source = adj(&[("a", "b"), ("b", "a"), ("a", "c")]);

        // ELF constellation with the identical topology, projected via the shared
        // WorkspaceGraph model (what to_workspace_graph yields for real objects).
        let bin_edges = vec![
            CrossRepoEdge::normal("a", "b", ["s_ab".to_string()].into_iter().collect()),
            CrossRepoEdge::normal("b", "a", ["s_ba".to_string()].into_iter().collect()),
            CrossRepoEdge::normal("a", "c", ["s_ac".to_string()].into_iter().collect()),
        ];
        let wg = WorkspaceGraph::from_query_parts(Default::default(), bin_edges);
        let derived = BinaryDerivedGraph::from_workspace(&wg);

        // The binary projection found exactly the one a⇄b cycle.
        assert_eq!(derived.cycles, vec![vec!["a".to_string(), "b".to_string()]]);

        // Cross-check: SCC partition + MFAS cut cost agree.
        let cc = cross_check_source_vs_binary(&source, &derived.adjacency);
        assert!(cc.agrees(), "source and ELF graphs agree: {cc:?}");
        assert_eq!(cc.shared_cycles, vec![vec!["a".to_string(), "b".to_string()]]);
        assert!(cc.source_only_cycles.is_empty());
        assert!(cc.binary_only_cycles.is_empty());
        assert!(cc.mfas_divergences.is_empty());
    }

    /// A DIVERGENCE — the binaries link a cycle the source manifests do not
    /// declare (or vice-versa) — is flagged, not silently passed. This is the
    /// doctor signal that source and shipped artefacts have drifted.
    #[test]
    fn binary_derived_divergence_from_source_is_flagged() {
        // Source is a clean DAG a→b→c (no cycle).
        let source = adj(&[("a", "b"), ("b", "c")]);
        // The linked binaries, though, carry a b⇄c back-edge (a real link cycle).
        let bin_edges = vec![
            CrossRepoEdge::normal("a", "b", ["s".to_string()].into_iter().collect()),
            CrossRepoEdge::normal("b", "c", ["s".to_string()].into_iter().collect()),
            CrossRepoEdge::normal("c", "b", ["s".to_string()].into_iter().collect()),
        ];
        let wg = WorkspaceGraph::from_query_parts(Default::default(), bin_edges);
        let derived = BinaryDerivedGraph::from_workspace(&wg);

        let cc = cross_check_source_vs_binary(&source, &derived.adjacency);
        assert!(!cc.agrees(), "a binary-only cycle must NOT pass the cross-check");
        assert_eq!(cc.binary_only_cycles, vec![vec!["b".to_string(), "c".to_string()]]);
        assert!(cc.source_only_cycles.is_empty());
        assert!(cc.shared_cycles.is_empty());
    }

    /// `graph_from_binary` drives the real ELF extractor end-to-end: point it at
    /// the test binary's own executable (a genuine ELF on this Linux target) and
    /// assert it yields a non-empty symbol graph with the object as a node. Guards
    /// the extraction → projection wiring, not just the pure cross-check math.
    #[test]
    fn graph_from_binary_reads_a_real_elf() {
        let exe = std::env::current_exe().expect("test exe path");
        let derived = graph_from_binary(&[exe]).expect("extract ELF graph from the test binary");
        assert!(!derived.adjacency.is_empty(), "the ELF object is a graph node");
        assert!(
            !derived.symbol_rows.is_empty(),
            "a dynamically-linked ELF exposes .dynsym symbol rows"
        );
    }
}