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
use std::collections::BTreeSet;
use std::fs;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

use colored::Colorize;
use semver::Version;

use crate::cli::commands::VersionBumpCmd;
use crate::cli::interactive::{searchable_multi_select, searchable_select};
use crate::config::load_versioning_files_registry;
use crate::strategies::XbpConfig;
use crate::utils::{find_xbp_config_upwards, write_xbp_project_config_at_path};
use dialoguer::{theme::ColorfulTheme, Input};

use super::versioning_history::{
    append_bump_history, build_history_event, load_bump_history, BumpHistoryEvent,
};
use super::versioning_suggest::{
    all_paths_patch_only, clamp_kind_for_paths, rules_for_scope, suggest_bump_kind, BumpKind,
    BumpSuggestion,
};
use super::{
    assign_dirty_paths_to_scopes, auto_commit_command_paths, auto_commit_command_paths_result,
    bump_version, clear_version_change_guards_for_scopes, collect_changed_files_since_reference,
    git_dirty_entries, git_tag_distance_from_head, load_service_version_scopes,
    parse_git_status_path, record_version_change_guard_after_write, resolve_current_version_for_bump,
    resolve_project_root, run_version_release_command, scope_matches_changed_path,
    sync_cli_version_write_activity, version_scope_prompt_label,
    write_version_to_configured_files_with_paths, ReleaseLatestPolicy, VersionReleaseOptions,
    VersionScope,
};
use crate::cli::auto_commit::AutoCommitResult;

#[derive(Clone, Debug)]
struct BumpCandidate {
    scope: VersionScope,
    changed_paths: Vec<String>,
    current_version: Version,
    baseline_source: Option<String>,
    baseline_ref: Option<String>,
    commits_since: Option<usize>,
    suggestion: BumpSuggestion,
    mode: BumpMode,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum BumpMode {
    DirtyTree,
    SinceRelease,
    ManualOffer,
}

#[derive(Clone, Debug)]
struct BumpPlan {
    scope: VersionScope,
    current: Version,
    next: Version,
    kind: BumpKind,
    changed_paths: Vec<String>,
    baseline_ref: Option<String>,
    commits_since: Option<usize>,
    mode: BumpMode,
    suggestion_reasons: Vec<String>,
    /// Skip change-guard / allow non-monotonic set (exact override).
    force: bool,
}

const BUMP_ACTIONS: [&str; 8] = [
    "Patch bump",
    "Minor bump",
    "Major bump",
    "Set exact version (force override)…",
    "Disable versioning for this service",
    "Skip",
    "Skip remaining packages",
    "Quit without bumping",
];

/// Interactive actions when the change set is docs/config only (no minor/major).
const BUMP_ACTIONS_PATCH_ONLY: [&str; 6] = [
    "Patch bump (docs/config change set — minor/major not allowed)",
    "Set exact version (force override)…",
    "Disable versioning for this service",
    "Skip",
    "Skip remaining packages",
    "Quit without bumping",
];

pub async fn run_version_bump_command(args: &VersionBumpCmd) -> Result<(), String> {
    let invocation_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let project_root = resolve_project_root();
    let registry = load_versioning_files_registry()?;
    let project_config = load_project_config(&project_root);
    let history = load_bump_history(&project_root);
    let preview_only = args.dry_run || args.plan;
    let cli_default = resolve_cli_default_kind(args);

    let dirty_paths = collect_dirty_normalized_paths(&project_root)?;
    let (mut candidates, from_dirty_tree) = if dirty_paths.is_empty() {
        let candidates = build_bump_candidates_since_release_with_options(
            &project_root,
            &invocation_dir,
            &registry,
            project_config.as_ref(),
            &history,
            cli_default.clone(),
            args.include_unchanged,
            args.refresh_tags,
        )?;
        (candidates, false)
    } else {
        let candidates = build_bump_candidates_dirty(
            &project_root,
            &invocation_dir,
            &registry,
            &dirty_paths,
            project_config.as_ref(),
            &history,
            cli_default.clone(),
        );
        (candidates, true)
    };

    if candidates.is_empty() {
        return Err(
            "No versioned packages found to bump. Register services with `xbp version discover`, \
             make changes under a watched path, or use `--include-unchanged` to offer packages \
             that already have a release tag but no commits since then. Never-released packages \
             are offered automatically on a clean tree."
                .to_string(),
        );
    }

    // Prefer cwd-matching scope first for interactive flow.
    prefer_invocation_scope(&mut candidates, &invocation_dir, &project_root);

    if from_dirty_tree {
        print_candidate_summary(&candidates, BumpMode::DirtyTree);
    } else {
        print_candidate_summary(&candidates, BumpMode::SinceRelease);
    }

    // Non-interactive force-set of a single exact version (applies to first/cwd scope).
    if let Some(raw_set) = args.set.as_deref() {
        let target = parse_explicit_version(raw_set)?;
        let candidate = candidates
            .first()
            .ok_or_else(|| "No versioned package found for --set.".to_string())?;
        let plan = build_exact_plan(candidate, target);
        let plans = vec![plan];
        if args.plan {
            print_rich_plan(&plans, from_dirty_tree);
            return Ok(());
        }
        if preview_only {
            print_dry_run_plans(&plans);
            return Ok(());
        }
        // `--set` always implies force (exact override / mistake recovery).
        let bumped =
            apply_bump_plans(&project_root, &invocation_dir, &registry, &plans, true).await?;
        maybe_chain_releases(args, &project_root, &bumped).await?;
        return Ok(());
    }

    if let Some(service) = args.disable_versioning.as_deref() {
        if preview_only {
            println!(
                "Would disable versioning for service `{}` (dry-run).",
                service
            );
            return Ok(());
        }
        disable_versioning_for_service_name(&project_root, service).await?;
        return Ok(());
    }

    let prompt_result = if args.all {
        let kind = cli_default.unwrap_or(BumpKind::Patch);
        BumpPromptResult {
            plans: build_plans_for_all_clamped(&candidates, kind),
            disable_scopes: Vec::new(),
        }
    } else if args.auto {
        BumpPromptResult {
            plans: build_plans_from_suggestions(&candidates),
            disable_scopes: Vec::new(),
        }
    } else if !std::io::stdin().is_terminal() {
        return Err(
            "Interactive terminal required for `xbp version bump`. Use `--auto`, or `--all` with \
             `--patch`/`--minor`/`--major`, or `--set <version>`. Preview with `--plan` or `--dry-run`."
                .to_string(),
        );
    } else {
        prompt_bump_plans(&candidates)?
    };

    let plans = prompt_result.plans;
    let disable_scopes = prompt_result.disable_scopes;

    if plans.is_empty() && disable_scopes.is_empty() {
        println!("{}", "No packages selected for bump.".dimmed());
        return Ok(());
    }

    if args.plan {
        print_rich_plan(&plans, from_dirty_tree);
        if !disable_scopes.is_empty() {
            println!("\n{}", "Would also disable versioning for:".bright_yellow());
            for scope in &disable_scopes {
                println!("{}", version_scope_prompt_label(scope));
            }
        }
        return Ok(());
    }

    if preview_only {
        print_dry_run_plans(&plans);
        if !disable_scopes.is_empty() {
            println!("\n{}", "Would also disable versioning for:".bright_yellow());
            for scope in &disable_scopes {
                println!("{}", version_scope_prompt_label(scope));
            }
        }
        return Ok(());
    }

    for scope in &disable_scopes {
        disable_versioning_for_scope(&project_root, scope).await?;
    }

    if plans.is_empty() {
        println!("{}", "No version bumps applied.".dimmed());
        return Ok(());
    }

    let bumped_plans = apply_bump_plans(
        &project_root,
        &invocation_dir,
        &registry,
        &plans,
        args.force,
    )
    .await?;

    println!(
        "\n{} Bumped {} package(s) independently.",
        "".bright_green().bold(),
        bumped_plans.len()
    );

    maybe_chain_releases(args, &project_root, &bumped_plans).await?;
    let _ = args.push; // reserved: auto_commit path may honor push elsewhere
    Ok(())
}

async fn maybe_chain_releases(
    args: &VersionBumpCmd,
    _project_root: &Path,
    plans: &[BumpPlan],
) -> Result<(), String> {
    if plans.is_empty() || args.no_release_prompt {
        return Ok(());
    }

    let labels: Vec<String> = plans
        .iter()
        .map(|p| {
            format!(
                "{} ({}{})",
                version_scope_prompt_label(&p.scope),
                p.current,
                p.next
            )
        })
        .collect();

    let selected_indices: Vec<usize> = if args.release {
        (0..plans.len()).collect()
    } else if std::io::stdin().is_terminal() {
        println!();
        println!(
            "{}",
            "Continue with version release for bumped packages?"
                .bright_cyan()
                .bold()
        );
        let defaults = vec![false; plans.len()];
        searchable_multi_select(
            "Select services to release (Enter with none to skip)",
            &labels,
            &defaults,
        )?
    } else {
        return Ok(());
    };

    if selected_indices.is_empty() {
        println!("{}", "Skipping release chain.".dimmed());
        return Ok(());
    }

    // Collect all choices first, then run sequentially.
    let to_release: Vec<&BumpPlan> = selected_indices
        .into_iter()
        .filter_map(|idx| plans.get(idx))
        .collect();

    for plan in to_release {
        let label = version_scope_prompt_label(&plan.scope);
        println!(
            "\n{} Releasing {} @ {}",
            "".bright_cyan(),
            label.bright_white(),
            plan.next.to_string().bright_green()
        );
        let options = VersionReleaseOptions {
            explicit_version: Some(plan.next.to_string()),
            release_flag: None,
            allow_dirty: false,
            title: None,
            notes: None,
            notes_file: None,
            draft: false,
            prerelease: false,
            publish: false,
            force: false,
            dry_run: false,
            latest_policy: ReleaseLatestPolicy::Legacy,
            force_scope: Some(plan.scope.clone()),
        };
        if let Err(error) = run_version_release_command(options).await {
            eprintln!(
                "{} Release for {label} failed: {error}",
                "".bright_red().bold()
            );
        }
    }
    Ok(())
}

fn load_project_config(project_root: &Path) -> Option<XbpConfig> {
    let found = find_xbp_config_upwards(project_root)?;
    let content = fs::read_to_string(&found.config_path).ok()?;
    let kind = crate::utils::config_kind_from_path(&found.config_path).ok()?;
    crate::utils::parse_config_with_auto_heal::<XbpConfig>(&content, kind)
        .ok()
        .map(|(config, _)| config)
}

fn resolve_cli_default_kind(args: &VersionBumpCmd) -> Option<BumpKind> {
    if args.major {
        Some(BumpKind::Major)
    } else if args.minor {
        Some(BumpKind::Minor)
    } else if args.patch {
        Some(BumpKind::Patch)
    } else {
        None
    }
}

/// Build plans for `--all`, clamping docs/config-only change sets to patch.
fn build_plans_for_all_clamped(candidates: &[BumpCandidate], kind: BumpKind) -> Vec<BumpPlan> {
    candidates
        .iter()
        .map(|candidate| {
            let effective = clamp_kind_for_paths(kind, &candidate.changed_paths);
            if effective != kind && all_paths_patch_only(&candidate.changed_paths) {
                eprintln!(
                    "  {} {} has only docs/config changes — clamping {} → patch",
                    "".bright_cyan(),
                    version_scope_prompt_label(&candidate.scope).bright_white(),
                    kind.as_str()
                );
            }
            build_plan(candidate, effective)
        })
        .collect()
}

fn build_plans_from_suggestions(candidates: &[BumpCandidate]) -> Vec<BumpPlan> {
    candidates
        .iter()
        .filter(|c| !c.changed_paths.is_empty() || matches!(c.mode, BumpMode::ManualOffer))
        .map(|candidate| build_plan(candidate, candidate.suggestion.kind.clone()))
        .collect()
}

struct BumpPromptResult {
    plans: Vec<BumpPlan>,
    disable_scopes: Vec<VersionScope>,
}

fn prompt_bump_plans(candidates: &[BumpCandidate]) -> Result<BumpPromptResult, String> {
    let mut plans = Vec::new();
    let mut disable_scopes = Vec::new();
    let total = candidates.len();

    for (index, candidate) in candidates.iter().enumerate() {
        print_candidate_detail(index + 1, total, candidate);

        let patch_only = all_paths_patch_only(&candidate.changed_paths)
            && !candidate.changed_paths.is_empty();
        let selection = if patch_only {
            eprintln!(
                "  {} Change set is docs/config only — minor/major bumps are not offered.",
                "".bright_cyan()
            );
            let selection =
                searchable_select("Choose bump action", &BUMP_ACTIONS_PATCH_ONLY, 0)?;
            let Some(selection) = selection else {
                println!("{}", "Cancelled.".dimmed());
                return Ok(BumpPromptResult {
                    plans: Vec::new(),
                    disable_scopes: Vec::new(),
                });
            };
            // Map patch-only menu indices onto the full action table.
            Some(match selection {
                0 => 0, // patch
                1 => 3, // exact
                2 => 4, // disable
                3 => 5, // skip
                4 => 6, // skip remaining
                _ => 7, // quit
            })
        } else {
            let default_idx = default_action_index(&candidate.suggestion.kind);
            searchable_select("Choose bump action", &BUMP_ACTIONS, default_idx)?
        };

        let Some(selection) = selection else {
            println!("{}", "Cancelled.".dimmed());
            return Ok(BumpPromptResult {
                plans: Vec::new(),
                disable_scopes: Vec::new(),
            });
        };

        match selection {
            0 => plans.push(build_plan(candidate, BumpKind::Patch)),
            1 => plans.push(build_plan(candidate, BumpKind::Minor)),
            2 => plans.push(build_plan(candidate, BumpKind::Major)),
            3 => match prompt_exact_version(&candidate.current_version)? {
                Some(version) => plans.push(build_exact_plan(candidate, version)),
                None => {
                    println!("{}", "Skipped exact set.".dimmed());
                }
            },
            4 => {
                disable_scopes.push(candidate.scope.clone());
                println!(
                    "  {} Will disable versioning for {}",
                    "".bright_yellow(),
                    version_scope_prompt_label(&candidate.scope).bright_white()
                );
            }
            5 => {}
            6 => break,
            _ => {
                return Ok(BumpPromptResult {
                    plans: Vec::new(),
                    disable_scopes: Vec::new(),
                });
            }
        }
    }

    Ok(BumpPromptResult {
        plans,
        disable_scopes,
    })
}

fn prompt_exact_version(current: &Version) -> Result<Option<Version>, String> {
    let input: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt(format!(
            "Exact version (current {current}; allows force override / downgrade)"
        ))
        .allow_empty(true)
        .interact_text()
        .map_err(|e| format!("Failed to read version: {e}"))?;
    let trimmed = input.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }
    Ok(Some(parse_explicit_version(trimmed)?))
}

fn parse_explicit_version(raw: &str) -> Result<Version, String> {
    let trimmed = raw.trim().trim_start_matches('v');
    Version::parse(trimmed).map_err(|e| format!("Invalid semver `{raw}`: {e}"))
}

fn build_exact_plan(candidate: &BumpCandidate, next: Version) -> BumpPlan {
    BumpPlan {
        scope: candidate.scope.clone(),
        current: candidate.current_version.clone(),
        next,
        kind: BumpKind::Exact,
        changed_paths: candidate.changed_paths.clone(),
        baseline_ref: candidate.baseline_ref.clone(),
        commits_since: candidate.commits_since,
        mode: candidate.mode,
        suggestion_reasons: vec!["interactive force override".to_string()],
        force: true,
    }
}

async fn apply_bump_plans(
    project_root: &Path,
    invocation_dir: &Path,
    registry: &[String],
    plans: &[BumpPlan],
    force_all: bool,
) -> Result<Vec<BumpPlan>, String> {
    // Operator explicitly chose these scopes — clear stale pending guards so a
    // multi-package chain is not aborted by leftover dirty state on one service
    // (commonly the repo-root service such as `xbp-legacy`).
    if !force_all {
        let scopes: Vec<&VersionScope> = plans.iter().map(|p| &p.scope).collect();
        clear_version_change_guards_for_scopes(project_root, &scopes)?;
    }

    let mut bumped_plans: Vec<BumpPlan> = Vec::new();
    let mut failed_labels: Vec<String> = Vec::new();

    for plan in plans {
        let label = version_scope_prompt_label(&plan.scope);
        let updated_paths = match write_version_to_configured_files_with_paths(
            project_root,
            invocation_dir,
            registry,
            &plan.scope,
            &plan.next,
        ) {
            Ok(paths) => paths,
            Err(error) => {
                eprintln!(
                    "  {} {} skipped — failed to write version files: {error}",
                    "".bright_red(),
                    label.bright_white()
                );
                failed_labels.push(label);
                continue;
            }
        };
        let kind_label = if plan.force || matches!(plan.kind, BumpKind::Exact) {
            "force-set"
        } else {
            plan.kind.as_str()
        };
        println!(
            "  {} {} {} -> {} ({})",
            "".bright_green(),
            label.bright_white(),
            plan.current.to_string().dimmed(),
            plan.next.to_string().bright_green().bold(),
            kind_label.bright_yellow()
        );

        let mut unique_paths = dedupe_paths(updated_paths);
        // Crate/service Cargo bumps often leave the workspace lockfile dirty.
        if unique_paths.iter().any(|p| {
            p.file_name()
                .and_then(|n| n.to_str())
                .is_some_and(|n| n.eq_ignore_ascii_case("Cargo.toml"))
        }) {
            let lock = project_root.join("Cargo.lock");
            if lock.is_file() {
                unique_paths.push(lock);
            }
        }
        let unique_paths = dedupe_paths(unique_paths);
        let commit_msg = if plan.force || matches!(plan.kind, BumpKind::Exact) {
            format!("chore(version): set {label} to {} (force)", plan.next)
        } else {
            format!("chore(version): bump {label} to {}", plan.next)
        };
        let commit_ok = match auto_commit_command_paths_result(
            project_root,
            unique_paths,
            commit_msg,
            "xbp version bump",
            false,
        )
        .await
        {
            Ok(AutoCommitResult::Committed(_)) => true,
            Ok(AutoCommitResult::Skipped(reason)) => {
                eprintln!(
                    "    {} Auto-commit skipped for {}: {}",
                    "!".bright_yellow(),
                    label.dimmed(),
                    reason.dimmed()
                );
                false
            }
            Err(error) => {
                eprintln!(
                    "    {} Auto-commit failed for {}: {}",
                    "!".bright_yellow(),
                    label.dimmed(),
                    error.dimmed()
                );
                false
            }
        };
        // Only arm the dirty guard when the version write was NOT committed.
        // Successful commits must clear the scope so multi-package bumps continue.
        if let Err(error) =
            record_version_change_guard_after_write(project_root, Some(&plan.scope), commit_ok)
        {
            eprintln!(
                "    {} Failed to update version-change guard for {}: {error}",
                "!".bright_yellow(),
                label
            );
        }
        sync_cli_version_write_activity(
            project_root,
            &plan.scope,
            &plan.next,
            format!(
                "Bumped {} from {} to {} via `xbp version bump`.",
                label, plan.current, plan.next
            ),
        )
        .await;

        let mode_label = match plan.mode {
            BumpMode::DirtyTree => "dirty",
            BumpMode::SinceRelease => "since-release",
            BumpMode::ManualOffer => "manual",
        };
        let event = build_history_event(
            &label,
            &plan.kind,
            &plan.current.to_string(),
            &plan.next.to_string(),
            mode_label,
            plan.baseline_ref.as_deref(),
            plan.commits_since,
            &plan.changed_paths,
        );
        if let Err(error) = append_bump_history(project_root, &event) {
            eprintln!(
                "{} Failed to append versioning history: {error}",
                "!".bright_yellow()
            );
        }

        bumped_plans.push(plan.clone());
    }

    if bumped_plans.is_empty() && !failed_labels.is_empty() {
        return Err(format!(
            "No packages were bumped. Failures: {}",
            failed_labels.join(", ")
        ));
    }
    if !failed_labels.is_empty() {
        eprintln!(
            "  {} {} package(s) failed; {} succeeded",
            "!".bright_yellow(),
            failed_labels.len(),
            bumped_plans.len()
        );
    }

    Ok(bumped_plans)
}

async fn disable_versioning_for_scope(
    project_root: &Path,
    scope: &VersionScope,
) -> Result<(), String> {
    match scope {
        VersionScope::Service { service_name, .. } => {
            disable_versioning_for_service_name(project_root, service_name).await
        }
        VersionScope::Crate {
            crate_relative_root,
            package_name,
            ..
        } => {
            // Prefer matching a service by package name / root; else project-level disable list.
            if let Some(name) = find_service_name_for_crate(project_root, package_name, crate_relative_root)
            {
                disable_versioning_for_service_name(project_root, &name).await
            } else {
                append_versioning_disabled_pattern(project_root, crate_relative_root).await
            }
        }
        VersionScope::Repository => Err(
            "Cannot disable versioning for the whole repository from bump; set per-service `versioning: false`."
                .to_string(),
        ),
    }
}

fn find_service_name_for_crate(
    project_root: &Path,
    package_name: &str,
    crate_relative_root: &str,
) -> Option<String> {
    let config = load_project_config(project_root)?;
    let services = config.services.as_ref()?;
    let rel = crate_relative_root.replace('\\', "/");
    services.iter().find_map(|service| {
        let root = service
            .root_directory
            .as_deref()
            .unwrap_or("")
            .replace('\\', "/")
            .trim_start_matches("./")
            .to_string();
        if service.name == package_name || root == rel || root.ends_with(&rel) {
            Some(service.name.clone())
        } else {
            None
        }
    })
}

/// Append durable `versioning_disabled` patterns (name + root) so discover
/// will not re-prompt after a service row is pruned and re-added.
fn push_versioning_disabled_pattern(config: &mut XbpConfig, pattern: &str) {
    let pattern = pattern.trim().trim_start_matches("./");
    if pattern.is_empty() {
        return;
    }
    if !config
        .versioning_disabled
        .iter()
        .any(|p| p.eq_ignore_ascii_case(pattern))
    {
        config.versioning_disabled.push(pattern.to_string());
    }
}

async fn disable_versioning_for_service_name(
    project_root: &Path,
    service_name: &str,
) -> Result<(), String> {
    let found = find_xbp_config_upwards(project_root)
        .ok_or_else(|| "No project XBP config found to update.".to_string())?;
    let content = fs::read_to_string(&found.config_path).map_err(|e| {
        format!(
            "Failed to read {}: {e}",
            found.config_path.display()
        )
    })?;
    let kind = crate::utils::config_kind_from_path(&found.config_path)?;
    let (mut config, _) =
        crate::utils::parse_config_with_auto_heal::<XbpConfig>(&content, kind)
            .map_err(|e| format!("Failed to parse project config: {e}"))?;

    let mut roots: Vec<String> = Vec::new();
    if let Some(services) = config.services.as_mut() {
        for service in services.iter_mut() {
            if service.name == service_name {
                service.versioning = Some(false);
                service.release = Some(false);
                service.version_targets = None;
                if let Some(root) = service.root_directory.as_deref() {
                    let normalized = root
                        .replace('\\', "/")
                        .trim_start_matches("./")
                        .trim_matches('/')
                        .to_string();
                    if !normalized.is_empty() {
                        roots.push(normalized);
                    }
                }
            }
        }
    }

    // Always record durable project-level patterns (name + roots) so a later
    // `xbp version discover` that drops/re-adds the service row cannot re-enable.
    push_versioning_disabled_pattern(&mut config, service_name);
    for root in &roots {
        push_versioning_disabled_pattern(&mut config, root);
    }

    write_xbp_project_config_at_path(&found.config_path, &config)?;
    println!(
        "  {} Disabled versioning for service `{}` in {}",
        "".bright_green(),
        service_name.bright_white(),
        found.config_path.display()
    );

    auto_commit_command_paths(
        project_root,
        vec![found.config_path.clone()],
        format!("chore(xbp): disable versioning for {service_name}"),
        "xbp version bump",
    )
    .await;
    Ok(())
}

async fn append_versioning_disabled_pattern(
    project_root: &Path,
    pattern: &str,
) -> Result<(), String> {
    let found = find_xbp_config_upwards(project_root)
        .ok_or_else(|| "No project XBP config found to update.".to_string())?;
    let content = fs::read_to_string(&found.config_path).map_err(|e| {
        format!(
            "Failed to read {}: {e}",
            found.config_path.display()
        )
    })?;
    let kind = crate::utils::config_kind_from_path(&found.config_path)?;
    let (mut config, _) =
        crate::utils::parse_config_with_auto_heal::<XbpConfig>(&content, kind)
            .map_err(|e| format!("Failed to parse project config: {e}"))?;

    let pattern = pattern.trim().trim_start_matches("./");
    if !config
        .versioning_disabled
        .iter()
        .any(|p| p == pattern)
    {
        config.versioning_disabled.push(pattern.to_string());
    }
    write_xbp_project_config_at_path(&found.config_path, &config)?;
    println!(
        "  {} Added `{}` to versioning_disabled in {}",
        "".bright_green(),
        pattern.bright_white(),
        found.config_path.display()
    );
    auto_commit_command_paths(
        project_root,
        vec![found.config_path.clone()],
        format!("chore(xbp): disable versioning for {pattern}"),
        "xbp version bump",
    )
    .await;
    Ok(())
}

fn default_action_index(kind: &BumpKind) -> usize {
    match kind {
        BumpKind::Patch => 0,
        BumpKind::Minor => 1,
        BumpKind::Major => 2,
        BumpKind::Exact => 3,
    }
}

fn build_plan(candidate: &BumpCandidate, kind: BumpKind) -> BumpPlan {
    BumpPlan {
        scope: candidate.scope.clone(),
        current: candidate.current_version.clone(),
        next: bump_version_for_kind(&candidate.current_version, &kind),
        kind,
        changed_paths: candidate.changed_paths.clone(),
        baseline_ref: candidate.baseline_ref.clone(),
        commits_since: candidate.commits_since,
        mode: candidate.mode,
        suggestion_reasons: candidate.suggestion.reasons.clone(),
        force: false,
    }
}

fn bump_version_for_kind(current: &Version, kind: &BumpKind) -> Version {
    match kind {
        BumpKind::Patch => bump_version(current, "patch"),
        BumpKind::Minor => bump_version(current, "minor"),
        BumpKind::Major => bump_version(current, "major"),
        BumpKind::Exact => current.clone(),
    }
}

fn collect_dirty_normalized_paths(project_root: &Path) -> Result<Vec<String>, String> {
    let entries = git_dirty_entries(project_root)?;
    let mut paths = entries
        .iter()
        .filter_map(|entry| parse_git_status_path(entry))
        .collect::<Vec<_>>();
    paths.sort();
    paths.dedup();
    Ok(paths)
}

fn enrich_candidate(
    project_root: &Path,
    invocation_dir: &Path,
    registry: &[String],
    scope: VersionScope,
    changed_paths: Vec<String>,
    mode: BumpMode,
    baseline_source: Option<String>,
    baseline_ref: Option<String>,
    commits_since: Option<usize>,
    config: Option<&XbpConfig>,
    history: &[BumpHistoryEvent],
    cli_default: Option<BumpKind>,
) -> BumpCandidate {
    let current_version =
        resolve_current_version_for_bump(project_root, invocation_dir, registry, &scope);
    let label = version_scope_prompt_label(&scope);
    let (default_kind, rules) = rules_for_scope(config, &scope);
    let suggestion = suggest_bump_kind(
        &changed_paths,
        &rules,
        default_kind,
        history,
        &label,
        commits_since,
        cli_default,
    );
    BumpCandidate {
        scope,
        changed_paths,
        current_version,
        baseline_source,
        baseline_ref,
        commits_since,
        suggestion,
        mode,
    }
}

fn build_bump_candidates_dirty(
    project_root: &Path,
    invocation_dir: &Path,
    registry: &[String],
    dirty_paths: &[String],
    config: Option<&XbpConfig>,
    history: &[BumpHistoryEvent],
    cli_default: Option<BumpKind>,
) -> Vec<BumpCandidate> {
    let nested_scopes = collect_nested_version_scopes(project_root, invocation_dir);
    let assigned = assign_dirty_paths_to_scopes(project_root, &nested_scopes, dirty_paths);
    let mut candidates = assigned
        .into_iter()
        .map(|(scope, changed_paths)| {
            enrich_candidate(
                project_root,
                invocation_dir,
                registry,
                scope,
                changed_paths,
                BumpMode::DirtyTree,
                None,
                None,
                None,
                config,
                history,
                cli_default.clone(),
            )
        })
        .collect::<Vec<_>>();

    let unscoped_paths = dirty_paths
        .iter()
        .filter(|path| {
            !candidates
                .iter()
                .any(|candidate| scope_matches_changed_path(project_root, &candidate.scope, path))
        })
        .cloned()
        .collect::<Vec<_>>();
    if !unscoped_paths.is_empty() {
        candidates.push(enrich_candidate(
            project_root,
            invocation_dir,
            registry,
            VersionScope::Repository,
            unscoped_paths,
            BumpMode::DirtyTree,
            None,
            None,
            None,
            config,
            history,
            cli_default,
        ));
    }

    sort_candidates(&mut candidates);
    candidates
}

fn build_bump_candidates_since_release_with_options(
    project_root: &Path,
    invocation_dir: &Path,
    registry: &[String],
    config: Option<&XbpConfig>,
    history: &[BumpHistoryEvent],
    cli_default: Option<BumpKind>,
    include_unchanged: bool,
    force_refresh_remote: bool,
) -> Result<Vec<BumpCandidate>, String> {
    use super::change_selection::{
        resolve_change_baseline_with_options, ChangeBaselineOptions,
    };

    let mut scopes = collect_nested_version_scopes(project_root, invocation_dir);
    if scopes.is_empty() {
        scopes.push(VersionScope::Repository);
    }

    let repo = project_root
        .file_name()
        .and_then(|v| v.to_str())
        .unwrap_or("repo");

    let baseline_opts = ChangeBaselineOptions {
        allow_remote: true,
        force_refresh_remote,
    };

    // Phase 1: resolve baselines for every scope (local tags / ledger first;
    // remote tags are fetched at most once via the shared cache).
    let mut scope_baseline_meta: Vec<(VersionScope, String, Option<String>)> = Vec::new();
    let mut unique_refs: BTreeSet<String> = BTreeSet::new();
    for scope in &scopes {
        let (source, reference, tag) =
            resolve_change_baseline_with_options(project_root, scope, repo, baseline_opts)?;
        let baseline_ref = reference.or(tag);
        if let Some(ref_name) = baseline_ref.as_ref() {
            unique_refs.insert(ref_name.clone());
        }
        scope_baseline_meta.push((scope.clone(), source, baseline_ref));
    }

    // Phase 2: one git rev-list + one git diff per unique baseline ref (not per scope).
    let mut commits_by_ref: std::collections::BTreeMap<String, Option<usize>> =
        std::collections::BTreeMap::new();
    let mut changed_by_ref: std::collections::BTreeMap<String, Vec<String>> =
        std::collections::BTreeMap::new();
    for ref_name in &unique_refs {
        commits_by_ref.insert(
            ref_name.clone(),
            git_tag_distance_from_head(project_root, ref_name),
        );
        changed_by_ref.insert(
            ref_name.clone(),
            collect_changed_files_since_reference(project_root, Some(ref_name.as_str()))
                .unwrap_or_default(),
        );
    }
    // No baseline: working-tree style diff once.
    let changed_no_baseline =
        if scope_baseline_meta.iter().any(|(_, _, br)| br.is_none()) {
            collect_changed_files_since_reference(project_root, None).unwrap_or_default()
        } else {
            Vec::new()
        };

    // Collect union of all changed files since each scope baseline, then assign
    // paths to deepest matching scope (same isolation as dirty tree).
    let mut path_to_meta: std::collections::BTreeMap<String, (String, Option<String>, Option<usize>)> =
        std::collections::BTreeMap::new();
    let mut scope_baselines: Vec<(VersionScope, String, Option<String>, Option<usize>, Vec<String>)> =
        Vec::new();

    for (scope, source, baseline_ref) in &scope_baseline_meta {
        let commits_since = baseline_ref
            .as_ref()
            .and_then(|r| commits_by_ref.get(r).copied())
            .flatten();
        let changed = match baseline_ref.as_ref() {
            Some(r) => changed_by_ref.get(r).cloned().unwrap_or_default(),
            None => changed_no_baseline.clone(),
        };
        // Filter to paths that belong to this scope when nested.
        let scoped_paths: Vec<String> = changed
            .into_iter()
            .filter(|path| {
                matches!(scope, VersionScope::Repository)
                    || scope_matches_changed_path(project_root, scope, path)
            })
            .collect();
        for path in &scoped_paths {
            path_to_meta.entry(path.clone()).or_insert_with(|| {
                (
                    source.clone(),
                    baseline_ref.clone(),
                    commits_since,
                )
            });
        }
        scope_baselines.push((
            scope.clone(),
            source.clone(),
            baseline_ref.clone(),
            commits_since,
            scoped_paths,
        ));
    }

    let all_paths: Vec<String> = path_to_meta.keys().cloned().collect();
    let assigned = assign_dirty_paths_to_scopes(project_root, &scopes, &all_paths);

    let mut candidates = Vec::new();
    let mut assigned_keys = BTreeSet::new();

    for (scope, paths) in assigned {
        let key = version_scope_prompt_label(&scope);
        assigned_keys.insert(key.clone());
        let meta = paths
            .first()
            .and_then(|p| path_to_meta.get(p))
            .cloned()
            .unwrap_or_else(|| {
                scope_baselines
                    .iter()
                    .find(|(s, _, _, _, _)| version_scope_prompt_label(s) == key)
                    .map(|(_, src, br, cs, _)| (src.clone(), br.clone(), *cs))
                    .unwrap_or_else(|| ("none".into(), None, None))
            });
        candidates.push(enrich_candidate(
            project_root,
            invocation_dir,
            registry,
            scope,
            paths,
            BumpMode::SinceRelease,
            Some(meta.0),
            meta.1,
            meta.2,
            config,
            history,
            cli_default.clone(),
        ));
    }

    // Scopes with no matching paths:
    // - `--include-unchanged`: offer even when a prior release baseline exists
    // - never released (no baseline ref / initial-release): offer automatically so a
    //   clean tree after `xbp version discover` can still `xbp v bump` without flags
    for (scope, source, baseline_ref, commits_since, paths) in scope_baselines {
        let key = version_scope_prompt_label(&scope);
        if assigned_keys.contains(&key) {
            continue;
        }
        // Paths may be non-empty for the scope's baseline filter but reassigned to a
        // deeper sibling; only offer empty path sets here.
        if !paths.is_empty() {
            continue;
        }
        let never_released = baseline_ref.is_none();
        if !(include_unchanged || never_released) {
            continue;
        }
        candidates.push(enrich_candidate(
            project_root,
            invocation_dir,
            registry,
            scope,
            Vec::new(),
            BumpMode::ManualOffer,
            Some(source),
            baseline_ref,
            commits_since,
            config,
            history,
            cli_default.clone(),
        ));
    }

    // Unscoped repo-level leftovers
    let unscoped: Vec<String> = all_paths
        .iter()
        .filter(|path| {
            !candidates
                .iter()
                .any(|c| scope_matches_changed_path(project_root, &c.scope, path))
        })
        .cloned()
        .collect();
    if !unscoped.is_empty() {
        let meta = unscoped
            .first()
            .and_then(|p| path_to_meta.get(p))
            .cloned()
            .unwrap_or_else(|| ("since-release".into(), None, None));
        candidates.push(enrich_candidate(
            project_root,
            invocation_dir,
            registry,
            VersionScope::Repository,
            unscoped,
            BumpMode::SinceRelease,
            Some(meta.0),
            meta.1,
            meta.2,
            config,
            history,
            cli_default,
        ));
    }

    sort_candidates(&mut candidates);
    Ok(candidates)
}

fn prefer_invocation_scope(
    candidates: &mut [BumpCandidate],
    invocation_dir: &Path,
    project_root: &Path,
) {
    if invocation_dir == project_root {
        return;
    }
    if let Some(matching) = candidates.iter().position(|candidate| {
        super::version_scope_root(&candidate.scope)
            .map(|root| invocation_dir.starts_with(root) || root.starts_with(invocation_dir))
            .unwrap_or(false)
    }) {
        candidates.swap(0, matching);
    }
}

fn sort_candidates(candidates: &mut [BumpCandidate]) {
    candidates.sort_by(|left, right| {
        version_scope_prompt_label(&left.scope).cmp(&version_scope_prompt_label(&right.scope))
    });
}

fn collect_nested_version_scopes(project_root: &Path, invocation_dir: &Path) -> Vec<VersionScope> {
    let mut scopes = load_service_version_scopes(project_root, invocation_dir);
    for crate_scope in load_crate_version_scopes(project_root) {
        if !scopes
            .iter()
            .any(|scope| scopes_share_root(scope, &crate_scope))
        {
            scopes.push(crate_scope);
        }
    }
    scopes.sort_by(|left, right| {
        version_scope_prompt_label(left).cmp(&version_scope_prompt_label(right))
    });
    scopes
}

fn load_crate_version_scopes(project_root: &Path) -> Vec<VersionScope> {
    let crates_root = project_root.join("crates");
    if !crates_root.is_dir() {
        return Vec::new();
    }

    let mut scopes = Vec::new();
    let Ok(entries) = fs::read_dir(&crates_root) else {
        return scopes;
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if !path.is_dir() {
            continue;
        }
        let cargo_toml = path.join("Cargo.toml");
        let Ok(content) = fs::read_to_string(&cargo_toml) else {
            continue;
        };
        let Ok(Some(package_name)) = super::cargo_package_name_from_content_optional(&content)
        else {
            continue;
        };
        let crate_relative_root = path
            .strip_prefix(project_root)
            .ok()
            .map(super::normalized_relative_path)
            .unwrap_or_else(|| {
                path.file_name()
                    .and_then(|value| value.to_str())
                    .unwrap_or("crate")
                    .to_string()
            });

        scopes.push(VersionScope::Crate {
            crate_root: path,
            crate_relative_root,
            package_name: package_name.clone(),
            tag_prefix: format!("{}-", super::default_release_tag_slug(&package_name)),
        });
    }

    scopes
}

fn scopes_share_root(left: &VersionScope, right: &VersionScope) -> bool {
    match (
        super::version_scope_root(left),
        super::version_scope_root(right),
    ) {
        (Some(left_root), Some(right_root)) => left_root == right_root,
        _ => false,
    }
}

fn print_candidate_summary(candidates: &[BumpCandidate], mode: BumpMode) {
    let title = match mode {
        BumpMode::DirtyTree => format!(
            "Found {} mutated package(s) in the working tree",
            candidates.len()
        ),
        BumpMode::SinceRelease | BumpMode::ManualOffer => format!(
            "Working tree is clean — {} package(s) with changes since last release (or offered)",
            candidates.len()
        ),
    };
    println!("\n{}", title.bright_cyan().bold());
    println!("{}", "".repeat(72).bright_black());

    for candidate in candidates {
        let suggest = format!(
            "{} ({:.0}%)",
            candidate.suggestion.kind.as_str(),
            candidate.suggestion.confidence * 100.0
        );
        let commits = candidate
            .commits_since
            .map(|n| format!("{n} commits"))
            .unwrap_or_else(|| "".into());
        println!(
            "  {:<28} {}  {} file(s)  {}  {}",
            version_scope_prompt_label(&candidate.scope).bright_white(),
            candidate.current_version.to_string().bright_green(),
            candidate.changed_paths.len().to_string().bright_yellow(),
            commits.dimmed(),
            suggest.bright_magenta()
        );
    }
}

fn print_candidate_detail(index: usize, total: usize, candidate: &BumpCandidate) {
    println!();
    println!(
        "{}",
        format!(
            "[{}/{}] {}",
            index,
            total,
            version_scope_prompt_label(&candidate.scope)
        )
        .bright_cyan()
        .bold()
    );
    println!(
        "  {:<18} {}",
        "current version".bright_white(),
        candidate.current_version.to_string().bright_green()
    );
    println!(
        "  {:<18} {} {}",
        "suggested".bright_white(),
        candidate.suggestion.kind.as_str().bright_yellow().bold(),
        format!("({:.0}%)", candidate.suggestion.confidence * 100.0).dimmed()
    );
    if let Some(baseline) = &candidate.baseline_ref {
        println!(
            "  {:<18} {} {}",
            "baseline".bright_white(),
            baseline.bright_black(),
            candidate
                .baseline_source
                .as_deref()
                .unwrap_or("")
                .dimmed()
        );
    }
    if let Some(n) = candidate.commits_since {
        println!(
            "  {:<18} {}",
            "commits since".bright_white(),
            n.to_string().bright_yellow()
        );
    }
    for reason in candidate.suggestion.reasons.iter().take(3) {
        println!("  {} {}", "·".bright_black(), reason.dimmed());
    }
    println!("  {}", "changed files".bright_white());
    for path in candidate.changed_paths.iter().take(8) {
        println!("    {} {}", "".bright_black(), path);
    }
    if candidate.changed_paths.len() > 8 {
        println!(
            "    {} … and {} more",
            "".bright_black(),
            candidate.changed_paths.len() - 8
        );
    }
    if candidate.changed_paths.is_empty() {
        println!("    {}", "(none — manual offer)".dimmed());
    }
}

fn print_dry_run_plans(plans: &[BumpPlan]) {
    println!();
    println!("{}", "Dry run — no files written".bright_yellow().bold());
    for plan in plans {
        println!(
            "  {} {} {} -> {} ({})",
            "".bright_cyan(),
            version_scope_prompt_label(&plan.scope).bright_white(),
            plan.current,
            plan.next.to_string().bright_green().bold(),
            plan.kind.as_str()
        );
    }
}

fn print_rich_plan(plans: &[BumpPlan], from_dirty: bool) {
    println!();
    println!(
        "{}",
        format!(
            "Bump plan ({})",
            if from_dirty {
                "dirty worktree"
            } else {
                "since last release"
            }
        )
        .bright_cyan()
        .bold()
    );
    println!("{}", "".repeat(72).bright_black());
    for plan in plans {
        println!(
            "\n{} {}{} ({})",
            version_scope_prompt_label(&plan.scope).bright_white().bold(),
            plan.current.to_string().dimmed(),
            plan.next.to_string().bright_green().bold(),
            plan.kind.as_str().bright_yellow()
        );
        if let Some(b) = &plan.baseline_ref {
            println!("  baseline: {}", b.bright_black());
        }
        if let Some(n) = plan.commits_since {
            println!("  commits:  {}", n.to_string().bright_yellow());
        }
        for reason in plan.suggestion_reasons.iter().take(4) {
            println!("  reason:   {}", reason.dimmed());
        }
        println!("  files ({}):", plan.changed_paths.len());
        for path in plan.changed_paths.iter().take(12) {
            println!("{path}");
        }
        if plan.changed_paths.len() > 12 {
            println!("    … +{} more", plan.changed_paths.len() - 12);
        }
    }
    println!(
        "\n{}",
        "Plan only — re-run without --plan to apply.".bright_yellow()
    );
}

fn dedupe_paths(paths: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut seen = BTreeSet::new();
    let mut unique = Vec::new();
    for path in paths {
        let key = path.to_string_lossy().replace('\\', "/");
        if seen.insert(key) {
            unique.push(path);
        }
    }
    unique
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_test_dir(label: &str) -> PathBuf {
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("clock")
            .as_nanos();
        std::env::temp_dir().join(format!("xbp-version-bump-{label}-{nanos}"))
    }

    fn git(dir: &Path, args: &[&str]) {
        let git_home = dir.join("_git_home");
        let _ = fs::create_dir_all(&git_home);
        let output = std::process::Command::new("git")
            .current_dir(dir)
            .env("HOME", &git_home)
            .env("XDG_CONFIG_HOME", git_home.join(".config"))
            .env("GIT_CONFIG_GLOBAL", git_home.join(".gitconfig"))
            .env("GIT_CONFIG_NOSYSTEM", "1")
            .args([
                "-c",
                "init.defaultBranch=main",
                "-c",
                "advice.defaultBranchName=false",
            ])
            .args(args)
            .output()
            .unwrap_or_else(|e| panic!("spawn git {:?}: {e}", args));
        assert!(
            output.status.success(),
            "git {:?} failed: {}",
            args,
            String::from_utf8_lossy(&output.stderr)
        );
    }

    #[test]
    fn clean_tree_offers_never_released_service_without_include_unchanged() {
        // Regression: after discover + commits but no release tags, clean-tree
        // `xbp v bump` must offer the package (no --include-unchanged required).
        let project_root = temp_test_dir("never-released");
        let _ = fs::remove_dir_all(&project_root);
        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir");
        fs::create_dir_all(project_root.join("src")).expect("src");
        fs::write(
            project_root.join(".xbp/xbp.toml"),
            r#"project_name = "demo"
version = "0.1.0"
port = 3000
build_dir = "./"
version_targets = ["package.json"]

[[services]]
name = "demo"
target = "nodejs"
branch = "main"
port = 3000
root_directory = "./"
version_targets = ["package.json"]
"#,
        )
        .expect("xbp.toml");
        fs::write(
            project_root.join("package.json"),
            r#"{"name":"demo","version":"0.1.0"}"#,
        )
        .expect("package.json");
        fs::write(project_root.join("src/index.ts"), "export {}\n").expect("src");

        git(&project_root, &["init", "-b", "main"]);
        git(&project_root, &["config", "user.email", "test@example.com"]);
        git(&project_root, &["config", "user.name", "Test"]);
        // Self-remote so `git ls-remote --tags origin` succeeds (no network).
        git(&project_root, &["remote", "add", "origin", project_root.to_str().unwrap()]);
        git(&project_root, &["add", "."]);
        git(&project_root, &["commit", "-m", "init"]);
        // Feature commit so there is history, still no tags.
        fs::write(project_root.join("src/index.ts"), "export const x = 1\n").expect("edit");
        git(&project_root, &["add", "src/index.ts"]);
        git(&project_root, &["commit", "-m", "feat: change"]);

        let registry = vec!["package.json".to_string()];
        let without_flag = build_bump_candidates_since_release_with_options(
            &project_root,
            &project_root,
            &registry,
            None,
            &[],
            None,
            false, // include_unchanged off
            false,
        )
        .expect("candidates");
        assert!(
            !without_flag.is_empty(),
            "never-released service should be offered on clean tree without --include-unchanged"
        );
        assert!(without_flag.iter().any(|c| {
            matches!(
                &c.scope,
                VersionScope::Service {
                    service_name,
                    ..
                } if service_name == "demo"
            ) && matches!(c.mode, BumpMode::ManualOffer)
        }));

        // After a release tag exists and HEAD is at that tag, without the flag
        // there should be no "changed since release" candidate.
        // Canonical service tag is `{slug}-{semver}` (no extra `v`).
        git(&project_root, &["tag", "-a", "demo-0.1.0", "-m", "release"]);
        let with_tag = build_bump_candidates_since_release_with_options(
            &project_root,
            &project_root,
            &registry,
            None,
            &[],
            None,
            false,
            false,
        )
        .expect("candidates with tag");
        let still_offers_demo = with_tag.iter().any(|c| {
            matches!(
                &c.scope,
                VersionScope::Service {
                    service_name,
                    ..
                } if service_name == "demo"
            )
        });
        // Tag at HEAD → no commits since release → empty unless include_unchanged.
        assert!(
            !still_offers_demo,
            "post-release clean tree must not auto-offer without --include-unchanged"
        );

        let with_flag = build_bump_candidates_since_release_with_options(
            &project_root,
            &project_root,
            &registry,
            None,
            &[],
            None,
            true,
            false,
        )
        .expect("candidates include_unchanged");
        assert!(
            with_flag.iter().any(|c| {
                matches!(
                    &c.scope,
                    VersionScope::Service {
                        service_name,
                        ..
                    } if service_name == "demo"
                )
            }),
            "--include-unchanged should still offer released-but-unchanged scopes"
        );

        let _ = fs::remove_dir_all(&project_root);
    }

    #[test]
    fn parse_explicit_version_accepts_v_prefix() {
        let v = parse_explicit_version("v1.2.3").expect("semver");
        assert_eq!(v.to_string(), "1.2.3");
    }

    #[test]
    fn build_exact_plan_marks_force() {
        let candidate = BumpCandidate {
            scope: VersionScope::Repository,
            changed_paths: vec!["README.md".into()],
            current_version: Version::new(1, 0, 0),
            baseline_source: None,
            baseline_ref: None,
            commits_since: None,
            suggestion: BumpSuggestion {
                kind: BumpKind::Patch,
                confidence: 0.5,
                reasons: vec![],
            },
            mode: BumpMode::DirtyTree,
        };
        let plan = build_exact_plan(&candidate, Version::new(0, 9, 0));
        assert!(plan.force);
        assert_eq!(plan.kind, BumpKind::Exact);
        assert_eq!(plan.next.to_string(), "0.9.0");
    }

    #[test]
    fn scope_matches_service_watch_paths_in_isolation() {
        let project_root = PathBuf::from("/repo");
        let scope = VersionScope::Service {
            service_root: PathBuf::from("/repo/apps/web"),
            service_relative_root: "apps/web".to_string(),
            service_name: "web".to_string(),
            tag_prefix: "web-".to_string(),
            cargo_package_name: None,
            version_targets: vec!["apps/web/package.json".to_string()],
            watch_paths: vec!["apps/web".to_string()],
        };

        assert!(scope_matches_changed_path(
            &project_root,
            &scope,
            "apps/web/src/routes/index.ts"
        ));
        assert!(scope_matches_changed_path(
            &project_root,
            &scope,
            "apps/web/package.json"
        ));
        assert!(!scope_matches_changed_path(
            &project_root,
            &scope,
            "apps/api/package.json"
        ));
    }

    #[test]
    fn build_bump_candidates_versions_sibling_services_independently() {
        let project_root = temp_test_dir("grouping");
        let _ = fs::remove_dir_all(&project_root);
        fs::create_dir_all(project_root.join("crates/cli/src")).expect("crate dir");
        fs::create_dir_all(project_root.join("apps/web/src")).expect("web dir");
        fs::create_dir_all(project_root.join("apps/api/src")).expect("api dir");
        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir");
        fs::write(
            project_root.join("crates/cli/Cargo.toml"),
            "[package]\nname = \"xbp_cli\"\nversion = \"1.0.0\"\n",
        )
        .expect("cargo toml");
        fs::write(
            project_root.join(".xbp/xbp.yaml"),
            r#"project_name: test
version: 0.1.0
port: 3000
build_dir: ./
services:
  - name: web
    target: web
    branch: main
    port: 3000
    root_directory: apps/web
    version_targets:
      - apps/web/package.json
    watch_paths:
      - apps/web
  - name: api
    target: api
    branch: main
    port: 3001
    root_directory: apps/api
    version_targets:
      - apps/api/package.json
    watch_paths:
      - apps/api
"#,
        )
        .expect("xbp yaml");
        fs::write(
            project_root.join("apps/web/package.json"),
            "{\"name\":\"web\",\"version\":\"0.2.0\"}",
        )
        .expect("package json");
        fs::write(
            project_root.join("apps/api/package.json"),
            "{\"name\":\"api\",\"version\":\"0.3.0\"}",
        )
        .expect("package json");

        let dirty_paths = vec![
            "crates/cli/src/main.rs".to_string(),
            "apps/web/src/app.ts".to_string(),
            "apps/api/src/handler.ts".to_string(),
        ];
        let registry = vec!["Cargo.toml".to_string(), "package.json".to_string()];
        let candidates = build_bump_candidates_dirty(
            &project_root,
            &project_root,
            &registry,
            &dirty_paths,
            None,
            &[],
            None,
        );

        assert_eq!(candidates.len(), 3);
        assert!(candidates.iter().any(|candidate| {
            matches!(candidate.scope, VersionScope::Crate { .. })
                && candidate.changed_paths == vec!["crates/cli/src/main.rs".to_string()]
        }));
        assert!(candidates.iter().any(|candidate| {
            matches!(
                &candidate.scope,
                VersionScope::Service {
                    service_name,
                    ..
                } if service_name == "web"
            ) && candidate.changed_paths == vec!["apps/web/src/app.ts".to_string()]
        }));
        assert!(candidates.iter().any(|candidate| {
            matches!(
                &candidate.scope,
                VersionScope::Service {
                    service_name,
                    ..
                } if service_name == "api"
            ) && candidate.changed_paths == vec!["apps/api/src/handler.ts".to_string()]
        }));
    }

    #[test]
    fn nested_watch_paths_assign_to_deepest_service_only() {
        let project_root = temp_test_dir("nested-watch");
        let _ = fs::remove_dir_all(&project_root);
        fs::create_dir_all(project_root.join("apps/web/packages/icons/src")).expect("icons");
        fs::create_dir_all(project_root.join("apps/web/src")).expect("web src");
        fs::create_dir_all(project_root.join(".xbp")).expect("xbp dir");
        fs::write(
            project_root.join(".xbp/xbp.yaml"),
            r#"project_name: test
version: 0.1.0
port: 3000
build_dir: ./
services:
  - name: web
    target: web
    branch: main
    port: 3000
    root_directory: apps/web
    version_targets:
      - apps/web/package.json
    watch_paths:
      - apps/web
  - name: icons
    target: nodejs
    branch: main
    port: 3001
    root_directory: apps/web/packages/icons
    version_targets:
      - apps/web/packages/icons/package.json
    watch_paths:
      - apps/web/packages/icons
"#,
        )
        .expect("yaml");
        fs::write(
            project_root.join("apps/web/package.json"),
            "{\"name\":\"web\",\"version\":\"1.0.0\"}",
        )
        .expect("web pkg");
        fs::write(
            project_root.join("apps/web/packages/icons/package.json"),
            "{\"name\":\"icons\",\"version\":\"2.0.0\"}",
        )
        .expect("icons pkg");

        let dirty_paths = vec!["apps/web/packages/icons/src/index.ts".to_string()];
        let registry = vec!["package.json".to_string()];
        let candidates = build_bump_candidates_dirty(
            &project_root,
            &project_root,
            &registry,
            &dirty_paths,
            None,
            &[],
            None,
        );

        assert_eq!(candidates.len(), 1);
        assert!(matches!(
            &candidates[0].scope,
            VersionScope::Service {
                service_name,
                ..
            } if service_name == "icons"
        ));
        assert_eq!(
            candidates[0].changed_paths,
            vec!["apps/web/packages/icons/src/index.ts".to_string()]
        );
    }
}