cuenv 0.40.6

Event-driven CLI with inline TUI for cuenv
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
//! Release management CLI commands.
//!
//! This module provides CLI commands for:
//! - `cuenv changeset add` - Create a new changeset
//! - `cuenv changeset status` - View pending changesets
//! - `cuenv changeset from-commits` - Generate changeset from conventional commits
//! - `cuenv release version` - Calculate and apply version bumps
//! - `cuenv release publish` - Publish workspace packages to crates.io in dependency order

use cuenv_release::{
    BumpType, CargoManifest, Changeset, ChangesetManager, CommitAnalyzer, CommitParser,
    PackageChange, PublishPackage, PublishPlan, ReleasePackagesConfig, TagType, Version,
    VersionCalculator,
};
use std::collections::HashSet;
use std::fmt::Write;
use std::fs;
use std::path::Path;
use std::process::{Command, Stdio};

use toml::Value as TomlValue;

/// Execute the `changeset add` command.
///
/// Creates a new changeset with the specified packages and bump types.
/// If no packages or summary are provided and stdin is a TTY, launches
/// an interactive picker.
///
/// # Errors
///
/// Returns an error if the changeset cannot be created or saved.
pub fn execute_changeset_add(
    path: &str,
    packages: &[(String, String)],
    summary: Option<&str>,
    description: Option<&str>,
) -> cuenv_core::Result<String> {
    let root = Path::new(path);

    // If no packages or summary provided and running interactively, launch picker
    if packages.is_empty()
        && summary.is_none()
        && std::io::IsTerminal::is_terminal(&std::io::stdin())
    {
        return execute_changeset_add_interactive(root);
    }

    // Validate we have the required args for non-interactive mode
    let summary = summary.ok_or_else(|| {
        cuenv_core::Error::configuration("Summary is required. Use -s or run interactively.")
    })?;

    if packages.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "At least one package must be specified. Use -P or run interactively.",
        ));
    }

    let manager = ChangesetManager::new(root);

    // Parse package changes
    let mut pkg_changes = Vec::new();
    for (name, bump_str) in packages {
        let bump = BumpType::parse(bump_str).map_err(|e| {
            cuenv_core::Error::configuration(format!("Invalid bump type for {name}: {e}"))
        })?;
        pkg_changes.push(PackageChange::new(name, bump));
    }

    let changeset = Changeset::new(summary, pkg_changes, description.map(String::from));

    let changeset_path = manager.add(&changeset).map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to create changeset: {e}"))
    })?;

    Ok(format!(
        "Created changeset: {}\n  ID: {}\n  Summary: {}",
        changeset_path.display(),
        changeset.id,
        changeset.summary
    ))
}

/// Execute the interactive changeset add flow.
fn execute_changeset_add_interactive(root: &Path) -> cuenv_core::Result<String> {
    use super::changeset_picker::{ChangesetPickerResult, PackageInfo, run_changeset_picker};

    // Get package info from manifest
    let manifest = CargoManifest::new(root);
    let package_versions = manifest.read_package_versions().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package versions: {e}"))
    })?;

    let packages: Vec<PackageInfo> = package_versions
        .into_iter()
        .map(|(name, version)| PackageInfo {
            name,
            version: version.to_string(),
        })
        .collect();

    if packages.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "No packages found in workspace",
        ));
    }

    // Run the interactive picker
    let result = run_changeset_picker(packages)
        .map_err(|e| cuenv_core::Error::configuration(format!("Interactive picker failed: {e}")))?;

    match result {
        ChangesetPickerResult::Cancelled => Ok("Changeset creation cancelled.".to_string()),
        ChangesetPickerResult::Completed {
            packages: pkg_bumps,
            summary,
            description,
        } => {
            let manager = ChangesetManager::new(root);

            let pkg_changes: Vec<PackageChange> = pkg_bumps
                .into_iter()
                .map(|(name, bump)| PackageChange::new(name, bump))
                .collect();

            let changeset = Changeset::new(&summary, pkg_changes, description);

            let changeset_path = manager.add(&changeset).map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to create changeset: {e}"))
            })?;

            Ok(format!(
                "Created changeset: {}\n  ID: {}\n  Summary: {}",
                changeset_path.display(),
                changeset.id,
                changeset.summary
            ))
        }
    }
}

/// Status output for JSON mode
#[derive(Debug, serde::Serialize)]
pub struct ChangesetStatusOutput {
    /// Number of pending changesets
    pub count: usize,
    /// Whether there are pending changesets
    pub has_pending: bool,
    /// List of changeset summaries
    pub changesets: Vec<ChangesetSummary>,
    /// Aggregated bumps per package
    pub aggregated_bumps: std::collections::HashMap<String, String>,
}

/// Summary of a single changeset for JSON output
#[derive(Debug, serde::Serialize)]
pub struct ChangesetSummary {
    /// Changeset ID
    pub id: String,
    /// Summary description
    pub summary: String,
    /// Packages affected
    pub packages: Vec<PackageBumpSummary>,
}

/// Package bump info for JSON output
#[derive(Debug, serde::Serialize)]
pub struct PackageBumpSummary {
    /// Package name
    pub name: String,
    /// Bump type
    pub bump: String,
}

/// Execute the `changeset status` command.
///
/// Lists all pending changesets and their accumulated bumps.
/// This is a convenience wrapper that defaults to human-readable output.
///
/// # Errors
///
/// Returns an error if changesets cannot be read.
#[cfg(test)]
pub fn execute_changeset_status(path: &str) -> cuenv_core::Result<String> {
    execute_changeset_status_with_format(path, crate::cli::OutputFormat::Text)
}

/// Execute the `changeset status` command with format option.
///
/// Lists all pending changesets and their accumulated bumps.
/// When format is JSON, returns structured JSON output suitable for CI parsing.
///
/// # Errors
///
/// Returns an error if changesets cannot be read.
pub fn execute_changeset_status_with_format(
    path: &str,
    format: crate::cli::OutputFormat,
) -> cuenv_core::Result<String> {
    let root = Path::new(path);
    let manager = ChangesetManager::new(root);

    let changesets = manager
        .list()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to read changesets: {e}")))?;

    // Get aggregated bumps
    let bumps = manager
        .get_package_bumps()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to aggregate bumps: {e}")))?;

    if format.is_json() {
        let output = ChangesetStatusOutput {
            count: changesets.len(),
            has_pending: !changesets.is_empty(),
            changesets: changesets
                .iter()
                .map(|cs| ChangesetSummary {
                    id: cs.id.clone(),
                    summary: cs.summary.clone(),
                    packages: cs
                        .packages
                        .iter()
                        .map(|pkg| PackageBumpSummary {
                            name: pkg.name.clone(),
                            bump: pkg.bump.to_string(),
                        })
                        .collect(),
                })
                .collect(),
            aggregated_bumps: bumps
                .iter()
                .map(|(k, v)| (k.clone(), v.to_string()))
                .collect(),
        };

        return serde_json::to_string_pretty(&output).map_err(|e| {
            cuenv_core::Error::configuration(format!("Failed to serialize JSON: {e}"))
        });
    }

    // Human-readable output
    if changesets.is_empty() {
        return Ok(
            "No pending changesets found.\n\nRun 'cuenv changeset add' to create one.".to_string(),
        );
    }

    let mut output = String::new();
    let _ = writeln!(output, "Found {} pending changeset(s):\n", changesets.len());

    for cs in &changesets {
        let _ = writeln!(output, "  {} - {}", cs.id, cs.summary);
        for pkg in &cs.packages {
            let _ = writeln!(output, "    • {} ({})", pkg.name, pkg.bump);
        }
        output.push('\n');
    }

    // Show aggregated bumps
    if !bumps.is_empty() {
        output.push_str("Aggregated version bumps:\n\n");
        let mut sorted_bumps: Vec<_> = bumps.iter().collect();
        sorted_bumps.sort_by(|a, b| a.0.cmp(b.0));
        for (pkg, bump) in sorted_bumps {
            let _ = writeln!(output, "  {pkg}: {bump}");
        }
    }

    Ok(output)
}

/// Execute the `changeset from-commits` command.
///
/// Parses conventional commits since the last tag and creates a changeset.
///
/// This function uses per-package versioning: it analyzes git diffs to determine
/// which packages each commit affects, and bumps only those packages. This enables
/// independent versioning in monorepos.
///
/// # Errors
///
/// Returns an error if commits cannot be parsed or changeset cannot be created.
pub fn execute_changeset_from_commits(
    path: &str,
    since_tag: Option<&str>,
) -> cuenv_core::Result<String> {
    let root = Path::new(path);

    // Parse conventional commits
    // TODO: Load tag_prefix and tag_type from project's release config (env.cue)
    let commits = CommitParser::parse_since_tag(root, since_tag, "", TagType::Semver)
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to parse commits: {e}")))?;

    if commits.is_empty() {
        return Ok("No conventional commits found since last tag.".to_string());
    }

    // Get package paths from manifest
    let manifest = CargoManifest::new(root);
    let package_paths = manifest.get_package_paths().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package paths: {e}"))
    })?;

    // Analyze commits per package
    let analyzer = CommitAnalyzer::new(root, package_paths.clone());
    let package_bumps = analyzer
        .calculate_bumps(&commits)
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to analyze commits: {e}")))?;

    if package_bumps.is_empty() {
        return Ok("No version-bumping commits found for any packages.\n\
             Use 'feat:' for features (minor) or 'fix:' for fixes (patch).\n\
             Note: Changes to root-level files don't affect package versions."
            .to_string());
    }

    // Create package changes only for affected packages
    let pkg_changes: Vec<PackageChange> = package_bumps
        .iter()
        .map(|(name, bump)| PackageChange::new(name, *bump))
        .collect();

    // Generate summary from commits
    let summary = CommitParser::summarize(&commits);

    // Create changeset
    let manager = ChangesetManager::new(root);
    let changeset = Changeset::new(
        format!("Release from {} commits", commits.len()),
        pkg_changes,
        Some(summary),
    );

    let changeset_path = manager.add(&changeset).map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to create changeset: {e}"))
    })?;

    let mut output = String::new();
    let _ = writeln!(
        output,
        "Created changeset from {} conventional commit(s)",
        commits.len()
    );
    let _ = writeln!(output, "  Path: {}", changeset_path.display());
    let _ = writeln!(output, "  ID: {}", changeset.id);
    let _ = writeln!(output, "\nPackages affected:");

    // Sort for consistent output
    let mut sorted_bumps: Vec<_> = package_bumps.iter().collect();
    sorted_bumps.sort_by(|a, b| a.0.cmp(b.0));
    for (name, bump) in sorted_bumps {
        let _ = writeln!(output, "  • {name} ({bump})");
    }

    // Show packages not affected
    let affected_packages: std::collections::HashSet<_> = package_bumps.keys().collect();
    let all_packages: Vec<_> = package_paths
        .keys()
        .filter(|p| !affected_packages.contains(p))
        .collect();

    if !all_packages.is_empty() {
        let _ = writeln!(output, "\nPackages unchanged:");
        for name in all_packages {
            let _ = writeln!(output, "  • {name}");
        }
    }

    Ok(output)
}

/// Execute the `release version` command.
///
/// Calculates new versions based on changesets and optionally updates manifest files.
///
/// # Errors
///
/// Returns an error if version calculation fails.
pub fn execute_release_version(
    path: &str,
    dry_run: cuenv_core::DryRun,
) -> cuenv_core::Result<String> {
    let root = Path::new(path);
    let manager = ChangesetManager::new(root);
    let manifest = CargoManifest::new(root);

    let changesets = manager
        .list()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to read changesets: {e}")))?;

    if changesets.is_empty() {
        return Err(cuenv_core::Error::configuration(
            "No changesets found. Run 'cuenv changeset add' first.",
        ));
    }

    // Read current versions from manifests
    let current_versions = manifest.read_package_versions().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package versions: {e}"))
    })?;

    // Get bumps from changesets
    let bumps = manager
        .get_package_bumps()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to aggregate bumps: {e}")))?;

    // Calculate new versions - for a workspace with shared versions, all packages share the same version
    let config = ReleasePackagesConfig::default();
    let calculator = VersionCalculator::new(current_versions.clone(), config);
    let new_versions = calculator.calculate(&bumps);

    let mut output = String::new();

    if dry_run.is_dry_run() {
        output.push_str("Dry run - no changes will be made.\n\n");
    }

    output.push_str("Version changes:\n\n");

    // Find the max new version (for workspace version)
    let max_new_version = new_versions.values().max().cloned();

    for (pkg, new_version) in &new_versions {
        let current = current_versions
            .get(pkg)
            .map_or("0.0.0".to_string(), std::string::ToString::to_string);
        let _ = writeln!(output, "  {pkg}: {current} -> {new_version}");
    }

    if !dry_run.is_dry_run() {
        // Update the workspace version
        if let Some(new_version) = max_new_version {
            manifest
                .update_workspace_version(&new_version)
                .map_err(|e| {
                    cuenv_core::Error::configuration(format!(
                        "Failed to update workspace version: {e}"
                    ))
                })?;

            // Update workspace dependency versions
            manifest
                .update_workspace_dependency_versions(&new_versions)
                .map_err(|e| {
                    cuenv_core::Error::configuration(format!(
                        "Failed to update dependency versions: {e}"
                    ))
                })?;

            // Clear consumed changesets
            manager.clear().map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to clear changesets: {e}"))
            })?;

            output.push_str("\nManifest files updated successfully.\n");
            output.push_str("Changesets have been consumed.\n");
        }
    }

    Ok(output)
}

/// Output format for release publish command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OutputFormat {
    /// Human-readable output
    Human,
    /// JSON output for CI consumption
    Json,
}

fn publish_to_crates_io(crate_dir: &Path) -> cuenv_core::Result<bool> {
    let manifest_path = crate_dir.join("Cargo.toml");
    let content = fs::read_to_string(&manifest_path).map_err(|e| {
        cuenv_core::Error::configuration(format!(
            "Failed to read crate manifest {}: {e}",
            manifest_path.display()
        ))
    })?;

    let doc: TomlValue = toml::from_str(&content).map_err(|e| {
        cuenv_core::Error::configuration(format!(
            "Failed to parse crate manifest {}: {e}",
            manifest_path.display()
        ))
    })?;

    let publish = doc.get("package").and_then(|p| p.get("publish"));

    match publish {
        Some(TomlValue::Boolean(false)) => Ok(false),
        Some(TomlValue::Array(arr)) => {
            if arr.is_empty() {
                return Ok(false);
            }
            Ok(arr
                .iter()
                .filter_map(TomlValue::as_str)
                .any(|v| v == "crates-io"))
        }
        _ => Ok(true),
    }
}

fn build_publish_plan(root: &Path) -> cuenv_core::Result<PublishPlan> {
    let manifest = CargoManifest::new(root);

    let package_paths = manifest.get_package_paths().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package paths: {e}"))
    })?;

    let package_versions = manifest.read_package_versions().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package versions: {e}"))
    })?;

    let package_deps = manifest.read_package_dependencies().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package dependencies: {e}"))
    })?;

    let mut publish_packages = Vec::new();
    for (name, path) in &package_paths {
        let version = package_versions.get(name).ok_or_else(|| {
            cuenv_core::Error::configuration(format!("No version found for package: {name}"))
        })?;
        let dependencies = package_deps.get(name).cloned().unwrap_or_default();

        publish_packages.push(PublishPackage {
            name: name.clone(),
            path: path.clone(),
            version: version.clone(),
            dependencies,
        });
    }

    PublishPlan::from_packages(publish_packages).map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to create publish plan: {e}"))
    })
}

fn publish_packages_to_crates_io(
    root: &Path,
    plan: &PublishPlan,
    publishable: &HashSet<String>,
) -> cuenv_core::Result<()> {
    for pkg in plan.iter() {
        if !publishable.contains(&pkg.name) {
            continue;
        }

        let status = Command::new("cargo")
            .current_dir(root)
            .arg("publish")
            .arg("-p")
            .arg(&pkg.name)
            .arg("--locked")
            .stdout(Stdio::inherit())
            .stderr(Stdio::inherit())
            .status()
            .map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to run 'cargo publish' for '{}': {e}", pkg.name),
                    "Ensure Rust/Cargo is available and CARGO_REGISTRY_TOKEN is set for crates.io publishing",
                )
            })?;

        if !status.success() {
            return Err(cuenv_core::Error::execution_with_help(
                format!("'cargo publish' failed for '{}'", pkg.name),
                "Check the command output above (authentication, crate metadata, or version already published)",
            ));
        }
    }

    Ok(())
}

/// Execute the `release publish` command.
///
/// Returns the topological order for publishing packages.
///
/// # Errors
///
/// Returns an error if package order cannot be determined.
pub fn execute_release_publish(
    path: &str,
    dry_run: cuenv_core::DryRun,
    format: OutputFormat,
) -> cuenv_core::Result<String> {
    let root = Path::new(path);
    let plan = build_publish_plan(root)?;

    // Extract package names in topological order
    let sorted_packages: Vec<String> = plan.iter().map(|p| p.name.clone()).collect();

    // Determine which packages are configured to publish.
    let mut publishable: HashSet<String> = HashSet::new();
    let mut skipped: HashSet<String> = HashSet::new();
    for pkg in plan.iter() {
        let should_publish = publish_to_crates_io(&pkg.path)?;
        if should_publish {
            publishable.insert(pkg.name.clone());
        } else {
            skipped.insert(pkg.name.clone());
        }
    }

    // Safety: don't allow publishing a crate that depends on an internal crate marked publish=false.
    for pkg in plan.iter() {
        if !publishable.contains(&pkg.name) {
            continue;
        }
        for dep in &pkg.dependencies {
            if skipped.contains(dep) {
                return Err(cuenv_core::Error::configuration(format!(
                    "Cannot publish '{}' because it depends on '{}' which is marked publish = false",
                    pkg.name, dep
                )));
            }
        }
    }

    if !dry_run.is_dry_run() {
        publish_packages_to_crates_io(root, &plan, &publishable)?;
    }

    match format {
        OutputFormat::Json => {
            let results = plan
                .iter()
                .map(|p| {
                    let status = if publishable.contains(&p.name) {
                        if dry_run.is_dry_run() {
                            "planned"
                        } else {
                            "published"
                        }
                    } else {
                        "skipped"
                    };

                    serde_json::json!({
                        "name": p.name,
                        "status": status,
                    })
                })
                .collect::<Vec<_>>();

            let json = serde_json::json!({
                "packages": sorted_packages,
                "results": results,
                "dry_run": dry_run.is_dry_run()
            });
            serde_json::to_string_pretty(&json).map_err(|e| {
                cuenv_core::Error::configuration(format!("Failed to serialize JSON: {e}"))
            })
        }
        OutputFormat::Human => {
            let mut output = String::new();

            if dry_run.is_dry_run() {
                output.push_str("Dry run - no packages will be published.\n\n");
            }

            if dry_run.is_dry_run() {
                output.push_str("Publish plan (topologically sorted):\n\n");
            } else {
                output.push_str("Publish order (topologically sorted):\n\n");
            }

            for (i, pkg) in sorted_packages.iter().enumerate() {
                if publishable.contains(pkg) {
                    let _ = writeln!(output, "  {}. {pkg}", i + 1);
                } else {
                    let _ = writeln!(output, "  {}. {pkg} (skipped: publish disabled)", i + 1);
                }
            }

            if dry_run.is_dry_run() {
                output.push_str("\nDry run complete.\n");
            }

            Ok(output)
        }
    }
}

/// Release phase to execute.
#[derive(Debug, Clone, Copy, Default)]
pub enum ReleaseBinariesPhase {
    /// Build binaries only.
    Build,
    /// Package binaries only.
    Package,
    /// Publish only (requires existing artifacts).
    Publish,
    /// Full pipeline: build, package, publish.
    #[default]
    Full,
}

/// Options for the `release binaries` command.
#[derive(Debug, Clone, Default)]
pub struct ReleaseBinariesOptions {
    /// Project root path.
    pub path: String,
    /// Dry run mode (no actual publishing).
    pub dry_run: cuenv_core::DryRun,
    /// Filter to specific backends.
    pub backends: Option<Vec<String>>,
    /// Release phase to execute.
    pub phase: ReleaseBinariesPhase,
    /// Target platforms to build for.
    pub targets: Option<Vec<String>>,
    /// Version to release (auto-detected from Cargo.toml if not provided).
    pub version: Option<String>,
}

impl ReleaseBinariesOptions {
    /// Creates new options with the given path.
    #[must_use]
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            ..Default::default()
        }
    }

    /// Sets dry run mode.
    #[must_use]
    pub const fn with_dry_run(mut self, dry_run: cuenv_core::DryRun) -> Self {
        self.dry_run = dry_run;
        self
    }

    /// Sets the backends filter.
    #[must_use]
    pub fn with_backends(mut self, backends: Option<Vec<String>>) -> Self {
        self.backends = backends;
        self
    }

    /// Sets the release phase.
    #[must_use]
    pub const fn with_phase(mut self, phase: ReleaseBinariesPhase) -> Self {
        self.phase = phase;
        self
    }

    /// Sets the target platforms.
    #[must_use]
    pub fn with_targets(mut self, targets: Option<Vec<String>>) -> Self {
        self.targets = targets;
        self
    }

    /// Sets the version.
    #[must_use]
    pub fn with_version(mut self, version: Option<String>) -> Self {
        self.version = version;
        self
    }
}

/// Execute the `release binaries` command.
///
/// Builds, packages, and publishes binary releases to configured backends.
///
/// # Errors
///
/// Returns an error if the release process fails.
#[allow(clippy::format_push_string, clippy::too_many_lines)]
pub async fn execute_release_binaries(opts: ReleaseBinariesOptions) -> cuenv_core::Result<String> {
    use cuenv_release::{
        CargoManifest, OrchestratorConfig, ReleaseOrchestrator, ReleasePhase, Target,
    };
    use std::path::Path;

    let root = Path::new(&opts.path);

    // Get version from Cargo.toml if not provided
    let release_version = if let Some(v) = opts.version {
        v
    } else {
        let manifest = CargoManifest::new(root);
        manifest
            .read_workspace_version()
            .map_err(|e| cuenv_core::Error::configuration(format!("Failed to read version: {e}")))?
            .to_string()
    };

    // Get binary name from Cargo.toml (use first package name or workspace name)
    let manifest = CargoManifest::new(root);
    let binary_name = manifest
        .get_package_names()
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to read packages: {e}")))?
        .into_iter()
        .next()
        .ok_or_else(|| cuenv_core::Error::configuration("No packages found in workspace"))?;

    // Parse targets
    let release_targets: Vec<Target> = if let Some(target_strs) = opts.targets {
        target_strs
            .iter()
            .map(|t| {
                t.parse::<Target>().map_err(|e| {
                    cuenv_core::Error::configuration(format!("Invalid target '{t}': {e}"))
                })
            })
            .collect::<cuenv_core::Result<Vec<_>>>()?
    } else {
        vec![Target::LinuxX64, Target::LinuxArm64, Target::DarwinArm64]
    };

    // Build config
    let config = OrchestratorConfig::new(&binary_name, &release_version)
        .with_targets(release_targets)
        .with_output_dir("target/release-artifacts")
        .with_dry_run(opts.dry_run);

    // Determine phase
    let phase = match opts.phase {
        ReleaseBinariesPhase::Build => ReleasePhase::Build,
        ReleaseBinariesPhase::Package => ReleasePhase::Package,
        ReleaseBinariesPhase::Publish => ReleasePhase::Publish,
        ReleaseBinariesPhase::Full => ReleasePhase::Full,
    };

    // Create backends
    let mut backends: Vec<Box<dyn cuenv_release::ReleaseBackend>> = Vec::new();

    // Add GitHub Releases backend if available
    #[cfg(feature = "github")]
    {
        if let Ok(token) = std::env::var("GITHUB_TOKEN") {
            // Try to get repo info from git remote
            if let Some((owner, repo)) = get_github_repo_from_remote(root) {
                let config = cuenv_github::GitHubReleaseConfig::new(&owner, &repo, token);
                backends.push(Box::new(cuenv_github::GitHubReleaseBackend::new(config)));
            }
        }
    }

    // Add Homebrew backend if available
    #[cfg(feature = "homebrew")]
    {
        // Only add if token is available (indicates intent to publish)
        if std::env::var("HOMEBREW_TAP_TOKEN").is_ok() {
            // TODO: Load tap config from CUE release config
            // For now, use a sensible default based on project name
            let tap = format!("{binary_name}/homebrew-tap");
            let config = cuenv_homebrew::HomebrewConfig::new(&tap, &binary_name)
                .with_license("AGPL-3.0-or-later")
                .with_homepage(format!("https://github.com/{binary_name}"));
            backends.push(Box::new(cuenv_homebrew::HomebrewBackend::new(config)));
        }
    }

    // Apply backend filter if specified
    if let Some(ref filter) = opts.backends {
        let filter_lower: Vec<String> = filter.iter().map(|s| s.to_lowercase()).collect();
        backends.retain(|b| filter_lower.contains(&b.name().to_lowercase()));
    }

    // Create orchestrator with backends
    let orchestrator = ReleaseOrchestrator::new(config).with_backends(backends);

    // Run orchestrator
    let report = orchestrator
        .run(phase)
        .await
        .map_err(|e| cuenv_core::Error::configuration(format!("Release failed: {e}")))?;

    // Format output
    let mut output = String::new();

    if opts.dry_run.is_dry_run() {
        output.push_str("[dry-run] ");
    }

    output.push_str(&format!("Release {binary_name} v{release_version}\n"));
    output.push_str(&format!("Phase: {:?}\n", report.phase));

    if !report.artifacts.is_empty() {
        output.push_str("\nArtifacts:\n");
        for artifact in &report.artifacts {
            output.push_str(&format!(
                "  - {} ({})\n",
                artifact.archive_name, artifact.sha256
            ));
        }
    }

    if !report.backend_results.is_empty() {
        output.push_str("\nBackend results:\n");
        for result in &report.backend_results {
            let status = if result.success { "✓" } else { "✗" };
            output.push_str(&format!(
                "  {} {}: {}\n",
                status, result.backend, result.message
            ));
            if let Some(url) = &result.url {
                output.push_str(&format!("      URL: {url}\n"));
            }
        }
    }

    if report.success {
        output.push_str("\nRelease completed successfully.\n");
    } else {
        output.push_str("\nRelease completed with errors.\n");
    }

    Ok(output)
}

/// Gets the GitHub owner/repo from the git remote origin.
#[cfg(feature = "github")]
fn get_github_repo_from_remote(root: &std::path::Path) -> Option<(String, String)> {
    let repo = gix::discover(root).ok()?;
    let remote = repo.find_remote("origin").ok()?;
    let url = remote.url(gix::remote::Direction::Fetch)?;
    parse_github_url(&url.to_bstring().to_string())
}

/// Parses a GitHub URL into (owner, repo).
#[cfg(feature = "github")]
fn parse_github_url(url: &str) -> Option<(String, String)> {
    // Handle SSH format: git@github.com:owner/repo.git
    if let Some(rest) = url.strip_prefix("git@github.com:") {
        let path = rest.strip_suffix(".git").unwrap_or(rest);
        let (owner, repo) = path.split_once('/')?;
        return Some((owner.to_string(), repo.to_string()));
    }

    // Handle HTTPS format: https://github.com/owner/repo.git
    if let Some(rest) = url.strip_prefix("https://github.com/") {
        let path = rest.strip_suffix(".git").unwrap_or(rest);
        let (owner, repo) = path.split_once('/')?;
        return Some((owner.to_string(), repo.to_string()));
    }

    None
}

/// Options for the `release prepare` command.
#[derive(Debug, Clone)]
pub struct ReleasePrepareOptions {
    /// Project root path.
    pub path: String,
    /// Git tag or ref to analyze commits from.
    pub since: Option<String>,
    /// Preview changes without applying.
    pub dry_run: cuenv_core::DryRun,
    /// Branch name for the release.
    pub branch: String,
    /// Skip creating the pull request.
    pub no_pr: bool,
}

/// Information about a package version bump.
#[derive(Debug, serde::Serialize)]
pub struct PackageBumpInfo {
    /// Package name.
    pub name: String,
    /// Current version.
    pub current_version: String,
    /// New version.
    pub new_version: String,
    /// Bump type.
    pub bump_type: String,
}

/// Execute the `release prepare` command.
///
/// This unified command orchestrates the release workflow:
/// 1. Analyze commits since the last tag
/// 2. Map commits to affected packages
/// 3. Calculate per-package version bumps
/// 4. Update Cargo.toml versions
/// 5. Generate/update CHANGELOG.md
/// 6. Create release branch, commit, and push
/// 7. Create PR via `gh` CLI
///
/// # Errors
///
/// Returns an error if any step fails.
#[allow(clippy::too_many_lines)]
pub fn execute_release_prepare(opts: &ReleasePrepareOptions) -> cuenv_core::Result<String> {
    let root = Path::new(&opts.path).canonicalize().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to resolve path '{}': {e}", &opts.path))
    })?;

    // Step 1: Parse commits since last tag
    // TODO: Load tag_prefix and tag_type from project's release config (env.cue)
    let commits = CommitParser::parse_since_tag(&root, opts.since.as_deref(), "", TagType::Semver)
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to parse commits: {e}")))?;

    if commits.is_empty() {
        return Ok("No conventional commits found since last tag. Nothing to release.".to_string());
    }

    // Step 2: Get workspace packages
    let manifest = CargoManifest::new(&root);
    let package_paths = manifest.get_package_paths().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package paths: {e}"))
    })?;
    let package_versions = manifest.read_package_versions().map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read package versions: {e}"))
    })?;

    // Step 3: Analyze which packages each commit affects
    let analyzer = CommitAnalyzer::new(&root, package_paths.clone());
    let package_bumps = analyzer
        .calculate_bumps(&commits)
        .map_err(|e| cuenv_core::Error::configuration(format!("Failed to analyze commits: {e}")))?;

    if package_bumps.is_empty() {
        return Ok("No packages affected by commits. Nothing to release.".to_string());
    }

    // Step 4: Calculate unified version for fixed (lockstep) versioning
    // All packages in the workspace share the same version.

    // Find max bump type across all affected packages
    let max_bump = package_bumps
        .values()
        .filter(|b| **b != BumpType::None)
        .max()
        .copied()
        .unwrap_or(BumpType::None);

    if max_bump == BumpType::None {
        return Ok("No version-bumping changes found. Nothing to release.".to_string());
    }

    // Find max current version across ALL workspace packages
    let max_current = package_versions
        .values()
        .max()
        .cloned()
        .ok_or_else(|| cuenv_core::Error::configuration("No packages found in workspace"))?;

    // Adjust for pre-1.0: breaking changes (Major) become Minor bumps
    let adjusted_bump = max_current.adjusted_bump_type(max_bump);
    let new_version = max_current.bump(adjusted_bump);

    // Apply same version to ALL packages (fixed/lockstep versioning)
    let mut bump_infos = Vec::new();
    for (pkg_name, current) in &package_versions {
        bump_infos.push(PackageBumpInfo {
            name: pkg_name.clone(),
            current_version: current.to_string(),
            new_version: new_version.to_string(),
            bump_type: adjusted_bump.to_string(),
        });
    }
    let new_versions: std::collections::HashMap<String, Version> = package_versions
        .keys()
        .map(|k| (k.clone(), new_version.clone()))
        .collect();

    // Build output
    let mut output = String::new();
    let _ = writeln!(output, "Release Prepare Summary");
    let _ = writeln!(output, "=======================\n");
    let _ = writeln!(output, "Commits analyzed: {}", commits.len());
    let _ = writeln!(output, "Packages affected: {}\n", bump_infos.len());

    let _ = writeln!(output, "Version Bumps:");
    let _ = writeln!(output, "{:-<60}", "");
    let _ = writeln!(output, "{:<30} {:>12} {:>12}", "Package", "Current", "New");
    let _ = writeln!(output, "{:-<60}", "");
    for info in &bump_infos {
        let _ = writeln!(
            output,
            "{:<30} {:>12} {:>12}",
            info.name, info.current_version, info.new_version
        );
    }
    let _ = writeln!(output, "{:-<60}\n", "");

    if opts.dry_run.is_dry_run() {
        let _ = writeln!(output, "[DRY RUN] No changes applied.");
        let _ = writeln!(output, "\nTo apply changes, run without --dry-run");
        return Ok(output);
    }

    // Step 5: Update Cargo.toml versions
    let _ = writeln!(output, "Updating package versions...");
    for info in &bump_infos {
        if let Some(pkg_path) = package_paths.get(&info.name) {
            let manifest_path = pkg_path.join("Cargo.toml");
            update_package_version(&manifest_path, &info.new_version)?;
        }
    }

    // Also update workspace version if present
    let workspace_manifest = root.join("Cargo.toml");
    if let Ok(content) = fs::read_to_string(&workspace_manifest)
        && content.contains("[workspace.package]")
        && content.contains("version =")
        && let Some(primary) = bump_infos.first()
        && let Some(new_ver) = new_versions.get(&primary.name)
    {
        manifest.update_workspace_version(new_ver).map_err(|e| {
            cuenv_core::Error::configuration(format!("Failed to update workspace version: {e}"))
        })?;

        // Also update workspace dependency versions
        manifest
            .update_workspace_dependency_versions(&new_versions)
            .map_err(|e| {
                cuenv_core::Error::configuration(format!(
                    "Failed to update workspace dependency versions: {e}"
                ))
            })?;
    }

    // Step 6: Create release branch, stage changes, and commit via gix
    let _ = writeln!(output, "Creating release branch '{}'...", opts.branch);
    let commit_msg = format!(
        "chore(release): prepare release\n\n{}",
        bump_infos
            .iter()
            .map(|i| format!("- {}: {} -> {}", i.name, i.current_version, i.new_version))
            .collect::<Vec<_>>()
            .join("\n")
    );
    create_branch_and_commit(&root, &opts.branch, &commit_msg)?;

    // Step 7: Push branch (kept as CLI for authentication handling)
    let _ = writeln!(output, "Pushing branch to origin...");
    run_git_push(&root, &opts.branch)?;

    // Step 8: Create PR
    if !opts.no_pr {
        let _ = writeln!(output, "Creating pull request...");
        let pr_body = generate_pr_body(&bump_infos, &commits);
        let pr_title = format!(
            "chore(release): prepare release {}",
            bump_infos
                .first()
                .map_or("next", |i| i.new_version.as_str())
        );

        match create_pull_request(&root, &pr_title, &pr_body) {
            Ok(pr_url) => {
                let _ = writeln!(output, "\nPull request created: {pr_url}");
            }
            Err(e) => {
                let _ = writeln!(output, "\nWarning: Failed to create PR: {e}");
                let _ = writeln!(output, "You can create the PR manually.");
            }
        }
    }

    let _ = writeln!(output, "\nRelease preparation complete!");
    Ok(output)
}

/// Update a package's Cargo.toml with new version.
fn update_package_version(manifest_path: &Path, new_version: &str) -> cuenv_core::Result<()> {
    let content = fs::read_to_string(manifest_path).map_err(|e| {
        cuenv_core::Error::configuration(format!("Failed to read {}: {e}", manifest_path.display()))
    })?;

    // Simple regex-free version update
    let mut new_content = String::new();
    let mut in_package = false;
    let mut version_updated = false;

    for line in content.lines() {
        if line.trim() == "[package]" {
            in_package = true;
        } else if line.starts_with('[') {
            in_package = false;
        }

        if in_package && line.trim().starts_with("version") && !version_updated {
            // Check if it's workspace reference
            if line.contains("workspace = true") {
                new_content.push_str(line);
            } else {
                let _ = write!(new_content, "version = \"{new_version}\"");
                version_updated = true;
            }
        } else {
            new_content.push_str(line);
        }
        new_content.push('\n');
    }

    fs::write(manifest_path, new_content).map_err(|e| {
        cuenv_core::Error::configuration(format!(
            "Failed to write {}: {e}",
            manifest_path.display()
        ))
    })?;

    Ok(())
}

/// Create a new branch, stage all working-tree changes, and commit them using gix.
///
/// This replaces the previous `git checkout -b`, `git add -A`, and `git commit` shell calls
/// with native gix operations. The approach:
/// 1. Discover the repository from the given path
/// 2. Build a new tree by diffing the worktree against the HEAD tree
///    - Handles tracked file modifications, deletions, and mode changes
///    - Walks worktree for new untracked files (matching `git add -A` semantics)
///    - Correctly handles symlinks by storing link targets, not dereferenced content
/// 3. Create the branch reference pointing to the current HEAD
/// 4. Point HEAD at the new branch (symbolic ref)
/// 5. Create a commit on HEAD with the new tree
fn create_branch_and_commit(root: &Path, branch: &str, message: &str) -> cuenv_core::Result<()> {
    use gix::object::tree::EntryKind;
    use gix::refs::transaction::PreviousValue;

    let repo = gix::discover(root).map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to discover git repository: {e}"),
            "Ensure you are inside a valid git repository",
        )
    })?;

    let head_commit = repo.head_commit().map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to resolve HEAD commit: {e}"),
            "Ensure the repository has at least one commit",
        )
    })?;
    let head_id = head_commit.id;
    let head_tree = head_commit.tree().map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to read HEAD tree: {e}"),
            "Repository may be corrupted",
        )
    })?;

    // Build a new tree by updating blobs for all modified tracked files
    let workdir = repo
        .workdir()
        .ok_or_else(|| cuenv_core::Error::configuration("Cannot operate in a bare repository"))?;

    let mut editor = repo.edit_tree(head_tree.id).map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to create tree editor: {e}"),
            "Repository may be corrupted",
        )
    })?;

    // Read the current index to find all tracked files, then check for modifications
    let index = repo.open_index().map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to open index: {e}"),
            "Repository index may be missing or corrupted",
        )
    })?;

    // Collect tracked file paths for new-file detection later
    let mut tracked_paths: std::collections::HashSet<std::path::PathBuf> =
        std::collections::HashSet::new();

    for entry in index.entries() {
        let rel_path = entry.path(&index);
        let rel_path_os = gix::path::from_bstr(rel_path);
        let abs_path = workdir.join(&rel_path_os);
        tracked_paths.insert(rel_path_os.to_path_buf());

        let path_str = String::from_utf8_lossy(rel_path);

        // Use lstat (no symlink follow) to get file metadata
        let fs_metadata = match gix::index::fs::Metadata::from_path_no_follow(&abs_path) {
            Ok(m) => m,
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                // File was deleted — remove from tree
                editor.remove(path_str.as_ref()).map_err(|e| {
                    cuenv_core::Error::execution_with_help(
                        format!("Failed to remove tree entry for '{path_str}': {e}"),
                        "Tree editing failed while removing deleted files",
                    )
                })?;
                continue;
            }
            Err(e) => {
                return Err(cuenv_core::Error::execution_with_help(
                    format!(
                        "Failed to read file metadata for '{}': {e}",
                        abs_path.display()
                    ),
                    "Ensure the file is accessible before running release prepare",
                ));
            }
        };

        // Skip unchanged files using stat comparison (avoids reading+hashing every file)
        if let Ok(fs_stat) = gix::index::entry::Stat::from_fs(&fs_metadata)
            && entry
                .stat
                .matches(&fs_stat, gix::index::entry::stat::Options::default())
        {
            continue;
        }

        let metadata = abs_path.symlink_metadata().map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!(
                    "Failed to read file metadata for '{}': {e}",
                    abs_path.display()
                ),
                "Ensure the file is accessible before running release prepare",
            )
        })?;

        // Read content: for symlinks, store the link target path; for regular files, read bytes
        let content = if metadata.is_symlink() {
            let target = fs::read_link(&abs_path).map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to read symlink '{}': {e}", abs_path.display()),
                    "Ensure the symlink is readable",
                )
            })?;
            target.as_os_str().as_encoded_bytes().to_vec()
        } else {
            fs::read(&abs_path).map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to read file '{}': {e}", abs_path.display()),
                    "Ensure the file is readable before running release prepare",
                )
            })?
        };

        let blob_id = repo.write_blob(&content).map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to write blob: {e}"),
                "Object database may be corrupted",
            )
        })?;

        // Determine the correct entry kind from the worktree metadata
        let kind = if metadata.is_symlink() {
            EntryKind::Link
        } else if is_executable(&metadata) {
            EntryKind::BlobExecutable
        } else {
            EntryKind::Blob
        };

        editor
            .upsert(path_str.as_ref(), kind, blob_id)
            .map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to update tree entry: {e}"),
                    "Tree editing failed",
                )
            })?;
    }

    // Walk the worktree for new (untracked) files to match `git add -A` semantics.
    // Uses ignore::WalkBuilder which respects .gitignore rules.
    for dir_entry in ignore::WalkBuilder::new(workdir)
        .hidden(false)
        .build()
        .flatten()
    {
        let path = dir_entry.path();
        if !path.is_file() && !path.is_symlink() {
            continue;
        }
        let Ok(rel_path) = path.strip_prefix(workdir) else {
            continue;
        };
        if tracked_paths.contains(rel_path) {
            continue;
        }
        // Skip .git directory entries
        if rel_path.starts_with(".git") {
            continue;
        }

        let metadata = path.symlink_metadata().map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to read metadata for '{}': {e}", path.display()),
                "Ensure the file is accessible",
            )
        })?;

        let content = if metadata.is_symlink() {
            let target = fs::read_link(path).map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to read symlink '{}': {e}", path.display()),
                    "Ensure the symlink is readable",
                )
            })?;
            target.as_os_str().as_encoded_bytes().to_vec()
        } else {
            fs::read(path).map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to read file '{}': {e}", path.display()),
                    "Ensure the file is readable",
                )
            })?
        };

        let blob_id = repo.write_blob(&content).map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to write blob: {e}"),
                "Object database may be corrupted",
            )
        })?;

        let kind = if metadata.is_symlink() {
            EntryKind::Link
        } else if is_executable(&metadata) {
            EntryKind::BlobExecutable
        } else {
            EntryKind::Blob
        };

        let rel_str = rel_path.to_string_lossy();
        editor
            .upsert(rel_str.as_ref(), kind, blob_id)
            .map_err(|e| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to add new file '{rel_str}' to tree: {e}"),
                    "Tree editing failed",
                )
            })?;
    }

    let new_tree_id = editor.write().map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to write tree: {e}"),
            "Object database may be corrupted",
        )
    })?;

    // Create the branch reference pointing to the current HEAD commit
    let branch_ref = format!("refs/heads/{branch}");
    repo.reference(
        branch_ref.as_str(),
        head_id,
        PreviousValue::MustNotExist,
        format!("branch: Created {branch}"),
    )
    .map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to create branch '{branch}': {e}"),
            "Check that the branch name is valid and does not already exist",
        )
    })?;

    // Point HEAD at the new branch (equivalent to git checkout)
    repo.edit_reference(gix::refs::transaction::RefEdit {
        change: gix::refs::transaction::Change::Update {
            log: gix::refs::transaction::LogChange::default(),
            expected: PreviousValue::Any,
            new: gix::refs::Target::Symbolic(branch_ref.try_into().map_err(
                |e: gix::validate::reference::name::Error| {
                    cuenv_core::Error::execution_with_help(
                        format!("Invalid branch name '{branch}': {e}"),
                        "Use a valid git branch name",
                    )
                },
            )?),
        },
        name: "HEAD"
            .try_into()
            .map_err(|e: gix::validate::reference::name::Error| {
                cuenv_core::Error::execution_with_help(
                    format!("Failed to resolve HEAD: {e}"),
                    "Repository may be corrupted",
                )
            })?,
        deref: false,
    })
    .map_err(|e| {
        cuenv_core::Error::execution_with_help(
            format!("Failed to update HEAD to branch '{branch}': {e}"),
            "Reference transaction failed",
        )
    })?;

    // Create the commit on HEAD (which now points to the new branch)
    repo.commit("HEAD", message, new_tree_id, [head_id])
        .map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to create commit: {e}"),
                "Ensure git user.name and user.email are configured",
            )
        })?;

    // Refresh the index to match the new commit so `git status` is clean.
    // We use `git reset` via CLI since gix index-write APIs are complex and
    // this runs once per release.
    let workdir_path = workdir.to_path_buf();
    let output = Command::new("git")
        .args(["reset", "--mixed", "HEAD"])
        .current_dir(&workdir_path)
        .output()
        .map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to refresh index after commit: {e}"),
                "The commit was created successfully but the index may be stale",
            )
        })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(cuenv_core::Error::execution_with_help(
            format!("Failed to refresh index after commit: {stderr}"),
            "The commit was created successfully but the index may be stale",
        ));
    }

    Ok(())
}

/// Check if file metadata indicates the executable bit is set.
#[cfg(unix)]
fn is_executable(metadata: &std::fs::Metadata) -> bool {
    use std::os::unix::fs::PermissionsExt;
    metadata.permissions().mode() & 0o111 != 0
}

#[cfg(not(unix))]
fn is_executable(_metadata: &std::fs::Metadata) -> bool {
    false
}

/// Push a branch to the remote origin via CLI.
///
/// Push is kept as a shell command because authentication handling
/// (SSH agents, credential helpers, etc.) is complex to replicate in-process.
fn run_git_push(root: &Path, branch: &str) -> cuenv_core::Result<()> {
    let output = Command::new("git")
        .args(["push", "-u", "origin", branch])
        .current_dir(root)
        .output()
        .map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to run git push: {e}"),
                "Ensure git is installed and available in PATH",
            )
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(cuenv_core::Error::execution_with_help(
            format!("git push failed: {stderr}"),
            "Check remote access and authentication",
        ));
    }

    Ok(())
}

/// Generate PR body from bump info and commits.
fn generate_pr_body(
    bumps: &[PackageBumpInfo],
    commits: &[cuenv_release::ConventionalCommit],
) -> String {
    let mut body = String::new();

    body.push_str("## Summary\n\n");

    // Version table
    body.push_str("| Package | Current | New | Bump |\n");
    body.push_str("|---------|---------|-----|------|\n");
    for info in bumps {
        let _ = writeln!(
            body,
            "| {} | {} | {} | {} |",
            info.name, info.current_version, info.new_version, info.bump_type
        );
    }

    body.push_str("\n## Commits\n\n");

    // Group commits by type
    let mut features: Vec<&cuenv_release::ConventionalCommit> = Vec::new();
    let mut fixes: Vec<&cuenv_release::ConventionalCommit> = Vec::new();
    let mut others: Vec<&cuenv_release::ConventionalCommit> = Vec::new();

    for commit in commits {
        match commit.commit_type.as_str() {
            "feat" => features.push(commit),
            "fix" => fixes.push(commit),
            _ => others.push(commit),
        }
    }

    if !features.is_empty() {
        body.push_str("### Features\n\n");
        for c in &features {
            let scope = c
                .scope
                .as_ref()
                .map_or(String::new(), |s| format!("**{s}**: "));
            let _ = writeln!(body, "- {}{}", scope, c.description);
        }
        body.push('\n');
    }

    if !fixes.is_empty() {
        body.push_str("### Bug Fixes\n\n");
        for c in &fixes {
            let scope = c
                .scope
                .as_ref()
                .map_or(String::new(), |s| format!("**{s}**: "));
            let _ = writeln!(body, "- {}{}", scope, c.description);
        }
        body.push('\n');
    }

    if !others.is_empty() {
        body.push_str("### Other Changes\n\n");
        for c in &others {
            let scope = c
                .scope
                .as_ref()
                .map_or(String::new(), |s| format!("**{s}**: "));
            let _ = writeln!(body, "- {}{}", scope, c.description);
        }
    }

    body.push_str("\n---\n\n🤖 Generated with [cuenv](https://github.com/cuenv/cuenv)\n");

    body
}

/// Create a pull request using gh CLI.
fn create_pull_request(root: &Path, title: &str, body: &str) -> cuenv_core::Result<String> {
    let output = Command::new("gh")
        .args(["pr", "create", "--title", title, "--body", body])
        .current_dir(root)
        .output()
        .map_err(|e| {
            cuenv_core::Error::execution_with_help(
                format!("Failed to run gh pr create: {e}"),
                "Ensure gh CLI is installed and authenticated (gh auth login)",
            )
        })?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(cuenv_core::Error::execution_with_help(
            format!("gh pr create failed: {stderr}"),
            "Ensure gh CLI is authenticated and repository has a remote origin",
        ));
    }

    let pr_url = String::from_utf8_lossy(&output.stdout).trim().to_string();
    Ok(pr_url)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::process::Command;
    use tempfile::TempDir;

    /// Create a test directory with proper prefix (non-hidden) for gix compatibility.
    ///
    /// gix has stricter checks on temp directories that start with `.` (hidden directories).
    /// The default `TempDir::new()` creates hidden directories like `.tmpXXXXX`, which can
    /// cause gix to fail with "does not appear to be a git repository".
    fn create_test_dir() -> TempDir {
        tempfile::Builder::new()
            .prefix("cuenv_test_")
            .tempdir()
            .expect("Failed to create temp directory")
    }

    fn create_test_workspace(temp: &TempDir) -> String {
        let root = temp.path();

        // Create root Cargo.toml
        let root_manifest = r#"[workspace]
resolver = "2"
members = ["crates/foo", "crates/bar"]

[workspace.package]
version = "1.0.0"
edition = "2021"

[workspace.dependencies]
foo = { path = "crates/foo", version = "1.0.0" }
bar = { path = "crates/bar", version = "1.0.0" }
"#;
        fs::write(root.join("Cargo.toml"), root_manifest).unwrap();

        // Create member crates
        fs::create_dir_all(root.join("crates/foo")).unwrap();
        fs::create_dir_all(root.join("crates/bar")).unwrap();

        let foo_manifest = r#"[package]
name = "foo"
version.workspace = true
"#;
        fs::write(root.join("crates/foo/Cargo.toml"), foo_manifest).unwrap();

        let bar_manifest = r#"[package]
name = "bar"
version.workspace = true
"#;
        fs::write(root.join("crates/bar/Cargo.toml"), bar_manifest).unwrap();

        root.to_string_lossy().to_string()
    }

    #[test]
    fn test_changeset_add() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        let packages = vec![("my-pkg".to_string(), "minor".to_string())];

        let result =
            execute_changeset_add(path, &packages, Some("Add feature"), Some("Details here"));

        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Created changeset"));
        assert!(output.contains("Add feature"));
    }

    #[test]
    fn test_changeset_add_invalid_bump() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        let packages = vec![("my-pkg".to_string(), "invalid".to_string())];

        let result = execute_changeset_add(path, &packages, Some("Test"), None);
        assert!(result.is_err());
    }

    #[test]
    fn test_changeset_add_no_packages() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        let packages: Vec<(String, String)> = vec![];

        let result = execute_changeset_add(path, &packages, Some("Test"), None);
        assert!(result.is_err());
    }

    #[test]
    fn test_changeset_status_empty() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        let result = execute_changeset_status(path);
        assert!(result.is_ok());
        assert!(result.unwrap().contains("No pending changesets"));
    }

    #[test]
    fn test_changeset_status_with_changesets() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        // First add a changeset
        let packages = vec![("pkg-a".to_string(), "minor".to_string())];
        execute_changeset_add(path, &packages, Some("Add feature"), None).unwrap();

        // Then check status
        let result = execute_changeset_status(path);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("1 pending changeset"));
        assert!(output.contains("Add feature"));
        assert!(output.contains("pkg-a"));
    }

    #[test]
    fn test_release_version_no_changesets() {
        let temp = TempDir::new().unwrap();
        let path = create_test_workspace(&temp);

        let result = execute_release_version(&path, true.into());
        assert!(result.is_err());
    }

    #[test]
    fn test_release_version_dry_run() {
        let temp = TempDir::new().unwrap();
        let path = create_test_workspace(&temp);

        // Add a changeset first
        let packages = vec![("foo".to_string(), "minor".to_string())];
        execute_changeset_add(&path, &packages, Some("Feature"), None).unwrap();

        let result = execute_release_version(&path, true.into());
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Dry run"));
        assert!(output.contains("Version changes"));
    }

    #[test]
    fn test_release_version_apply() {
        let temp = TempDir::new().unwrap();
        let path = create_test_workspace(&temp);

        // Add a changeset
        let packages = vec![("foo".to_string(), "minor".to_string())];
        execute_changeset_add(&path, &packages, Some("Feature"), None).unwrap();

        // Apply version changes
        let result = execute_release_version(&path, false.into());
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Manifest files updated"));
        assert!(output.contains("Changesets have been consumed"));

        // Verify version was updated
        let manifest = CargoManifest::new(Path::new(&path));
        let version = manifest.read_workspace_version().unwrap();
        assert_eq!(version.to_string(), "1.1.0");
    }

    #[test]
    fn test_release_publish_dry_run_human() {
        let temp = TempDir::new().unwrap();
        let path = create_test_workspace(&temp);

        let result = execute_release_publish(&path, true.into(), OutputFormat::Human);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("Dry run"));
        assert!(output.contains("Publish plan"));
    }

    #[test]
    fn test_release_publish_json() {
        let temp = TempDir::new().unwrap();
        let path = create_test_workspace(&temp);

        let result = execute_release_publish(&path, true.into(), OutputFormat::Json);
        assert!(result.is_ok());
        let output = result.unwrap();
        assert!(output.contains("\"packages\""));
        assert!(output.contains("bar"));
        assert!(output.contains("foo"));
    }

    /// Helper function to initialize and configure a git repository for testing
    fn init_git_repo(path: &str) {
        let out = Command::new("git")
            .args(["init"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git init failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );

        // Verify .git directory and HEAD file were created (ensures git init fully completed)
        let git_dir = std::path::Path::new(path).join(".git");
        let git_head = git_dir.join("HEAD");
        assert!(
            git_dir.exists(),
            "git init did not create .git directory at {}",
            git_dir.display()
        );
        assert!(
            git_head.exists(),
            "git init did not create .git/HEAD at {}",
            git_head.display()
        );

        let out = Command::new("git")
            .args(["config", "user.name", "Test User"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git config user.name failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );

        let out = Command::new("git")
            .args(["config", "user.email", "test@example.com"])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git config user.email failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    /// Helper function to create a git commit
    fn create_git_commit(path: &str, message: &str) {
        let out = Command::new("git")
            .args(["add", "."])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git add failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );

        let out = Command::new("git")
            .args(["commit", "--no-gpg-sign", "-m", message])
            .current_dir(path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git commit failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[test]
    fn test_changeset_from_commits_no_git_repo() {
        let temp = TempDir::new().unwrap();
        let path = temp.path().to_str().unwrap();

        // Should fail because there's no git repository
        let result = execute_changeset_from_commits(path, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_changeset_from_commits_with_workspace() {
        let temp = create_test_dir();
        let path = create_test_workspace(&temp);

        init_git_repo(&path);
        create_git_commit(&path, "feat: add new feature");

        // Now test the function
        let result = execute_changeset_from_commits(&path, None);
        assert!(result.is_ok(), "Expected Ok, got error: {:?}", result.err());
        let output = result.unwrap();
        assert!(output.contains("Created changeset"));
        assert!(output.contains("conventional commit"));
    }

    #[test]
    fn test_changeset_from_commits_no_version_bumps() {
        let temp = create_test_dir();
        let path = create_test_workspace(&temp);

        init_git_repo(&path);
        create_git_commit(&path, "chore: update deps");

        // Should return message about no version-bumping commits
        let result = execute_changeset_from_commits(&path, None);
        assert!(result.is_ok(), "Expected Ok, got error: {:?}", result.err());
        let output = result.unwrap();
        assert!(output.contains("No version-bumping commits"));
    }

    #[test]
    fn test_changeset_from_commits_with_since_tag() {
        let temp = create_test_dir();
        let path = create_test_workspace(&temp);

        init_git_repo(&path);
        create_git_commit(&path, "fix: initial fix");

        // Create a tag (use -m to create annotated tag, works with all git configs)
        let out = std::process::Command::new("git")
            .args(["tag", "--no-sign", "-m", "Release v0.1.0", "v0.1.0"])
            .current_dir(&path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git tag failed: {}",
            String::from_utf8_lossy(&out.stderr)
        );

        // Verify tag was created
        let out = std::process::Command::new("git")
            .args(["tag", "-l", "v0.1.0"])
            .current_dir(&path)
            .output()
            .unwrap();
        assert!(
            out.status.success() && String::from_utf8_lossy(&out.stdout).trim() == "v0.1.0",
            "git tag verification failed: stdout={}, stderr={}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );

        // Create a second commit (after tag) - this should be picked up
        // The file must be in a package directory for per-package analysis to detect it
        let new_file = std::path::Path::new(&path).join("crates/foo/new-feature.rs");
        std::fs::write(new_file, "// new feature").unwrap();
        create_git_commit(&path, "feat: new feature after tag");

        // Test with since_tag - should only process commits after the tag
        let result = execute_changeset_from_commits(&path, Some("v0.1.0"));
        assert!(result.is_ok(), "Expected Ok, got error: {:?}", result.err());
        let output = result.unwrap();
        assert!(output.contains("Created changeset"));
        assert!(output.contains("conventional commit"));
        // Should have created changeset from 1 commit (the one after the tag)
        assert!(output.contains("1 conventional commit"));
        // Only foo should be affected (not bar)
        assert!(output.contains("foo"));
    }

    #[test]
    fn test_changeset_from_commits_with_nonexistent_tag() {
        let temp = create_test_dir();
        let path = create_test_workspace(&temp);

        init_git_repo(&path);
        create_git_commit(&path, "feat: new feature");

        // Test with non-existent tag - should return error
        let result = execute_changeset_from_commits(&path, Some("v0.1.0"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("Tag 'v0.1.0' not found"));
    }
}