xbp 10.57.0

XBP is a zero-config build pack that can also interact with proxies, kafka, sockets, synthetic monitors.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
//! cargo-dist integration for `xbp version release`.
//!
//! Discovers `dist-workspace.toml` / package dist metadata, runs `dist build`,
//! collects artifacts under `target/distrib`, and uploads them to the GitHub
//! release. Steps are ledger-friendly: partial uploads resume by asset name.

use semver::Version;
use serde::Deserialize;
use serde_json::Value as JsonValue;
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::strategies::PublishProjectConfig;
use crate::utils::{canonicalize_for_subprocess, command_exists};

use super::adapters::{
    cargo_package_name_from_content_optional, parse_version, read_cargo_toml_version_from_content,
};
use super::VersionScope;

/// Working directory for `dist` / cargo-dist subprocesses.
///
/// cargo-dist fails to find `Cargo.toml` on Windows when the shell cwd uses
/// non-canonical casing; always run it from the filesystem-canonical path.
fn dist_working_dir(project_root: &Path) -> PathBuf {
    canonicalize_for_subprocess(project_root)
}

/// Default dist binary names to probe (`dist` is the modern cargo-dist CLI).
const DIST_TOOL_CANDIDATES: &[&str] = &["dist", "cargo-dist"];

#[derive(Debug, Clone)]
pub(crate) struct CargoDistReleasePlan {
    pub(crate) enabled: bool,
    pub(crate) reason: String,
    pub(crate) tool: String,
    /// GitHub release / git tag (may be an XBP scoped tag like `crates-cli-10.38.2`).
    pub(crate) tag_name: String,
    /// Tag passed to `dist plan` / `dist build --tag`. cargo-dist only accepts
    /// unified (`v1.2.3`) or package-scoped (`xbp-1.2.3`, `xbp/1.2.3`) forms.
    pub(crate) announcement_tag: String,
    pub(crate) installers: Vec<String>,
    pub(crate) targets: Vec<String>,
    pub(crate) artifacts_modes: Vec<String>,
    pub(crate) allow_dirty: bool,
    pub(crate) generate_ci: bool,
    pub(crate) packages: Vec<String>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub(crate) struct CargoDistBuiltArtifact {
    pub(crate) name: String,
    pub(crate) path: PathBuf,
    pub(crate) kind: String,
}

#[derive(Debug, Clone)]
pub(crate) struct CargoDistBuildResult {
    pub(crate) artifacts: Vec<CargoDistBuiltArtifact>,
    pub(crate) announcement_github_body: Option<String>,
    pub(crate) install_methods: Vec<CargoDistInstallMethod>,
    pub(crate) modes_run: Vec<String>,
}

#[derive(Debug, Clone, serde::Serialize)]
pub(crate) struct CargoDistInstallMethod {
    pub(crate) package_name: String,
    pub(crate) title: String,
    pub(crate) command: String,
}

#[derive(Debug, Deserialize)]
struct DistManifest {
    #[serde(default)]
    announcement_github_body: Option<String>,
    #[serde(default)]
    artifacts: BTreeMap<String, DistArtifact>,
}

#[derive(Debug, Deserialize)]
struct DistArtifact {
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    path: Option<String>,
    #[serde(default)]
    kind: Option<String>,
    #[serde(default)]
    description: Option<String>,
    #[serde(default)]
    install_hint: Option<String>,
}

/// Worktree is cargo-dist enabled when config exists or publish.dist is on.
pub(crate) fn project_has_cargo_dist_config(project_root: &Path) -> bool {
    project_root.join("dist-workspace.toml").is_file()
        || project_root.join("dist.toml").is_file()
        || workspace_cargo_has_dist_metadata(project_root)
}

fn workspace_cargo_has_dist_metadata(project_root: &Path) -> bool {
    let cargo_toml = project_root.join("Cargo.toml");
    let Ok(content) = fs::read_to_string(cargo_toml) else {
        return false;
    };
    content.contains("metadata.dist") || content.contains("[workspace.metadata.dist]")
}

/// Inputs for deciding whether cargo-dist should run for a given release.
#[derive(Debug, Clone, Copy)]
pub(crate) struct CargoDistReleaseContext<'a> {
    pub project_root: &'a Path,
    pub publish_config: Option<&'a PublishProjectConfig>,
    pub tag_name: &'a str,
    pub release_version: &'a Version,
    pub version_scope: &'a VersionScope,
    /// Cargo package names from selected crates publish targets (may be empty).
    pub preferred_packages: &'a [String],
    /// When true, skip on-disk version alignment (tests / legacy callers).
    pub skip_version_alignment: bool,
}

fn disabled_dist_plan(tag_name: &str, reason: impl Into<String>) -> CargoDistReleasePlan {
    CargoDistReleasePlan {
        enabled: false,
        reason: reason.into(),
        tool: String::new(),
        tag_name: tag_name.to_string(),
        announcement_tag: tag_name.to_string(),
        installers: Vec::new(),
        targets: Vec::new(),
        artifacts_modes: Vec::new(),
        allow_dirty: true,
        generate_ci: false,
        packages: Vec::new(),
    }
}

/// Cargo package names owned by this version/release scope (Rust only).
///
/// Non-Rust services (npm/docs/JS) return an empty list — cargo-dist must not run.
pub(crate) fn cargo_packages_owned_by_scope(
    project_root: &Path,
    version_scope: &VersionScope,
) -> Vec<String> {
    let mut packages = BTreeSet::new();
    match version_scope {
        VersionScope::Repository => {
            // Repository scope does not imply every dist package; callers must
            // supply crates publish targets or version-aligned configured packages.
        }
        VersionScope::Crate { package_name, crate_root, .. } => {
            if crate_root.join("Cargo.toml").is_file() {
                packages.insert(package_name.clone());
            }
        }
        VersionScope::Service {
            service_root,
            cargo_package_name,
            version_targets,
            ..
        } => {
            if let Some(name) = cargo_package_name
                .as_deref()
                .map(str::trim)
                .filter(|v| !v.is_empty())
            {
                // Only if the service root is actually a Cargo package.
                if service_root.join("Cargo.toml").is_file() {
                    packages.insert(name.to_string());
                }
            }
            // Collect package names from Cargo.toml version targets under this service.
            for relative in version_targets {
                let normalized = relative.replace('\\', "/");
                if !normalized.ends_with("Cargo.toml") && !normalized.ends_with("Cargo.lock") {
                    continue;
                }
                let path = if Path::new(&normalized).is_absolute() {
                    PathBuf::from(&normalized)
                } else {
                    project_root.join(&normalized)
                };
                let cargo_toml = if path
                    .file_name()
                    .and_then(|n| n.to_str())
                    .is_some_and(|n| n.eq_ignore_ascii_case("Cargo.lock"))
                {
                    path.with_file_name("Cargo.toml")
                } else {
                    path
                };
                if let Ok(content) = fs::read_to_string(&cargo_toml) {
                    if let Ok(Some(name)) = cargo_package_name_from_content_optional(&content) {
                        packages.insert(name);
                    }
                }
            }
            // Service root Cargo.toml without explicit cargo_package_name.
            let root_cargo = service_root.join("Cargo.toml");
            if root_cargo.is_file() {
                if let Ok(content) = fs::read_to_string(&root_cargo) {
                    if let Ok(Some(name)) = cargo_package_name_from_content_optional(&content) {
                        packages.insert(name);
                    }
                }
            }
        }
    }
    packages.into_iter().collect()
}

/// Resolve on-disk Cargo package versions for alignment checks.
pub(crate) fn read_cargo_package_versions(
    project_root: &Path,
    package_names: &[String],
) -> BTreeMap<String, Version> {
    let mut out = BTreeMap::new();
    if package_names.is_empty() {
        return out;
    }
    let wanted: BTreeSet<&str> = package_names.iter().map(String::as_str).collect();

    let mut candidates = Vec::new();
    candidates.push(project_root.join("Cargo.toml"));
    let crates_root = project_root.join("crates");
    if let Ok(entries) = fs::read_dir(&crates_root) {
        for entry in entries.flatten() {
            let cargo = entry.path().join("Cargo.toml");
            if cargo.is_file() {
                candidates.push(cargo);
            }
        }
    }

    for cargo_toml in candidates {
        let Ok(content) = fs::read_to_string(&cargo_toml) else {
            continue;
        };
        let Ok(Some(name)) = cargo_package_name_from_content_optional(&content) else {
            continue;
        };
        if !wanted.contains(name.as_str()) {
            continue;
        }
        if let Ok(Some(raw)) = read_cargo_toml_version_from_content(&content) {
            if let Ok(version) = parse_version(&raw) {
                out.insert(name, Version::new(version.major, version.minor, version.patch));
            }
        }
    }
    out
}

/// Compute effective dist package list for this release (empty ⇒ do not run dist).
pub(crate) fn effective_dist_packages_for_release(
    project_root: &Path,
    version_scope: &VersionScope,
    preferred_packages: &[String],
    configured_packages: &[String],
    release_version: &Version,
) -> (Vec<String>, Option<String>) {
    let mut owned: BTreeSet<String> = cargo_packages_owned_by_scope(project_root, version_scope)
        .into_iter()
        .collect();
    for pkg in preferred_packages {
        let pkg = pkg.trim();
        if !pkg.is_empty() {
            owned.insert(pkg.to_string());
        }
    }

    // Repository-wide release with no crates selection: only announce configured
    // packages whose Cargo version already matches the release (safe monorepo path).
    if owned.is_empty() && matches!(version_scope, VersionScope::Repository) {
        let configured: Vec<String> = configured_packages
            .iter()
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .collect();
        if !configured.is_empty() {
            let versions = read_cargo_package_versions(project_root, &configured);
            let release_core = Version::new(
                release_version.major,
                release_version.minor,
                release_version.patch,
            );
            for pkg in &configured {
                if versions.get(pkg).is_some_and(|v| *v == release_core) {
                    owned.insert(pkg.clone());
                }
            }
            if owned.is_empty() {
                return (
                    Vec::new(),
                    Some(
                        "repository release: no configured dist package matches this release version"
                            .to_string(),
                    ),
                );
            }
        }
    }

    if owned.is_empty() {
        return (
            Vec::new(),
            Some(
                "scope does not own a Rust/dist package (cargo-dist only applies to Cargo packages)"
                    .to_string(),
            ),
        );
    }

    let configured: Vec<String> = configured_packages
        .iter()
        .map(|v| v.trim().to_string())
        .filter(|v| !v.is_empty())
        .collect();

    let mut effective: Vec<String> = if configured.is_empty() {
        owned.into_iter().collect()
    } else {
        let configured_set: BTreeSet<String> = configured.into_iter().collect();
        owned
            .into_iter()
            .filter(|pkg| configured_set.contains(pkg))
            .collect()
    };
    effective.sort();
    effective.dedup();

    if effective.is_empty() {
        return (
            Vec::new(),
            Some(
                "owned packages are not in publish.dist.packages (not a dist crate for this release)"
                    .to_string(),
            ),
        );
    }

    // Drop packages whose on-disk version does not match the release (sibling bumps).
    let versions = read_cargo_package_versions(project_root, &effective);
    let release_core = Version::new(
        release_version.major,
        release_version.minor,
        release_version.patch,
    );
    let before = effective.len();
    effective.retain(|pkg| match versions.get(pkg) {
        Some(v) => *v == release_core,
        // Unknown version: keep only if this is a true owning scope package
        // (avoid inventing dist for strangers). Prefer skip when unknown.
        None => false,
    });
    if effective.is_empty() {
        return (
            Vec::new(),
            Some(format!(
                "dist package version does not match release {release_core} (or package not found); skipping cargo-dist"
            )),
        );
    }
    if effective.len() < before {
        // partial retain is fine
    }

    // cargo-dist only packages binaries/cdylibs — pure library crates announce
    // nothing useful and leave `target/distrib` empty (hard-fail before this filter).
    let before_bins = effective.len();
    effective.retain(|pkg| cargo_package_is_distable(project_root, pkg));
    if effective.is_empty() {
        return (
            Vec::new(),
            Some(if before_bins > 0 {
                "selected Rust package(s) are library-only (no [[bin]] / src/main.rs / src/bin); cargo-dist has nothing to package"
                    .to_string()
            } else {
                "no distable (binary) packages for this release".to_string()
            }),
        );
    }

    (effective, None)
}

/// True when a Cargo package can produce cargo-dist binary artifacts.
///
/// Library-only crates still get package-version tags for crates.io, but dist
/// correctly builds an empty artifact set for them — XBP must not treat that as failure.
pub(crate) fn cargo_package_is_distable(project_root: &Path, package_name: &str) -> bool {
    let package_name = package_name.trim();
    if package_name.is_empty() {
        return false;
    }
    let Some(cargo_toml) = find_cargo_toml_for_package(project_root, package_name) else {
        // Unknown path: keep package and let dist decide (legacy / unusual layouts).
        return true;
    };
    cargo_manifest_looks_distable(&cargo_toml)
}

fn find_cargo_toml_for_package(project_root: &Path, package_name: &str) -> Option<PathBuf> {
    let mut candidates = Vec::new();
    candidates.push(project_root.join("Cargo.toml"));
    for sub in ["crates", "packages", "apps", "services", "bins", "bin"] {
        let dir = project_root.join(sub);
        if let Ok(entries) = fs::read_dir(&dir) {
            for entry in entries.flatten() {
                let cargo = entry.path().join("Cargo.toml");
                if cargo.is_file() {
                    candidates.push(cargo);
                }
            }
        }
    }
    // Also accept crates/<name>/Cargo.toml heuristics without scanning everything twice.
    for hyphen_variant in [
        package_name.to_string(),
        package_name.replace('_', "-"),
        package_name.replace('-', "_"),
    ] {
        for sub in ["crates", "packages", "apps", "services"] {
            let cargo = project_root.join(sub).join(&hyphen_variant).join("Cargo.toml");
            if cargo.is_file() {
                candidates.push(cargo);
            }
        }
    }

    for cargo_toml in candidates {
        let Ok(content) = fs::read_to_string(&cargo_toml) else {
            continue;
        };
        let Ok(Some(name)) = cargo_package_name_from_content_optional(&content) else {
            continue;
        };
        if name == package_name
            || name.replace('_', "-") == package_name.replace('_', "-")
        {
            return Some(cargo_toml);
        }
    }
    None
}

fn cargo_manifest_looks_distable(cargo_toml: &Path) -> bool {
    let Ok(content) = fs::read_to_string(cargo_toml) else {
        return true;
    };
    // Explicit [[bin]] targets.
    if content.lines().any(|line| line.trim() == "[[bin]]") {
        return true;
    }
    // cdylib / staticlib can be packaged by some dist setups.
    if content.contains("crate-type")
        && (content.contains("\"cdylib\"")
            || content.contains("'cdylib'")
            || content.contains("\"staticlib\"")
            || content.contains("'staticlib'"))
    {
        return true;
    }
    let package_dir = cargo_toml.parent().unwrap_or(cargo_toml);
    if package_dir.join("src").join("main.rs").is_file() {
        return true;
    }
    let bin_dir = package_dir.join("src").join("bin");
    if bin_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&bin_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.extension().and_then(|e| e.to_str()) == Some("rs") || path.is_dir() {
                    return true;
                }
            }
        }
    }
    false
}

/// Backward-compatible helper: requires explicit preferred crates packages.
/// Prefer [`resolve_cargo_dist_release_plan_for_context`] for real releases.
pub(crate) fn resolve_cargo_dist_release_plan(
    project_root: &Path,
    publish_config: Option<&PublishProjectConfig>,
    tag_name: &str,
    preferred_packages: &[String],
) -> CargoDistReleasePlan {
    let release_version = Version::new(0, 0, 0);
    let scope = VersionScope::Repository;
    // Without a real release version, only honor explicit crates publish packages
    // (never "configured dist packages for the whole monorepo").
    if preferred_packages
        .iter()
        .all(|p| p.trim().is_empty())
    {
        return disabled_dist_plan(
            tag_name,
            "no crates packages selected for cargo-dist",
        );
    }
    resolve_cargo_dist_release_plan_for_context(CargoDistReleaseContext {
        project_root,
        publish_config,
        tag_name,
        release_version: &release_version,
        version_scope: &scope,
        preferred_packages,
        skip_version_alignment: true,
    })
}

pub(crate) fn resolve_cargo_dist_release_plan_for_context(
    ctx: CargoDistReleaseContext<'_>,
) -> CargoDistReleasePlan {
    let dist_cfg = ctx.publish_config.and_then(|publish| publish.dist.as_ref());
    let explicitly_disabled = dist_cfg
        .and_then(|cfg| cfg.enabled)
        .is_some_and(|enabled| !enabled);
    let explicitly_enabled = dist_cfg.and_then(|cfg| cfg.enabled).unwrap_or(false);
    let has_config = project_has_cargo_dist_config(ctx.project_root);
    let tag_name = ctx.tag_name;

    if explicitly_disabled {
        return disabled_dist_plan(tag_name, "publish.dist.enabled is false");
    }

    if !explicitly_enabled && !has_config {
        return disabled_dist_plan(
            tag_name,
            "no dist-workspace.toml / dist config and publish.dist not enabled",
        );
    }

    let configured = dist_cfg
        .map(|cfg| cfg.packages.clone())
        .unwrap_or_default();

    let (mut packages, skip_reason) = if ctx.skip_version_alignment {
        // Prefer intersection of preferred ∩ configured (or preferred if no configured).
        let mut pkgs: Vec<String> = ctx
            .preferred_packages
            .iter()
            .map(|v| v.trim().to_string())
            .filter(|v| !v.is_empty())
            .collect();
        let owned = cargo_packages_owned_by_scope(ctx.project_root, ctx.version_scope);
        for p in owned {
            if !pkgs.iter().any(|x| x == &p) {
                pkgs.push(p);
            }
        }
        if !configured.is_empty() {
            let cfg: BTreeSet<_> = configured
                .iter()
                .map(|v| v.trim().to_string())
                .filter(|v| !v.is_empty())
                .collect();
            pkgs.retain(|p| cfg.contains(p));
        }
        pkgs.sort();
        pkgs.dedup();
        if pkgs.is_empty() {
            (
                Vec::new(),
                Some("no Rust/dist packages for this release scope".to_string()),
            )
        } else {
            (pkgs, None)
        }
    } else {
        effective_dist_packages_for_release(
            ctx.project_root,
            ctx.version_scope,
            ctx.preferred_packages,
            &configured,
            ctx.release_version,
        )
    };

    // Drop pure libraries even when version-alignment was skipped (tests / preferred list).
    if !packages.is_empty() {
        packages.retain(|pkg| cargo_package_is_distable(ctx.project_root, pkg));
    }

    if packages.is_empty() {
        return disabled_dist_plan(
            tag_name,
            skip_reason.unwrap_or_else(|| {
                "scope does not own a distable binary package (library-only crates skip cargo-dist)"
                    .to_string()
            }),
        );
    }

    // Never dist-build a non-Cargo release tag (e.g. athena-js-3.1.1) even if
    // monorepo dist config / sibling crates exist.
    if !release_tag_is_distable(tag_name, &packages) {
        return disabled_dist_plan(
            tag_name,
            format!(
                "release tag `{tag_name}` is not a cargo-dist package tag (packages: {}); skipping dist for non-Rust scope",
                packages.join(", ")
            ),
        );
    }

    let tool = dist_cfg
        .and_then(|cfg| cfg.tool.as_deref())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(str::to_string)
        .or_else(find_dist_tool)
        .unwrap_or_default();

    if tool.is_empty() {
        return disabled_dist_plan(
            tag_name,
            "cargo-dist CLI not found (install with `cargo install cargo-dist`)",
        );
    }

    let installers = dist_cfg
        .map(|cfg| cfg.installers.clone())
        .filter(|values| !values.is_empty())
        // shell = curl|sh on Unix; msi = double-click Windows installer (not .ps1).
        .unwrap_or_else(|| vec!["shell".to_string(), "msi".to_string()]);
    let targets = dist_cfg.map(|cfg| cfg.targets.clone()).unwrap_or_default();
    let artifacts_modes = dist_cfg
        .map(|cfg| cfg.artifacts_modes.clone())
        .filter(|values| !values.is_empty())
        .unwrap_or_else(|| vec!["host".to_string(), "global".to_string()]);
    let allow_dirty = dist_cfg.and_then(|cfg| cfg.allow_dirty).unwrap_or(true);
    let generate_ci = dist_cfg.and_then(|cfg| cfg.generate_ci).unwrap_or(true);
    let announcement_tag = cargo_dist_announcement_tag(tag_name, &packages);

    // After rewrite, announcement must still name a real dist package or unified version.
    if !release_tag_is_distable(&announcement_tag, &packages) {
        return disabled_dist_plan(
            tag_name,
            format!(
                "announcement tag `{announcement_tag}` does not match dist packages ({}); not a Rust release",
                packages.join(", ")
            ),
        );
    }

    CargoDistReleasePlan {
        enabled: true,
        reason: if has_config {
            format!("dist packages for this scope: {}", packages.join(", "))
        } else {
            format!("publish.dist.enabled; packages: {}", packages.join(", "))
        },
        tool,
        tag_name: tag_name.to_string(),
        announcement_tag,
        installers,
        targets,
        artifacts_modes,
        allow_dirty,
        generate_ci,
        packages,
    }
}

/// Whether a git/announcement tag can be used with cargo-dist for `packages`.
///
/// Accepts unified `v1.2.3` / `1.2.3`, or singular `pkg-1.2.3` / `pkg/1.2.3` when
/// `pkg` is in `packages`. Rejects foreign tags like `athena-js-3.1.1` when packages
/// are only Rust crates (`athena_rs`, `athena-billing`, …).
pub(crate) fn release_tag_is_distable(tag: &str, packages: &[String]) -> bool {
    let tag = tag.trim();
    if tag.is_empty() || packages.is_empty() {
        return false;
    }
    if Version::parse(tag).is_ok() {
        return true;
    }
    if let Some(rest) = tag.strip_prefix('v') {
        if Version::parse(rest).is_ok() {
            return true;
        }
    }
    for package in packages {
        let package = package.trim();
        if package.is_empty() {
            continue;
        }
        for sep in ['-', '/'] {
            if let Some(rest) = tag.strip_prefix(package).and_then(|r| r.strip_prefix(sep)) {
                let rest = rest.strip_prefix('v').unwrap_or(rest);
                if Version::parse(rest).is_ok() {
                    return true;
                }
                // Allow pre-release / build metadata tails cargo-dist may accept.
                if let Some((core, _)) = rest.split_once('+') {
                    if Version::parse(core).is_ok() {
                        return true;
                    }
                }
                if let Some((core, _)) = rest.split_once('-') {
                    if Version::parse(core).is_ok() {
                        return true;
                    }
                }
            }
        }
    }
    false
}

/// True when a dist error should soft-skip instead of failing the whole release.
pub(crate) fn cargo_dist_error_is_non_applicable(error: &str) -> bool {
    let lower = error.to_ascii_lowercase();
    // Collapse whitespace so multi-line JSON help still matches.
    let compact = lower
        .chars()
        .filter(|c| !c.is_whitespace())
        .collect::<String>();
    lower.contains("doesn't have anything for dist to release")
        || lower.contains("does not have anything for dist to release")
        || compact.contains("doesn'thaveanythingfordisttorelease")
        || compact.contains("doesnothaveanythingfordisttorelease")
        || lower.contains("produced no uploadable artifacts")
        || lower.contains("no uploadable artifacts")
        || lower.contains("library-only")
        || lower.contains("claims we're releasing")
        || lower.contains("but that package is version")
        || lower.contains("you may need to pass the current version as --tag")
        || lower.contains("will announce:")
        // Repository URL is required for GH CI metadata; release can continue without dist
        // when heal failed (virtual workspace edge cases / no origin).
        || lower.contains("requires you to specify the url of your repository")
        || lower.contains("cargo-dist requires a repository url")
        || compact.contains("githubcisupportrequiresyou")
}

/// Map an XBP git/GitHub release tag onto a cargo-dist announcement tag.
///
/// cargo-dist accepts:
/// - unified: `v1.2.3`, `1.2.3`, `releases/1.2.3`
/// - singular: `pkg-v1.2.3`, `pkg-1.2.3`, `pkg/1.2.3`
///
/// Service-scope tags like `crates-cli-10.38.2` are not parseable (package is
/// not a Cargo package name), so we rewrite to `xbp-10.38.2` or `v10.38.2`.
pub(crate) fn cargo_dist_announcement_tag(github_tag: &str, packages: &[String]) -> String {
    let tag = github_tag.trim();
    if tag.is_empty() {
        return tag.to_string();
    }
    if announcement_tag_is_cargo_dist_compatible(tag, packages) {
        return tag.to_string();
    }
    let Some(version) = extract_semver_core_from_tag(tag) else {
        // Last resort: force a v-prefix so dist at least gets a version-shaped tag.
        if tag.starts_with('v') {
            return tag.to_string();
        }
        return format!("v{tag}");
    };
    if packages.len() == 1 {
        let package = packages[0].trim();
        if !package.is_empty() {
            return format!("{package}-{version}");
        }
    }
    format!("v{version}")
}

fn announcement_tag_is_cargo_dist_compatible(tag: &str, packages: &[String]) -> bool {
    if Version::parse(tag).is_ok() {
        return true;
    }
    if let Some(rest) = tag.strip_prefix('v') {
        if Version::parse(rest).is_ok() {
            return true;
        }
    }
    // Path-style unified: `releases/1.2.3` or nested `a/b/1.2.3`.
    if let Some(last) = tag.rsplit('/').next() {
        let last = last.strip_prefix('v').unwrap_or(last);
        if tag.contains('/') && Version::parse(last).is_ok() {
            return true;
        }
    }
    // Singular: package must be a real Cargo package we are shipping.
    for package in packages {
        let package = package.trim();
        if package.is_empty() {
            continue;
        }
        for sep in ['-', '/'] {
            if let Some(rest) = tag.strip_prefix(package).and_then(|r| r.strip_prefix(sep)) {
                let rest = rest.strip_prefix('v').unwrap_or(rest);
                if Version::parse(rest).is_ok() {
                    return true;
                }
            }
        }
    }
    false
}

fn extract_semver_core_from_tag(tag: &str) -> Option<String> {
    let tag = tag.trim();
    if let Ok(version) = Version::parse(tag) {
        return Some(version.to_string());
    }
    if let Some(rest) = tag.strip_prefix('v') {
        if let Ok(version) = Version::parse(rest) {
            return Some(version.to_string());
        }
    }
    if let Some(last) = tag.rsplit('/').next() {
        let last = last.strip_prefix('v').unwrap_or(last);
        if let Ok(version) = Version::parse(last) {
            return Some(version.to_string());
        }
    }
    // Scoped XBP tags: `{slug}-{semver}`, `{slug}-{semver}+{flag}`, `{slug}-{semver}+{flag}.{n}`.
    // Walk from the first digit so `crates-cli-10.38.2` → `10.38.2`.
    let digit_idx = tag.find(|ch: char| ch.is_ascii_digit())?;
    let rest = &tag[digit_idx..];
    if let Ok(version) = Version::parse(rest) {
        return Some(release_version_core_string(&version));
    }
    // Preferred build metadata: `10.38.2+nightly` / `10.38.2+nightly.3`.
    if let Some((core, _)) = rest.split_once('+') {
        if let Ok(version) = Version::parse(core) {
            return Some(release_version_core_string(&version));
        }
    }
    // Legacy hyphen flag: `10.38.2-nightly`.
    if let Some((core, _flag)) = rest.rsplit_once('-') {
        if let Ok(version) = Version::parse(core) {
            return Some(release_version_core_string(&version));
        }
    }
    None
}

fn release_version_core_string(version: &Version) -> String {
    format!("{}.{}.{}", version.major, version.minor, version.patch)
}

/// cargo-dist embeds `--tag` into GitHub download URLs. When we normalize the
/// announcement tag for parsing, rewrite those URLs back to the real release tag.
pub(crate) fn align_dist_body_to_github_tag(
    body: &str,
    announcement_tag: &str,
    github_tag: &str,
) -> String {
    if announcement_tag == github_tag || announcement_tag.is_empty() || github_tag.is_empty() {
        return body.to_string();
    }
    body.replace(
        &format!("/releases/download/{announcement_tag}/"),
        &format!("/releases/download/{github_tag}/"),
    )
}

fn find_dist_tool() -> Option<String> {
    DIST_TOOL_CANDIDATES
        .iter()
        .find(|name| command_exists(name))
        .map(|name| (*name).to_string())
}

/// Detect `[[bin]]` targets that use `required-features` (cargo-dist packaging trap).
///
/// Returns `None` when safe; otherwise a human-readable error for the release ledger.
pub(crate) fn preflight_feature_gated_bins(project_root: &Path) -> Option<String> {
    let cargo_toml = project_root.join("Cargo.toml");
    let content = fs::read_to_string(&cargo_toml).ok()?;
    let mut gated: Vec<String> = Vec::new();
    let mut current_bin: Option<String> = None;
    let mut in_bin = false;

    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed == "[[bin]]" {
            in_bin = true;
            current_bin = None;
            continue;
        }
        if trimmed.starts_with('[') {
            in_bin = false;
            current_bin = None;
            continue;
        }
        if !in_bin {
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("name") {
            let value = rest
                .trim()
                .trim_start_matches('=')
                .trim()
                .trim_matches('"')
                .trim_matches('\'')
                .to_string();
            if !value.is_empty() {
                current_bin = Some(value);
            }
        }
        if trimmed.starts_with("required-features") {
            if let Some(name) = current_bin.take() {
                gated.push(name);
            } else {
                gated.push("<unnamed-bin>".to_string());
            }
        }
    }

    if gated.is_empty() {
        return None;
    }

    Some(format!(
        "cargo-dist cannot reliably package feature-gated binaries: {}. \
Move them to `[[example]]` (or drop `required-features` on the bin), commit on the \
branch used for release (including `releases/…`), then re-run. \
Host builds otherwise fail with \"failed to find bin <name>.exe\".",
        gated.join(", ")
    ))
}

/// Ensure a minimal dist-workspace.toml exists when publish.dist is enabled without one.
pub(crate) fn ensure_dist_workspace_config(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
) -> Result<Option<PathBuf>, String> {
    let path = project_root.join("dist-workspace.toml");
    if path.is_file() {
        return Ok(None);
    }
    if !plan.enabled {
        return Ok(None);
    }

    let installers = if plan.installers.is_empty() {
        r#"["shell", "msi"]"#.to_string()
    } else {
        let items = plan
            .installers
            .iter()
            .map(|value| format!("\"{}\"", value.replace('"', "\\\"")))
            .collect::<Vec<_>>()
            .join(", ");
        format!("[{items}]")
    };

    let targets = if plan.targets.is_empty() {
        r#"[
    "aarch64-apple-darwin",
    "x86_64-apple-darwin",
    "x86_64-unknown-linux-gnu",
    "x86_64-unknown-linux-musl",
    "aarch64-unknown-linux-gnu",
    "x86_64-pc-windows-msvc",
]"#
        .to_string()
    } else {
        let items = plan
            .targets
            .iter()
            .map(|value| format!("    \"{}\"", value.replace('"', "\\\"")))
            .collect::<Vec<_>>()
            .join(",\n");
        format!("[\n{items}\n]")
    };

    let content = format!(
        r#"[workspace]
members = ["cargo:."]

[dist]
cargo-dist-version = "0.32.0"
ci = "github"
installers = {installers}
targets = {targets}
hosting = "github"
create-release = false
install-updater = false
pr-run-mode = "plan"
install-path = "CARGO_HOME"
"#
    );
    fs::write(&path, content).map_err(|error| {
        format!(
            "Failed to write default dist-workspace.toml at {}: {}",
            path.display(),
            error
        )
    })?;
    Ok(Some(path))
}

/// Best-effort: ensure root Cargo.toml has a `repository` URL for cargo-dist.
/// Returns the path written when a heal was applied.
pub(crate) fn ensure_cargo_repository_from_git(
    project_root: &Path,
) -> Result<Option<PathBuf>, String> {
    if cargo_manifest_has_repository(project_root) {
        return Ok(None);
    }
    let Some(url) = git_origin_https_url(project_root) else {
        return Ok(None);
    };
    ensure_cargo_repository_field(project_root, &url)
}

pub(crate) fn cargo_manifest_has_repository(project_root: &Path) -> bool {
    let path = project_root.join("Cargo.toml");
    let Ok(content) = fs::read_to_string(path) else {
        return false;
    };
    cargo_toml_content_has_repository(&content)
}

pub(crate) fn cargo_toml_content_has_repository(content: &str) -> bool {
    // package.repository or workspace.package.repository
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.starts_with('#') {
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("repository") {
            let rest = rest.trim_start();
            if rest.starts_with('=') {
                let val = rest.trim_start_matches('=').trim();
                if val.len() > 2 {
                    return true;
                }
            }
        }
    }
    false
}

pub(crate) fn git_origin_https_url(project_root: &Path) -> Option<String> {
    let raw = super::git_ops::git_remote_url(project_root, "origin").ok()?;
    normalize_github_https_url(&raw)
}

pub(crate) fn normalize_github_https_url(raw: &str) -> Option<String> {
    let raw = raw.trim();
    if raw.is_empty() {
        return None;
    }
    if let Some((owner, repo)) = crate::utils::parse_github_repo_from_remote_url(raw) {
        return Some(format!("https://github.com/{owner}/{repo}"));
    }
    if raw.starts_with("https://") || raw.starts_with("http://") {
        return Some(raw.trim_end_matches(".git").to_string());
    }
    None
}

/// Insert `repository = "…"` into `[package]` or `[workspace.package]` if missing.
pub(crate) fn ensure_cargo_repository_field(
    project_root: &Path,
    url: &str,
) -> Result<Option<PathBuf>, String> {
    let path = project_root.join("Cargo.toml");
    let content = fs::read_to_string(&path).map_err(|e| {
        format!(
            "Failed to read {}: {e}",
            path.display()
        )
    })?;
    if cargo_toml_content_has_repository(&content) {
        return Ok(None);
    }
    let Some(updated) = insert_repository_into_cargo_toml(&content, url) else {
        return Ok(None);
    };
    fs::write(&path, updated).map_err(|e| {
        format!(
            "Failed to write repository into {}: {e}",
            path.display()
        )
    })?;
    Ok(Some(path))
}

pub(crate) fn insert_repository_into_cargo_toml(content: &str, url: &str) -> Option<String> {
    if cargo_toml_content_has_repository(content) {
        return None;
    }
    let escaped = url.replace('\\', "\\\\").replace('"', "\\\"");
    let line = format!("repository = \"{escaped}\"\n");

    // Prefer [workspace.package] for virtual workspaces, else [package].
    if let Some(idx) = find_toml_table_header(content, "workspace.package") {
        return Some(insert_after_table_header(content, idx, &line));
    }
    if let Some(idx) = find_toml_table_header(content, "package") {
        // Only use root [package] if it is not a workspace-virtual layout.
        // Virtual workspaces have [workspace] and usually no real root package.
        if !is_virtual_workspace_manifest(content) {
            return Some(insert_after_table_header(content, idx, &line));
        }
    }
    if is_virtual_workspace_manifest(content) {
        // Create [workspace.package] after [workspace] header block.
        if let Some(idx) = find_toml_table_header(content, "workspace") {
            let insert_at = end_of_toml_table(content, idx);
            let mut out = String::with_capacity(content.len() + line.len() + 32);
            out.push_str(&content[..insert_at]);
            if !out.ends_with('\n') {
                out.push('\n');
            }
            out.push_str("\n[workspace.package]\n");
            out.push_str(&line);
            out.push_str(&content[insert_at..]);
            return Some(out);
        }
    }
    // Append a package table as last resort.
    let mut out = content.to_string();
    if !out.ends_with('\n') {
        out.push('\n');
    }
    out.push_str("\n[package]\n");
    out.push_str(&line);
    Some(out)
}

fn is_virtual_workspace_manifest(content: &str) -> bool {
    let has_workspace = find_toml_table_header(content, "workspace").is_some();
    if !has_workspace {
        return false;
    }
    // Virtual workspaces typically have members/exclude and no [package] name at root,
    // or [package] only as workspace inheritance stub. Treat presence of workspace.members
    // without a real package section as virtual.
    let has_members = content.contains("members")
        && (content.contains("members =") || content.contains("members="));
    let has_package = find_toml_table_header(content, "package").is_some();
    has_members && !has_package
}

/// Byte index just after the end of the table that starts at `header_idx`.
fn end_of_toml_table(content: &str, header_idx: usize) -> usize {
    let rest = &content[header_idx..];
    let mut offset = rest.find('\n').map(|n| n + 1).unwrap_or(rest.len());
    while offset < rest.len() {
        let line_start = offset;
        let line_end = rest[line_start..]
            .find('\n')
            .map(|n| line_start + n + 1)
            .unwrap_or(rest.len());
        let line = rest[line_start..line_end].trim();
        if line.starts_with('[') && !line.starts_with("[[") {
            // Next table begins here.
            return header_idx + line_start;
        }
        offset = line_end;
    }
    content.len()
}

fn find_toml_table_header(content: &str, table: &str) -> Option<usize> {
    let needle = format!("[{table}]");
    content.find(&needle)
}

fn insert_after_table_header(content: &str, header_idx: usize, line: &str) -> String {
    let after_header = content[header_idx..]
        .find('\n')
        .map(|n| header_idx + n + 1)
        .unwrap_or(content.len());
    let mut out = String::with_capacity(content.len() + line.len());
    out.push_str(&content[..after_header]);
    out.push_str(line);
    out.push_str(&content[after_header..]);
    out
}

pub(crate) fn run_cargo_dist_generate_ci(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
) -> Result<(), String> {
    if !plan.enabled || !plan.generate_ci {
        return Ok(());
    }
    if !cargo_manifest_has_repository(project_root) {
        return Err(
            "cargo-dist CI generate skipped: Cargo.toml has no repository URL (set package.repository or workspace.package.repository)"
                .to_string(),
        );
    }
    let working_dir = dist_working_dir(project_root);
    let mut command = Command::new(&plan.tool);
    command.current_dir(&working_dir);
    command.args(["generate", "--mode", "ci"]);
    if plan.allow_dirty {
        command.arg("--allow-dirty");
    }
    for installer in &plan.installers {
        command.arg("--installer").arg(installer);
    }
    let output = command
        .output()
        .map_err(|error| format!("Failed to run `{} generate`: {}", plan.tool, error))?;
    if output.status.success() {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&output.stderr);
    let stdout = String::from_utf8_lossy(&output.stdout);
    let combined = format!("{}\n{}", stdout.trim(), stderr.trim());
    // generate may fail if CI already exists and is dirty; treat as soft error when allow_dirty.
    if plan.allow_dirty
        && (combined.contains("out of date")
            || combined.contains("already exists")
            || combined.contains("dirty"))
    {
        return Ok(());
    }
    let human = format_cargo_dist_error(&combined);
    Err(format!(
        "`{} generate --mode ci` failed: {}",
        plan.tool, human
    ))
}

/// Run `dist plan` (no builds) to obtain announcement install markdown + artifact names.
pub(crate) fn run_cargo_dist_plan_manifest(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
) -> Result<(Option<String>, Vec<CargoDistInstallMethod>), String> {
    if !plan.enabled {
        return Ok((None, Vec::new()));
    }
    let working_dir = dist_working_dir(project_root);
    let mut command = Command::new(&plan.tool);
    command.current_dir(&working_dir);
    command.args(["plan", "-o", "json"]);
    command.arg("--tag").arg(&plan.announcement_tag);
    if plan.allow_dirty {
        command.arg("--allow-dirty");
    }
    for installer in &plan.installers {
        command.arg("--installer").arg(installer);
    }
    for target in &plan.targets {
        command.arg("--target").arg(target);
    }
    let output = command
        .output()
        .map_err(|error| format!("Failed to run `{} plan`: {}", plan.tool, error))?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() {
        let combined = format!("{}\n{}", stdout.trim(), stderr.trim());
        let human = format_cargo_dist_error(&combined);
        return Err(format!("`{} plan` failed: {}", plan.tool, human));
    }
    let manifest = parse_dist_manifest_json(stdout.trim()).or_else(|_| {
        stdout
            .find('{')
            .map(|idx| parse_dist_manifest_json(&stdout[idx..]))
            .transpose()
            .map_err(|error| error.to_string())?
            .ok_or_else(|| "cargo-dist plan produced no JSON object".to_string())
    })?;
    let body = manifest
        .announcement_github_body
        .as_ref()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
        .map(|value| {
            align_dist_body_to_github_tag(&value, &plan.announcement_tag, &plan.tag_name)
        });
    let mut methods = install_methods_from_manifest(&manifest, plan);
    if !plan.packages.is_empty() {
        methods.retain(|method| {
            plan.packages.iter().any(|package| {
                method.package_name == *package
                    || method.package_name.replace('_', "-") == package.replace('_', "-")
            })
        });
    }
    Ok((body, methods))
}

#[derive(Debug, Clone)]
pub(crate) struct DistModeTiming {
    pub mode: String,
    pub elapsed: std::time::Duration,
    pub artifact_count: usize,
    pub ok: bool,
}

pub(crate) enum DistProgressEvent {
    Start {
        mode: String,
        index: usize,
        total: usize,
        targets_hint: String,
    },
    Finish {
        mode: String,
        elapsed: std::time::Duration,
        artifact_count: usize,
    },
    Fail {
        mode: String,
        elapsed: std::time::Duration,
        message: String,
    },
}

pub(crate) fn dist_build_modes(plan: &CargoDistReleasePlan) -> Vec<String> {
    plan.artifacts_modes
        .iter()
        .map(|m| m.trim().to_string())
        .filter(|m| !m.is_empty())
        .collect()
}

pub(crate) fn run_cargo_dist_build(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
) -> Result<CargoDistBuildResult, String> {
    run_cargo_dist_build_with_progress(project_root, plan, &mut |_| {}).map(|(result, _)| result)
}

pub(crate) fn run_cargo_dist_build_with_progress(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
    on_event: &mut dyn FnMut(DistProgressEvent),
) -> Result<(CargoDistBuildResult, Vec<DistModeTiming>), String> {
    if !plan.enabled {
        return Ok((
            CargoDistBuildResult {
                artifacts: Vec::new(),
                announcement_github_body: None,
                install_methods: Vec::new(),
                modes_run: Vec::new(),
            },
            Vec::new(),
        ));
    }

    // cargo-dist requires package/workspace repository for GitHub CI metadata.
    // Heal before any build so host/global do not hard-fail mid-release.
    if let Ok(Some(path)) = ensure_cargo_repository_from_git(project_root) {
        eprintln!(
            "  {} Set Cargo.toml repository from git origin ({})",
            "✓",
            path.display()
        );
    }
    if !cargo_manifest_has_repository(project_root) {
        let hint = git_origin_https_url(project_root)
            .map(|u| format!("Add to Cargo.toml: repository = \"{u}\""))
            .unwrap_or_else(|| {
                "Set package.repository or workspace.package.repository in Cargo.toml".to_string()
            });
        return Err(format!(
            "cargo-dist requires a repository URL in Cargo.toml. {hint}"
        ));
    }

    // Feature-gated [[bin]] targets are listed by cargo-dist but often not built into
    // host artifacts → "failed to find bin foo.exe". Fail early with a fix hint.
    if let Some(warning) = preflight_feature_gated_bins(project_root) {
        return Err(warning);
    }

    let mut all_artifacts: BTreeMap<String, CargoDistBuiltArtifact> = BTreeMap::new();
    let mut announcement_github_body = None;
    let mut install_methods = Vec::new();
    let mut modes_run = Vec::new();
    let mut timings = Vec::new();
    let modes = dist_build_modes(plan);
    let total = modes.len();

    for (index, mode) in modes.iter().enumerate() {
        let mode = mode.as_str();
        modes_run.push(mode.to_string());
        let targets_hint = if mode != "host" && !plan.targets.is_empty() {
            format!("{} target(s)", plan.targets.len())
        } else {
            String::new()
        };
        on_event(DistProgressEvent::Start {
            mode: mode.to_string(),
            index,
            total,
            targets_hint,
        });
        let started = std::time::Instant::now();
        let manifest = match run_dist_build_mode(project_root, plan, mode) {
            Ok(m) => m,
            Err(error) => {
                let human = format_cargo_dist_error(&error);
                let elapsed = started.elapsed();
                on_event(DistProgressEvent::Fail {
                    mode: mode.to_string(),
                    elapsed,
                    message: human.clone(),
                });
                timings.push(DistModeTiming {
                    mode: mode.to_string(),
                    elapsed,
                    artifact_count: 0,
                    ok: false,
                });
                return Err(human);
            }
        };
        let before = all_artifacts.len();
        if announcement_github_body.is_none() {
            announcement_github_body = manifest
                .announcement_github_body
                .as_ref()
                .map(|value| value.trim().to_string())
                .filter(|value| !value.is_empty())
                .map(|value| {
                    align_dist_body_to_github_tag(&value, &plan.announcement_tag, &plan.tag_name)
                });
        }
        for method in install_methods_from_manifest(&manifest, plan) {
            if !install_methods.iter().any(|existing: &CargoDistInstallMethod| {
                existing.package_name == method.package_name && existing.title == method.title
            }) {
                install_methods.push(method);
            }
        }
        for (key, artifact) in manifest.artifacts {
            let Some(path_str) = artifact.path.as_deref().map(str::trim).filter(|v| !v.is_empty())
            else {
                continue;
            };
            let path = PathBuf::from(path_str);
            if !path.is_file() {
                // Build may have planned paths not produced for this mode/host.
                continue;
            }
            let name = artifact
                .name
                .as_deref()
                .map(str::trim)
                .filter(|value| !value.is_empty())
                .unwrap_or(key.as_str())
                .to_string();
            all_artifacts.insert(
                name.clone(),
                CargoDistBuiltArtifact {
                    name,
                    path,
                    kind: artifact
                        .kind
                        .unwrap_or_else(|| "artifact".to_string())
                        .trim()
                        .to_string(),
                },
            );
        }
        let artifact_count = all_artifacts.len().saturating_sub(before);
        let elapsed = started.elapsed();
        on_event(DistProgressEvent::Finish {
            mode: mode.to_string(),
            elapsed,
            artifact_count,
        });
        timings.push(DistModeTiming {
            mode: mode.to_string(),
            elapsed,
            artifact_count,
            ok: true,
        });
    }

    // Fallback: scan target/distrib for any files dist wrote that JSON skipped.
    let distrib_dir = project_root.join("target").join("distrib");
    if distrib_dir.is_dir() {
        if let Ok(entries) = fs::read_dir(&distrib_dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if !path.is_file() {
                    continue;
                }
                let Some(name) = path.file_name().and_then(|value| value.to_str()) else {
                    continue;
                };
                all_artifacts
                    .entry(name.to_string())
                    .or_insert_with(|| CargoDistBuiltArtifact {
                        name: name.to_string(),
                        path: path.clone(),
                        kind: "artifact".to_string(),
                    });
            }
        }
    }

    if !plan.packages.is_empty() {
        install_methods.retain(|method| {
            plan.packages.iter().any(|package| {
                method.package_name == *package
                    || method.package_name.replace('_', "-") == package.replace('_', "-")
            })
        });
        // Keep only artifacts that clearly belong to selected packages (or shared checksums/sources).
        all_artifacts.retain(|name, artifact| {
            if matches!(
                artifact.kind.as_str(),
                "checksum" | "unified-checksum" | "source-tarball"
            ) {
                return true;
            }
            plan.packages.iter().any(|package| {
                name == package
                    || name.starts_with(&format!("{package}-"))
                    || name.starts_with(&format!("{package}_"))
                    || name.replace('_', "-").starts_with(&format!(
                        "{}-",
                        package.replace('_', "-")
                    ))
            })
        });
    }

    // Library-only tags (e.g. athena-scheduler-4.0.3): dist exits 0 with an empty
    // artifact set. Soft-return empty so the release continues without Discord failure.
    if all_artifacts.is_empty() {
        return Ok((
            CargoDistBuildResult {
                artifacts: Vec::new(),
                announcement_github_body,
                install_methods,
                modes_run,
            },
            timings,
        ));
    }

    Ok((
        CargoDistBuildResult {
            artifacts: all_artifacts.into_values().collect(),
            announcement_github_body,
            install_methods,
            modes_run,
        },
        timings,
    ))
}

/// Humanize cargo-dist JSON diagnostics for TTY (never dump raw JSON).
pub(crate) fn format_cargo_dist_error(raw: &str) -> String {
    let trimmed = raw.trim();
    // Prefer any JSON object with diagnostic.message (may be embedded mid-string).
    if trimmed.find('{').is_some() {
        // Try parse from each `{` in case of prefix text.
        for (idx, _) in trimmed.match_indices('{') {
            let slice = &trimmed[idx..];
            // Truncate to balanced-ish JSON: take until last `}`
            let end = slice.rfind('}').map(|e| e + 1).unwrap_or(slice.len());
            let candidate = &slice[..end];
            if let Ok(value) = serde_json::from_str::<JsonValue>(candidate) {
                if let Some(message) = value
                    .pointer("/diagnostic/message")
                    .and_then(JsonValue::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                {
                    let help = value
                        .pointer("/diagnostic/help")
                        .and_then(JsonValue::as_str)
                        .map(str::trim)
                        .filter(|s| !s.is_empty());
                    return match help {
                        Some(h) => {
                            let hint = h
                                .lines()
                                .map(str::trim)
                                .filter(|l| !l.is_empty())
                                .take(3)
                                .collect::<Vec<_>>()
                                .join(" ");
                            format!("{message}\n  hint: {hint}")
                        }
                        None => message.to_string(),
                    };
                }
                if let Some(message) = value
                    .get("message")
                    .and_then(JsonValue::as_str)
                    .map(str::trim)
                    .filter(|s| !s.is_empty())
                {
                    return message.to_string();
                }
            }
        }
    }
    // Strip any JSON object spans and keep short non-json text.
    let mut without_json = String::new();
    let mut rest = trimmed;
    while let Some(start) = rest.find('{') {
        without_json.push_str(&rest[..start]);
        if let Some(end_rel) = rest[start..].rfind('}') {
            rest = &rest[start + end_rel + 1..];
        } else {
            rest = "";
            break;
        }
    }
    without_json.push_str(rest);
    let mut lines: Vec<&str> = without_json
        .lines()
        .map(str::trim)
        .filter(|l| !l.is_empty())
        .filter(|l| !l.starts_with('{') && !l.starts_with('['))
        .collect();
    if lines.is_empty() {
        let first = trimmed.lines().next().unwrap_or(trimmed);
        if first.len() > 200 {
            return format!("{}…", &first[..200]);
        }
        return first
            .chars()
            .filter(|c| *c != '{' && *c != '}')
            .collect::<String>()
            .trim()
            .to_string();
    }
    lines.truncate(6);
    lines.join("\n")
}

fn run_dist_build_mode(
    project_root: &Path,
    plan: &CargoDistReleasePlan,
    mode: &str,
) -> Result<DistManifest, String> {
    let working_dir = dist_working_dir(project_root);
    let mut command = Command::new(&plan.tool);
    command.current_dir(&working_dir);
    command.args(["build", "-o", "json", "--artifacts", mode]);
    command.arg("--tag").arg(&plan.announcement_tag);
    if plan.allow_dirty {
        command.arg("--allow-dirty");
    }
    for installer in &plan.installers {
        command.arg("--installer").arg(installer);
    }
    // Only pass explicit targets for non-host modes; host mode picks the local triple.
    if mode != "host" {
        for target in &plan.targets {
            command.arg("--target").arg(target);
        }
    }

    let output = command.output().map_err(|error| {
        format!(
            "Failed to run `{} build --artifacts={}`: {}",
            plan.tool, mode, error
        )
    })?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    if !output.status.success() {
        let combined = format!("{}\n{}", stdout.trim(), stderr.trim());
        let human = format_cargo_dist_error(&combined);
        return Err(format!(
            "`{} build --artifacts={}` failed: {}",
            plan.tool, mode, human
        ));
    }

    parse_dist_manifest_json(&stdout).or_else(|parse_error| {
        // Some dist versions print human logs before JSON.
        if let Some(json_start) = stdout.find('{') {
            parse_dist_manifest_json(&stdout[json_start..]).map_err(|inner| {
                format!(
                    "Failed to parse cargo-dist build JSON for mode `{mode}`: {inner} (after human prefix). stderr: {}",
                    stderr.trim()
                )
            })
        } else {
            Err(format!(
                "Failed to parse cargo-dist build JSON for mode `{mode}`: {parse_error}. stderr: {}",
                stderr.trim()
            ))
        }
    })
}

fn parse_dist_manifest_json(raw: &str) -> Result<DistManifest, String> {
    let trimmed = raw.trim().trim_start_matches('\u{feff}');
    serde_json::from_str(trimmed).map_err(|error| error.to_string())
}

fn install_methods_from_manifest(
    manifest: &DistManifest,
    plan: &CargoDistReleasePlan,
) -> Vec<CargoDistInstallMethod> {
    let mut methods = Vec::new();
    for artifact in manifest.artifacts.values() {
        if artifact.kind.as_deref() != Some("installer") {
            continue;
        }
        let Some(hint) = artifact
            .install_hint
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        else {
            continue;
        };
        let title = artifact
            .description
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .unwrap_or("Install prebuilt binaries")
            .to_string();
        let package_name = installer_package_name(artifact.name.as_deref());
        methods.push(CargoDistInstallMethod {
            package_name,
            title,
            command: align_dist_body_to_github_tag(
                hint,
                &plan.announcement_tag,
                &plan.tag_name,
            ),
        });
    }
    methods
}

/// Best-effort package name from a cargo-dist installer artifact filename.
fn installer_package_name(name: Option<&str>) -> String {
    let Some(name) = name.map(str::trim).filter(|value| !value.is_empty()) else {
        return "package".to_string();
    };
    for suffix in [
        "-installer.sh",
        "-installer.ps1",
        "-x86_64-pc-windows-msvc.msi",
        "-aarch64-pc-windows-msvc.msi",
        ".msi",
    ] {
        if let Some(package) = name.strip_suffix(suffix) {
            if !package.is_empty() {
                return package.to_string();
            }
        }
    }
    "package".to_string()
}

/// Prefer cargo-dist's announcement body for Install/Download sections when present.
pub(crate) fn merge_dist_install_into_release_notes(
    release_notes: &str,
    announcement_github_body: Option<&str>,
) -> String {
    let Some(body) = announcement_github_body.map(str::trim).filter(|v| !v.is_empty()) else {
        return release_notes.to_string();
    };

    let notes = release_notes.trim_end();
    // Avoid duplicating if notes already contain dist install headings.
    if notes.contains("Install prebuilt binaries via shell script")
        || notes.contains("Install prebuilt binaries via")
        || notes.contains("## Download ")
        || notes.contains(".msi")
    {
        return notes.to_string();
    }

    // Insert before the horizontal rule footer when present.
    if let Some(idx) = notes.rfind("\n---\n") {
        let (head, tail) = notes.split_at(idx);
        format!("{}\n\n{}\n{}", head.trim_end(), body, tail.trim_start())
    } else {
        format!("{notes}\n\n{body}\n")
    }
}

pub(crate) fn preferred_dist_packages_from_publish_targets(
    publish_targets: &[(String, Option<String>)],
) -> Vec<String> {
    let mut packages = BTreeSet::new();
    for (kind, package_name) in publish_targets {
        if kind != "crates" {
            continue;
        }
        if let Some(name) = package_name
            .as_deref()
            .map(str::trim)
            .filter(|value| !value.is_empty())
        {
            packages.insert(name.to_string());
        }
    }
    packages.into_iter().collect()
}

/// Parse uploaded asset names from ledger step details for resume.
pub(crate) fn uploaded_asset_names_from_details(details: &JsonValue) -> BTreeSet<String> {
    details
        .get("uploaded_assets")
        .and_then(JsonValue::as_array)
        .map(|values| {
            values
                .iter()
                .filter_map(JsonValue::as_str)
                .map(str::to_string)
                .collect()
        })
        .unwrap_or_default()
}

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

    #[test]
    fn merge_dist_install_inserts_before_footer() {
        let notes = "# Title\n\n## What's Changed\n\n- fix\n\n---\n\nRelease: v1\n";
        let body = "## Install xbp 1.0.0\n\n### Install prebuilt binaries via shell script\n\n```sh\ncurl ...\n```\n";
        let merged = merge_dist_install_into_release_notes(notes, Some(body));
        assert!(merged.contains("Install prebuilt binaries via shell script"));
        assert!(merged.find("## Install xbp").unwrap() < merged.find("\n---\n").unwrap());
    }

    #[test]
    fn resolve_plan_disabled_without_config() {
        let _plan = resolve_cargo_dist_release_plan(Path::new("."), None, "v1.0.0", &[]);
        // May be enabled if this repo has dist-workspace.toml during tests.
        // Only assert disabled path via explicit false.
        let cfg = PublishProjectConfig {
            npm: None,
            crates: None,
            dist: Some(PublishDistConfig {
                enabled: Some(false),
                ..PublishDistConfig::default()
            }),
        };
        let plan = resolve_cargo_dist_release_plan(
            Path::new("."),
            Some(&cfg),
            "v1.0.0",
            &["xbp".to_string()],
        );
        assert!(!plan.enabled);
        assert!(
            plan.reason.contains("false"),
            "expected enabled=false reason, got: {}",
            plan.reason
        );
    }

    #[test]
    fn announcement_tag_rewrites_service_scope_to_package() {
        let packages = vec!["xbp".to_string()];
        assert_eq!(
            cargo_dist_announcement_tag("crates-cli-10.38.2", &packages),
            "xbp-10.38.2"
        );
        assert_eq!(
            cargo_dist_announcement_tag("xbp-10.38.2", &packages),
            "xbp-10.38.2"
        );
        assert_eq!(
            cargo_dist_announcement_tag("v10.38.2", &packages),
            "v10.38.2"
        );
        assert_eq!(
            cargo_dist_announcement_tag("crates-cli-10.38.2", &[]),
            "v10.38.2"
        );
    }

    #[test]
    fn npm_docs_scope_does_not_own_cargo_packages() {
        let root = Path::new("/tmp/xbp-repo");
        let scope = VersionScope::Service {
            service_root: root.join("apps/docs"),
            service_relative_root: "apps/docs".to_string(),
            service_name: "@xylex-group/xbp-docs".to_string(),
            tag_prefix: "xbp-docs-".to_string(),
            cargo_package_name: None,
            version_targets: vec![
                "apps/docs/package.json".to_string(),
                "apps/docs/README.md".to_string(),
            ],
            watch_paths: vec!["apps/docs".to_string()],
        };
        assert!(cargo_packages_owned_by_scope(root, &scope).is_empty());
    }

    #[test]
    fn athena_js_style_scope_does_not_own_cargo_packages() {
        let root = Path::new("/tmp/athena");
        let scope = VersionScope::Service {
            service_root: root.join("packages/athena-js"),
            service_relative_root: "packages/athena-js".to_string(),
            service_name: "athena-js".to_string(),
            tag_prefix: "athena-js-".to_string(),
            cargo_package_name: None,
            version_targets: vec!["packages/athena-js/package.json".to_string()],
            watch_paths: vec!["packages/athena-js".to_string()],
        };
        assert!(cargo_packages_owned_by_scope(root, &scope).is_empty());
        let release = Version::new(3, 1, 1);
        let (effective, reason) = effective_dist_packages_for_release(
            root,
            &scope,
            &[],
            &["athena-billing".to_string(), "athena_rs".to_string()],
            &release,
        );
        assert!(effective.is_empty(), "expected no dist packages");
        assert!(reason.is_some());
    }

    #[test]
    fn athena_js_tag_is_not_distable_for_rust_packages() {
        let packages = vec!["athena_rs".to_string(), "athena-billing".to_string()];
        assert!(!release_tag_is_distable("athena-js-3.1.1", &packages));
        assert!(release_tag_is_distable("athena_rs-4.0.3", &packages));
        assert!(release_tag_is_distable("v4.0.3", &packages));
        assert!(!release_tag_is_distable("xylex-group-athena-auth-ui-2.2.1", &packages));
    }

    #[test]
    fn plan_disables_dist_for_athena_js_tag_even_with_configured_packages() {
        let cfg = PublishProjectConfig {
            npm: None,
            crates: None,
            dist: Some(PublishDistConfig {
                enabled: Some(true),
                packages: vec!["athena_rs".to_string()],
                ..PublishDistConfig::default()
            }),
        };
        let root = Path::new(".");
        let release = Version::new(3, 1, 1);
        let scope = VersionScope::Service {
            service_root: root.join("packages/athena-js"),
            service_relative_root: "packages/athena-js".to_string(),
            service_name: "athena-js".to_string(),
            tag_prefix: "athena-js-".to_string(),
            cargo_package_name: None,
            version_targets: vec!["packages/athena-js/package.json".to_string()],
            watch_paths: vec!["packages/athena-js".to_string()],
        };
        let plan = resolve_cargo_dist_release_plan_for_context(CargoDistReleaseContext {
            project_root: root,
            publish_config: Some(&cfg),
            tag_name: "athena-js-3.1.1",
            release_version: &release,
            version_scope: &scope,
            preferred_packages: &[],
            skip_version_alignment: false,
        });
        assert!(
            !plan.enabled,
            "athena-js must never enable cargo-dist: {}",
            plan.reason
        );
    }

    #[test]
    fn configured_dist_packages_do_not_force_docs_release() {
        let cfg = PublishProjectConfig {
            npm: None,
            crates: None,
            dist: Some(PublishDistConfig {
                enabled: Some(true),
                packages: vec!["xbp".to_string()],
                ..PublishDistConfig::default()
            }),
        };
        let root = Path::new(".");
        let release = Version::new(10, 46, 1);
        let scope = VersionScope::Service {
            service_root: root.join("apps/docs"),
            service_relative_root: "apps/docs".to_string(),
            service_name: "@xylex-group/xbp-docs".to_string(),
            tag_prefix: "xbp-docs-".to_string(),
            cargo_package_name: None,
            version_targets: vec!["apps/docs/package.json".to_string()],
            watch_paths: vec!["apps/docs".to_string()],
        };
        let plan = resolve_cargo_dist_release_plan_for_context(CargoDistReleaseContext {
            project_root: root,
            publish_config: Some(&cfg),
            tag_name: "xbp-docs-10.46.1",
            release_version: &release,
            version_scope: &scope,
            preferred_packages: &[],
            skip_version_alignment: false,
        });
        assert!(!plan.enabled, "docs must not run cargo-dist: {}", plan.reason);
        assert!(
            plan.reason.contains("Rust")
                || plan.reason.contains("scope")
                || plan.reason.contains("dist package"),
            "unexpected reason: {}",
            plan.reason
        );
    }

    #[test]
    fn dist_error_classifier_catches_mismatch_and_empty_workspace() {
        assert!(cargo_dist_error_is_non_applicable(
            "This workspace doesn't have anything for dist to Release!"
        ));
        assert!(cargo_dist_error_is_non_applicable(
            "The provided announcement tag (xbp-10.46.1) claims we're releasing xbp 10.46.1, but that package is version 10.47.0"
        ));
        assert!(cargo_dist_error_is_non_applicable(
            "`dist build --artifacts=host` failed:\n{\"diagnostic\":{\"message\":\"This workspace doesn't have anything for dist to Release!\",\"help\":\"--tag=v4.0.3 will Announce: athena_rs\"}}"
        ));
        assert!(cargo_dist_error_is_non_applicable(
            "cargo-dist build completed but produced no uploadable artifacts under C:\\Users\\floris\\Documents\\GitHub\\athena\\target\\distrib."
        ));
        assert!(!cargo_dist_error_is_non_applicable("linker failed"));
    }

    #[test]
    fn library_only_manifest_is_not_distable() {
        let dir = std::env::temp_dir().join(format!(
            "xbp-dist-lib-only-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("src")).expect("mkdir");
        fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"athena-scheduler\"\nversion = \"4.0.3\"\nedition = \"2021\"\n",
        )
        .expect("write cargo");
        fs::write(dir.join("src").join("lib.rs"), "// lib\n").expect("write lib");
        assert!(!cargo_manifest_looks_distable(&dir.join("Cargo.toml")));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn binary_manifest_is_distable() {
        let dir = std::env::temp_dir().join(format!(
            "xbp-dist-bin-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("src")).expect("mkdir");
        fs::write(
            dir.join("Cargo.toml"),
            "[package]\nname = \"athena-cli\"\nversion = \"4.0.3\"\nedition = \"2021\"\n",
        )
        .expect("write cargo");
        fs::write(dir.join("src").join("main.rs"), "fn main() {}\n").expect("write main");
        assert!(cargo_manifest_looks_distable(&dir.join("Cargo.toml")));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn format_cargo_dist_error_extracts_diagnostic_message() {
        let raw = r#"{"diagnostic":{"message":"This workspace doesn't have anything for dist to Release!","severity":"error","help":"use --tag=v1.0.0"}}"#;
        let human = format_cargo_dist_error(raw);
        assert!(human.contains("doesn't have anything"));
        assert!(!human.contains("\"severity\""));
        assert!(human.contains("hint:") || human.contains("v1.0.0"));
    }

    #[test]
    fn format_plan_repository_diagnostic_is_human() {
        let raw = r#"{"diagnostic": {"message": "Github CI support requires you to specify the URL of your repository","severity": "error","causes": [],"help": "Set the repository = \"https://github.com/...\" key in these manifests: \nC:\\Users\\floris\\Documents\\GitHub\\athena\\Cargo.toml","labels": [],"related": []}}"#;
        let human = format_cargo_dist_error(raw);
        assert!(human.contains("repository"));
        assert!(!human.contains("\"severity\""));
        assert!(!human.contains("\"labels\""));
    }

    #[test]
    fn insert_repository_into_package_table() {
        let input = "[package]\nname = \"athena\"\nversion = \"4.0.3\"\n";
        let out = insert_repository_into_cargo_toml(input, "https://github.com/xylex-group/athena")
            .expect("insert");
        assert!(out.contains("repository = \"https://github.com/xylex-group/athena\""));
        assert!(out.contains("name = \"athena\""));
        assert!(cargo_toml_content_has_repository(&out));
        assert!(insert_repository_into_cargo_toml(&out, "https://example.com").is_none());
    }

    #[test]
    fn insert_repository_into_workspace_package_table() {
        let input = "[workspace]\nmembers = [\"crates/*\"]\n\n[workspace.package]\nversion = \"1.0.0\"\n";
        let out = insert_repository_into_cargo_toml(input, "https://github.com/org/repo")
            .expect("insert");
        assert!(out.contains("[workspace.package]"));
        assert!(out.contains("repository = \"https://github.com/org/repo\""));
    }

    #[test]
    fn insert_repository_creates_workspace_package_for_virtual_workspace() {
        let input = "[workspace]\nmembers = [\"crates/*\", \"packages/*\"]\nresolver = \"2\"\n";
        let out = insert_repository_into_cargo_toml(input, "https://github.com/xylex-group/athena")
            .expect("insert");
        assert!(out.contains("[workspace.package]"));
        assert!(out.contains("repository = \"https://github.com/xylex-group/athena\""));
        assert!(is_virtual_workspace_manifest(input));
    }

    #[test]
    fn format_strips_embedded_json_with_prefix() {
        let raw = "`dist build --artifacts=host` failed:\n{\"diagnostic\": {\"message\": \"Github CI support requires you to specify the URL of your repository\",\"severity\": \"error\",\"help\": \"Set repository in Cargo.toml\"}}";
        let human = format_cargo_dist_error(raw);
        assert!(human.contains("repository"));
        assert!(!human.contains("\"severity\""));
        assert!(!human.contains("\"diagnostic\""));
    }

    #[test]
    fn normalize_github_ssh_to_https() {
        assert_eq!(
            normalize_github_https_url("git@github.com:xylex-group/athena.git").as_deref(),
            Some("https://github.com/xylex-group/athena")
        );
    }

    #[test]
    fn align_body_rewrites_download_urls_to_github_tag() {
        let body = "https://github.com/xylex-group/xbp/releases/download/xbp-10.38.2/xbp-installer.sh";
        let aligned = align_dist_body_to_github_tag(body, "xbp-10.38.2", "crates-cli-10.38.2");
        assert!(aligned.contains("/download/crates-cli-10.38.2/xbp-installer.sh"));
        assert!(!aligned.contains("/download/xbp-10.38.2/"));
    }

    #[test]
    fn installer_package_name_from_shell_ps1_and_msi() {
        assert_eq!(
            installer_package_name(Some("xbp-installer.sh")),
            "xbp"
        );
        assert_eq!(
            installer_package_name(Some("xbp-installer.ps1")),
            "xbp"
        );
        assert_eq!(
            installer_package_name(Some("xbp-x86_64-pc-windows-msvc.msi")),
            "xbp"
        );
        assert_eq!(installer_package_name(None), "package");
    }

    #[test]
    fn default_installers_are_shell_and_msi() {
        let cfg = PublishProjectConfig {
            npm: None,
            crates: None,
            dist: Some(PublishDistConfig {
                enabled: Some(true),
                ..PublishDistConfig::default()
            }),
        };
        let plan = resolve_cargo_dist_release_plan(
            Path::new("."),
            Some(&cfg),
            "v1.0.0",
            &["xbp".to_string()],
        );
        if plan.enabled {
            assert_eq!(plan.installers, vec!["shell".to_string(), "msi".to_string()]);
        }
    }

    #[test]
    fn legacy_resolve_without_preferred_packages_is_disabled() {
        let cfg = PublishProjectConfig {
            npm: None,
            crates: None,
            dist: Some(PublishDistConfig {
                enabled: Some(true),
                packages: vec!["xbp".to_string()],
                ..PublishDistConfig::default()
            }),
        };
        let plan = resolve_cargo_dist_release_plan(Path::new("."), Some(&cfg), "v1.0.0", &[]);
        assert!(!plan.enabled);
    }
}