gen-orb-mcp 0.1.13

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

pub mod conformance_rule;
pub mod consumer_parser;
pub mod differ;
pub mod generator;
pub mod migrator;
pub mod parser;
pub mod primer;

use anyhow::Result;
use clap::{Parser, Subcommand};
use generator::CodeGenerator;
use parser::OrbParser;

/// Generate MCP servers from CircleCI orb definitions.
#[derive(Debug, Parser)]
#[command(name = "gen-orb-mcp")]
#[command(
    author,
    version,
    about,
    long_about = "Generate MCP servers from CircleCI orb definitions, \
        exposing commands, jobs, and executors as AI-accessible resources. \
        Supports migration tooling, prior-version snapshots, and diff-based \
        conformance rules to help consumers keep their CI config in sync with \
        orb updates."
)]
pub struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Debug, Subcommand)]
enum Commands {
    /// Generate an MCP server from an orb definition
    Generate {
        /// Path to the orb YAML file (e.g., src/@orb.yml)
        #[arg(short = 'p', long)]
        orb_path: std::path::PathBuf,

        /// Output directory for generated server
        #[arg(short = 'o', long, default_value = "./dist")]
        output: std::path::PathBuf,

        /// Output format
        #[arg(short, long, value_enum, default_value = "source")]
        format: OutputFormat,

        /// Name for the generated orb server (defaults to filename)
        #[arg(short, long)]
        name: Option<String>,

        /// Version for the generated MCP server crate (e.g., "1.0.0")
        ///
        /// Required when regenerating an existing output directory.
        /// For CI workflows, this should match the orb release version.
        #[arg(short = 'V', long)]
        version: Option<String>,

        /// Overwrite existing files without confirmation
        ///
        /// Required for non-interactive CI environments when output exists.
        #[arg(long)]
        force: bool,

        /// Directory containing conformance rule JSON files to embed in the
        /// server
        ///
        /// All *.json files in this directory are merged and embedded as
        /// migration tooling in the generated server. When provided,
        /// the server gains plan_migration and apply_migration MCP
        /// Tools in addition to Resources.
        #[arg(long)]
        migrations: Option<std::path::PathBuf>,

        /// Directory of prior orb version YAML snapshots to embed in the server
        ///
        /// Each file should be named `<version>.yml` (e.g., `4.7.1.yml`). The
        /// generated server will expose version-specific resources for each
        /// prior version alongside the current version.
        #[arg(long)]
        prior_versions: Option<std::path::PathBuf>,

        /// Tag prefix used to discover the orb version from git tags
        ///
        /// The git repository is derived automatically from --orb-path.
        /// Defaults to "v" (matches tags like v6.0.0).
        #[arg(long, default_value = "v")]
        tag_prefix: String,
    },
    /// Validate an orb definition without generating
    Validate {
        /// Path to the orb YAML file
        #[arg(short = 'p', long)]
        orb_path: std::path::PathBuf,
    },
    /// Compute conformance rules by diffing two orb versions
    ///
    /// Compares the current orb against a previous version (read from a file)
    /// and emits a JSON array of ConformanceRule values. These rules can be
    /// passed to `generate --migrations` to embed migration tooling in the
    /// generated MCP server.
    Diff {
        /// Path to the current orb YAML (the new version)
        #[arg(long)]
        current: std::path::PathBuf,

        /// Path to the previous orb YAML (the old version to diff against)
        #[arg(long)]
        previous: std::path::PathBuf,

        /// The version string to embed in emitted rules (e.g. "5.0.0")
        #[arg(long)]
        since_version: String,

        /// Optional output file for the JSON rules (default: stdout)
        #[arg(long)]
        output: Option<std::path::PathBuf>,
    },
    /// Apply conformance-based migration to a consumer's .circleci/ directory
    ///
    /// Reads conformance rules from a JSON file (produced by `diff`) and
    /// applies them to the consumer's CI config. Reports planned changes
    /// before applying.
    Migrate {
        /// Path to the consumer's .circleci/ directory
        #[arg(long, default_value = ".circleci")]
        ci_dir: std::path::PathBuf,

        /// The orb alias as used in the consumer's orbs: section (e.g.
        /// "toolkit")
        #[arg(long)]
        orb: String,

        /// Path to the conformance rules JSON file (produced by `diff`)
        #[arg(long)]
        rules: std::path::PathBuf,

        /// Show planned changes without modifying files
        #[arg(long)]
        dry_run: bool,
    },
    /// Populate prior-versions/ and migrations/ from git history
    ///
    /// Discovers version tags in a sliding window (default: last 6 months),
    /// checks out each version, saves a snapshot to
    /// `prior-versions/<version>.yml`, and computes conformance-rule diffs
    /// to `migrations/<version>.json`. Removes files for versions outside
    /// the window to keep binary size bounded. Idempotent.
    Prime {
        /// Path to the orb YAML entry point
        #[arg(short = 'p', long, default_value = "src/@orb.yml")]
        orb_path: std::path::PathBuf,

        /// Path to the git repository root (default: walk up from orb-path to
        /// .git)
        #[arg(long)]
        git_repo: Option<std::path::PathBuf>,

        /// Git tag prefix (e.g. "v" matches tags like "v4.1.0")
        #[arg(long, default_value = "v")]
        tag_prefix: String,

        /// Fixed earliest version anchor (e.g. "4.1.0"); conflicts with --since
        #[arg(long, conflicts_with = "since")]
        earliest_version: Option<String>,

        /// Rolling window duration (e.g. "6 months", "1 year"); default: "6
        /// months"
        #[arg(long)]
        since: Option<String>,

        /// Directory to write prior-version snapshots
        #[arg(long, default_value = "prior-versions")]
        prior_versions_dir: std::path::PathBuf,

        /// Directory to write migration rule JSON files
        #[arg(long, default_value = "migrations")]
        migrations_dir: std::path::PathBuf,

        /// Write to `/tmp/gen-orb-mcp-prime-<pid>/` and print
        /// PRIME_PV_DIR/PRIME_MIG_DIR to stdout
        #[arg(long)]
        ephemeral: bool,

        /// Override git rename detection for a specific job (repeatable).
        /// Format: `OLD=NEW`, e.g. `--rename-map common_tests_rolling=common_tests`.
        /// Manual entries take precedence over git-detected hints for matching
        /// old names.  Use this when commits cannot be restructured to follow
        /// the two-commit rename rule.
        #[arg(long, value_name = "OLD=NEW")]
        rename_map: Vec<String>,

        /// Describe actions without writing any files
        #[arg(long)]
        dry_run: bool,
    },
    /// Stage, commit, and push generated artifacts back to the repository
    ///
    /// Idempotent: if the working tree is clean after staging the specified
    /// paths, exits successfully without creating an empty commit.
    /// The default commit message includes [skip ci] to prevent CI re-triggering.
    Save {
        /// Paths to stage and commit (relative to repository root)
        #[arg(long, required = true)]
        paths: Vec<std::path::PathBuf>,

        /// Commit message
        #[arg(
            short = 'm',
            long,
            default_value = "chore: update generated MCP server artifacts [skip ci]"
        )]
        message: String,

        /// Push after committing (default: true)
        #[arg(long, default_value_t = true, action = clap::ArgAction::Set)]
        push: bool,

        /// Stage and commit only, do not push
        #[arg(long, conflicts_with = "push")]
        no_push: bool,

        /// Show what would be committed without writing anything
        #[arg(long)]
        dry_run: bool,
    },
    /// Upload a compiled binary to an existing GitHub release as a release asset
    ///
    /// The GitHub release must already exist before this command is run.
    /// Set GITHUB_TOKEN, CIRCLE_PROJECT_USERNAME, CIRCLE_PROJECT_REPONAME,
    /// and CIRCLE_TAG (or use --tag) in the environment.
    Publish {
        /// Path to the binary file to upload
        #[arg(short = 'b', long)]
        binary: std::path::PathBuf,

        /// Name for the release asset (e.g. my-orb-mcp-linux-x86_64)
        #[arg(short = 'a', long)]
        asset_name: String,

        /// Release tag to publish to (default: $CIRCLE_TAG)
        #[arg(long)]
        tag: Option<String>,

        /// Describe the upload without performing it
        #[arg(long)]
        dry_run: bool,
    },
    /// Compile generated MCP server source to a native binary
    Build {
        /// Directory containing generated MCP server source
        #[arg(short = 'i', long)]
        input: std::path::PathBuf,

        /// Override the binary name (default: derived from Cargo.toml)
        #[arg(short = 'n', long)]
        name: Option<String>,

        /// Rust target triple (default: host)
        #[arg(long)]
        target: Option<String>,

        /// Print the cargo command without running it
        #[arg(long)]
        dry_run: bool,
    },
}

/// Output format for generated MCP server
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum OutputFormat {
    /// Compile to native binary (Linux x86_64)
    Binary,
    /// Generate Rust source code
    Source,
}

/// Optional embedding inputs for `run_generate`.
struct GenerateExtras<'a> {
    migrations: &'a Option<std::path::PathBuf>,
    prior_versions_dir: &'a Option<std::path::PathBuf>,
    tag_prefix: &'a str,
}

impl Cli {
    /// Execute the CLI command
    pub fn run(&self) -> Result<()> {
        match &self.command {
            Commands::Generate {
                orb_path,
                output,
                format,
                name,
                version,
                force,
                migrations,
                prior_versions,
                tag_prefix,
            } => run_generate(
                orb_path,
                output,
                format,
                name,
                version,
                *force,
                GenerateExtras {
                    migrations,
                    prior_versions_dir: prior_versions,
                    tag_prefix,
                },
            ),
            Commands::Validate { orb_path } => run_validate(orb_path),
            Commands::Diff {
                current,
                previous,
                since_version,
                output,
            } => run_diff(current, previous, since_version, output),
            Commands::Migrate {
                ci_dir,
                orb,
                rules: rules_path,
                dry_run,
            } => run_migrate(ci_dir, orb, rules_path, *dry_run),
            Commands::Prime {
                orb_path,
                git_repo,
                tag_prefix,
                earliest_version,
                since,
                prior_versions_dir,
                migrations_dir,
                rename_map,
                ephemeral,
                dry_run,
            } => run_prime(
                orb_path,
                git_repo.as_deref(),
                tag_prefix,
                earliest_version.as_deref(),
                since.as_deref(),
                prior_versions_dir,
                migrations_dir,
                rename_map,
                *ephemeral,
                *dry_run,
            ),
            Commands::Save {
                paths,
                message,
                push,
                no_push,
                dry_run,
            } => run_save(paths, message, *push && !*no_push, *dry_run),
            Commands::Publish {
                binary,
                asset_name,
                tag,
                dry_run,
            } => run_publish(binary, asset_name, tag.as_deref(), *dry_run),
            Commands::Build {
                input,
                name,
                target,
                dry_run,
            } => run_build(input, name.as_deref(), target.as_deref(), *dry_run),
        }
    }
}

fn run_generate(
    orb_path: &std::path::PathBuf,
    output: &std::path::PathBuf,
    format: &OutputFormat,
    name: &Option<String>,
    version: &Option<String>,
    force: bool,
    extras: GenerateExtras<'_>,
) -> Result<()> {
    tracing::info!(?orb_path, ?output, ?format, "Generating MCP server");

    let orb = OrbParser::parse(orb_path).map_err(|e| anyhow::anyhow!("{}", e))?;
    tracing::info!(
        commands = orb.commands.len(),
        jobs = orb.jobs.len(),
        executors = orb.executors.len(),
        "Parsed orb definition"
    );

    let orb_name = name.clone().unwrap_or_else(|| derive_orb_name(orb_path));

    // Auto-discover version from the git repo containing orb_path
    let git_hint: Option<String> = match find_git_root(orb_path) {
        Ok(repo) => discover_latest_version(&repo, extras.tag_prefix)?,
        Err(_) => None,
    };
    let resolved_version = resolve_version(output, version.as_deref(), force, git_hint.as_deref())?;
    tracing::info!(version = %resolved_version, "Using version");

    let conformance_rules = if let Some(migrations_dir) = extras.migrations {
        load_conformance_rules(migrations_dir)?
    } else {
        vec![]
    };
    if !conformance_rules.is_empty() {
        tracing::info!(rules = conformance_rules.len(), "Loaded conformance rules");
    }

    let prior_versions_data = if let Some(dir) = extras.prior_versions_dir {
        load_prior_versions(dir)?
    } else {
        vec![]
    };
    if !prior_versions_data.is_empty() {
        tracing::info!(
            versions = prior_versions_data.len(),
            "Loaded prior versions"
        );
    }

    let conformance_rules_json = if !conformance_rules.is_empty() {
        Some(serde_json::to_string(&conformance_rules)?)
    } else {
        None
    };

    let generator = CodeGenerator::new()
        .map_err(|e| anyhow::anyhow!("{}", e))?
        .with_prior_versions(prior_versions_data)
        .with_conformance_rules_json_opt(conformance_rules_json);
    let server = generator
        .generate(&orb, &orb_name, &resolved_version)
        .map_err(|e| anyhow::anyhow!("{}", e))?;

    match format {
        OutputFormat::Source => {
            server
                .write_to(output)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            println!("Generated MCP server source code:");
            println!("  Output: {}", output.display());
            println!("  Crate: {}", server.crate_name);
            println!("  Version: {}", resolved_version);
            println!("  Commands: {}", orb.commands.len());
            println!("  Jobs: {}", orb.jobs.len());
            println!("  Executors: {}", orb.executors.len());
            println!();
            println!("To build: cd {} && cargo build --release", output.display());
        }
        OutputFormat::Binary => {
            server
                .write_to(output)
                .map_err(|e| anyhow::anyhow!("{}", e))?;
            println!("Compiling MCP server...");
            let status = std::process::Command::new("cargo")
                .args(["build", "--release"])
                .current_dir(output)
                .status();
            match status {
                Ok(s) if s.success() => {
                    let binary_path = output.join("target/release").join(&server.crate_name);
                    println!("Successfully compiled MCP server:");
                    println!("  Binary: {}", binary_path.display());
                    println!("  Version: {}", resolved_version);
                }
                Ok(_) => {
                    anyhow::bail!(
                        "Compilation failed. Source code is available at: {}",
                        output.display()
                    );
                }
                Err(e) => {
                    anyhow::bail!(
                        "Failed to run cargo: {}. Source code is available at: {}",
                        e,
                        output.display()
                    );
                }
            }
        }
    }

    Ok(())
}

fn run_validate(orb_path: &std::path::PathBuf) -> Result<()> {
    tracing::info!(?orb_path, "Validating orb definition");
    let orb = OrbParser::parse(orb_path).map_err(|e| anyhow::anyhow!("{}", e))?;

    println!("Orb validation successful!");
    println!("  Version: {}", orb.version);
    if let Some(desc) = &orb.description {
        println!("  Description: {}", desc);
    }
    println!("  Commands: {}", orb.commands.len());
    for name in orb.commands.keys() {
        println!("    - {}", name);
    }
    println!("  Jobs: {}", orb.jobs.len());
    for name in orb.jobs.keys() {
        println!("    - {}", name);
    }
    println!("  Executors: {}", orb.executors.len());
    for name in orb.executors.keys() {
        println!("    - {}", name);
    }
    Ok(())
}

fn run_diff(
    current: &std::path::PathBuf,
    previous: &std::path::PathBuf,
    since_version: &str,
    output: &Option<std::path::PathBuf>,
) -> Result<()> {
    tracing::info!(?current, ?previous, "Diffing orb versions");

    let new_orb = OrbParser::parse(current).map_err(|e| anyhow::anyhow!("{}", e))?;
    let old_orb = OrbParser::parse(previous).map_err(|e| anyhow::anyhow!("{}", e))?;

    let rules = differ::diff(&old_orb, &new_orb, since_version);
    println!("Computed {} conformance rule(s):", rules.len());
    for rule in &rules {
        println!("{}", rule.description());
    }

    let json = serde_json::to_string_pretty(&rules)?;

    if let Some(out_path) = output {
        std::fs::write(out_path, &json)?;
        println!("\nRules written to: {}", out_path.display());
    } else {
        println!("\n{}", json);
    }

    Ok(())
}

fn run_migrate(
    ci_dir: &std::path::PathBuf,
    orb: &str,
    rules_path: &std::path::PathBuf,
    dry_run: bool,
) -> Result<()> {
    tracing::info!(?ci_dir, orb, "Migrating consumer config");

    let rules_json = std::fs::read_to_string(rules_path)
        .map_err(|e| anyhow::anyhow!("Failed to read rules file: {}", e))?;
    let rules: Vec<conformance_rule::ConformanceRule> = serde_json::from_str(&rules_json)
        .map_err(|e| anyhow::anyhow!("Failed to parse rules JSON: {}", e))?;

    let config = consumer_parser::ConsumerParser::parse_directory(ci_dir)
        .map_err(|e| anyhow::anyhow!("Failed to parse CI config: {}", e))?;

    let plan = migrator::Migrator::plan(&rules, &config, orb, "");
    println!("{}", plan.format_summary());

    if plan.changes.is_empty() {
        return Ok(());
    }

    if dry_run {
        println!("\n(Dry run — no files modified)");
        return Ok(());
    }

    let applied = migrator::Migrator::apply(&plan, false)?;
    println!("\n{}", applied.format_summary());

    Ok(())
}

/// Loads prior orb version snapshots from a directory of `<version>.yml` files.
fn load_prior_versions(dir: &std::path::Path) -> Result<Vec<(String, parser::OrbDefinition)>> {
    if !dir.is_dir() {
        anyhow::bail!("Prior versions directory does not exist: {}", dir.display());
    }
    let mut versions = Vec::new();
    let entries = std::fs::read_dir(dir)?;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("yml") {
            continue;
        }
        let version = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_string();
        if version.is_empty() {
            continue;
        }
        let orb_def = OrbParser::parse(&path)
            .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", path.display(), e))?;
        tracing::debug!(path = %path.display(), version = %version, "Loaded prior version");
        versions.push((version, orb_def));
    }
    Ok(versions)
}

/// Loads and merges conformance rules from all `*.json` files in a directory.
fn load_conformance_rules(dir: &std::path::Path) -> Result<Vec<conformance_rule::ConformanceRule>> {
    if !dir.is_dir() {
        anyhow::bail!("Migrations directory does not exist: {}", dir.display());
    }
    let mut all_rules = Vec::new();
    let entries = std::fs::read_dir(dir)?;
    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let json = std::fs::read_to_string(&path)
            .map_err(|e| anyhow::anyhow!("Failed to read {}: {}", path.display(), e))?;
        let rules: Vec<conformance_rule::ConformanceRule> = serde_json::from_str(&json)
            .map_err(|e| anyhow::anyhow!("Failed to parse {}: {}", path.display(), e))?;
        tracing::debug!(path = %path.display(), count = rules.len(), "Loaded rules file");
        all_rules.extend(rules);
    }
    Ok(all_rules)
}

#[allow(clippy::too_many_arguments)]
fn run_prime(
    orb_path: &std::path::Path,
    git_repo: Option<&std::path::Path>,
    tag_prefix: &str,
    earliest_version: Option<&str>,
    since: Option<&str>,
    prior_versions_dir: &std::path::Path,
    migrations_dir: &std::path::Path,
    rename_map: &[String],
    ephemeral: bool,
    dry_run: bool,
) -> Result<()> {
    use chrono::Local;
    use primer::{
        discover_tags, filter_by_date, filter_by_version, since_cutoff, tag_date, PrimeConfig,
    };

    // Resolve git repo path: either provided, or walk up from orb_path
    let repo_path = if let Some(r) = git_repo {
        r.to_path_buf()
    } else {
        find_git_root(orb_path)?
    };

    // Relative orb path from repo root
    let orb_abs = orb_path
        .canonicalize()
        .unwrap_or_else(|_| orb_path.to_path_buf());
    let repo_abs = repo_path
        .canonicalize()
        .unwrap_or_else(|_| repo_path.to_path_buf());
    let orb_rel = orb_abs
        .strip_prefix(&repo_abs)
        .unwrap_or(orb_path)
        .to_path_buf();

    // Resolve output dirs
    let (pv_dir, mig_dir) = if ephemeral {
        let base =
            std::path::PathBuf::from(format!("/tmp/gen-orb-mcp-prime-{}", std::process::id()));
        (base.join("prior-versions"), base.join("migrations"))
    } else {
        (
            prior_versions_dir.to_path_buf(),
            migrations_dir.to_path_buf(),
        )
    };

    // Discover and filter tags
    let all_tags = discover_tags(&repo_path, tag_prefix)?;
    tracing::info!(count = all_tags.len(), "Discovered version tags");

    let window_versions: Vec<String> = if let Some(ver_str) = earliest_version {
        let earliest = semver::Version::parse(ver_str)
            .map_err(|e| anyhow::anyhow!("Invalid version '{}': {}", ver_str, e))?;
        filter_by_version(&all_tags, &earliest)
    } else {
        let since_str = since.unwrap_or("6 months");
        let today = Local::now().date_naive();
        let cutoff = since_cutoff(since_str, today)?;
        // Need dates for each tag
        let tags_with_dates: Vec<primer::TagWithDate> = all_tags
            .iter()
            .filter_map(|v| match tag_date(&repo_path, tag_prefix, v) {
                Ok(d) => Some(primer::TagWithDate {
                    version: v.clone(),
                    date: d,
                }),
                Err(e) => {
                    tracing::warn!(version = %v, error = %e, "Could not get tag date, skipping");
                    None
                }
            })
            .collect();
        filter_by_date(&tags_with_dates, cutoff)
    };

    tracing::info!(count = window_versions.len(), "Versions in window");

    // Parse --rename-map OLD=NEW entries into (from, to) pairs.
    let extra_rename_hints: Vec<(String, String)> = rename_map
        .iter()
        .filter_map(|entry| {
            let mut parts = entry.splitn(2, '=');
            let from = parts.next()?.trim().to_string();
            let to = parts.next()?.trim().to_string();
            if from.is_empty() || to.is_empty() {
                tracing::warn!(entry, "--rename-map entry is malformed; skipping");
                return None;
            }
            Some((from, to))
        })
        .collect();

    let config = PrimeConfig {
        git_repo: repo_path,
        tag_prefix: tag_prefix.to_string(),
        orb_path_relative: orb_rel,
        prior_versions_dir: pv_dir.clone(),
        migrations_dir: mig_dir.clone(),
        dry_run,
        extra_rename_hints,
    };

    let result = primer::prime(&config, &window_versions)?;

    if ephemeral {
        println!("PRIME_PV_DIR={}", pv_dir.display());
        println!("PRIME_MIG_DIR={}", mig_dir.display());
    }

    println!(
        "prime: +{} snapshots, -{} snapshots, +{} migrations, -{} migrations",
        result.snapshots_added,
        result.snapshots_removed,
        result.migrations_added,
        result.migrations_removed,
    );

    Ok(())
}

fn run_save(paths: &[std::path::PathBuf], message: &str, push: bool, dry_run: bool) -> Result<()> {
    use git2::Repository;

    let repo = Repository::discover(".")
        .map_err(|e| anyhow::anyhow!("Not inside a git repository: {}", e))?;

    let mut index = repo.index()?;
    save_stage_paths(&mut index, paths)?;

    let head_commit = repo.head().ok().and_then(|h| h.peel_to_commit().ok());
    let diff = save_compute_diff(&repo, &mut index, head_commit.as_ref())?;

    if diff.deltas().count() == 0 {
        println!("Nothing to commit — working tree clean after staging.");
        return Ok(());
    }

    if dry_run {
        save_print_dry_run(&diff, message, push);
        return Ok(());
    }

    let oid = save_create_commit(&repo, &mut index, message, head_commit.as_ref())?;
    tracing::info!(commit = %oid, "Created commit");
    println!("Created commit {oid}: {message}");

    if push {
        save_git_push(&repo)?;
    }

    Ok(())
}

fn save_stage_paths(index: &mut git2::Index, paths: &[std::path::PathBuf]) -> Result<()> {
    let mut staged_any = false;
    for path in paths {
        if path.exists() {
            index.add_path(path)?;
            staged_any = true;
        } else {
            tracing::warn!(path = %path.display(), "Path does not exist, skipping");
        }
    }
    if staged_any {
        index.write()?;
    }
    Ok(())
}

fn save_compute_diff<'repo>(
    repo: &'repo git2::Repository,
    index: &mut git2::Index,
    head_commit: Option<&git2::Commit<'_>>,
) -> Result<git2::Diff<'repo>> {
    let new_tree_oid = index.write_tree()?;
    let new_tree = repo.find_tree(new_tree_oid)?;
    let head_tree = head_commit.map(|c| c.tree()).transpose()?;
    Ok(repo.diff_tree_to_tree(head_tree.as_ref(), Some(&new_tree), None)?)
}

fn save_print_dry_run(diff: &git2::Diff<'_>, message: &str, push: bool) {
    println!("Would commit the following changes:");
    for delta in diff.deltas() {
        let path = delta
            .new_file()
            .path()
            .and_then(|p| p.to_str())
            .unwrap_or("(unknown)");
        println!("  {path}");
    }
    println!("Commit message: {message}");
    if push {
        println!("Would push after committing.");
    }
}

fn save_create_commit(
    repo: &git2::Repository,
    index: &mut git2::Index,
    message: &str,
    head_commit: Option<&git2::Commit<'_>>,
) -> Result<git2::Oid> {
    let sig = repo.signature()?;
    let new_tree_oid = index.write_tree()?;
    let new_tree = repo.find_tree(new_tree_oid)?;
    let parents: Vec<&git2::Commit> = head_commit.into_iter().collect();
    Ok(repo.commit(Some("HEAD"), &sig, &sig, message, &new_tree, &parents)?)
}

fn save_git_push(repo: &git2::Repository) -> Result<()> {
    let remote_name = repo
        .remotes()?
        .iter()
        .flatten()
        .next()
        .map(|s| s.to_string())
        .unwrap_or_else(|| "origin".to_string());

    let mut callbacks = git2::RemoteCallbacks::new();
    let git_config = repo.config()?;
    let mut cred_handler = git2_credentials::CredentialHandler::new(git_config);
    callbacks.credentials(move |url, username, allowed| {
        cred_handler.try_next_credential(url, username, allowed)
    });

    let mut push_opts = git2::PushOptions::new();
    push_opts.remote_callbacks(callbacks);

    let head_ref = repo.head()?;
    let branch_name = head_ref
        .shorthand()
        .ok_or_else(|| anyhow::anyhow!("HEAD has no branch name"))?;
    let refspec = format!("refs/heads/{branch_name}:refs/heads/{branch_name}");

    let mut remote = repo.find_remote(&remote_name)?;
    remote
        .push(&[refspec.as_str()], Some(&mut push_opts))
        .map_err(|e| anyhow::anyhow!("Push failed: {}", e))?;

    println!("Pushed to {remote_name}/{branch_name}");
    Ok(())
}

fn run_publish(
    binary: &std::path::Path,
    asset_name: &str,
    tag: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    if !binary.exists() {
        anyhow::bail!("Binary not found: {}", binary.display());
    }

    let token = std::env::var("GITHUB_TOKEN")
        .map_err(|_| anyhow::anyhow!("GITHUB_TOKEN environment variable is not set"))?;

    let resolved_tag = match tag {
        Some(t) => t.to_string(),
        None => std::env::var("CIRCLE_TAG").map_err(|_| {
            anyhow::anyhow!("No release tag provided. Set CIRCLE_TAG or use --tag <TAG>")
        })?,
    };

    let owner = std::env::var("CIRCLE_PROJECT_USERNAME").unwrap_or_default();
    let repo = std::env::var("CIRCLE_PROJECT_REPONAME").unwrap_or_default();

    if dry_run {
        println!("Would upload release asset (dry run):");
        println!("  Binary:     {}", binary.display());
        println!("  Asset name: {asset_name}");
        println!("  Tag:        {resolved_tag}");
        if !owner.is_empty() && !repo.is_empty() {
            println!("  Repo:       {owner}/{repo}");
        }
        return Ok(());
    }

    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()?
        .block_on(upload_release_asset(
            &token,
            &owner,
            &repo,
            &resolved_tag,
            binary,
            asset_name,
        ))
}

async fn upload_release_asset(
    token: &str,
    owner: &str,
    repo: &str,
    tag: &str,
    binary: &std::path::Path,
    asset_name: &str,
) -> Result<()> {
    use octocrate::repos;
    use octocrate::{APIConfig, GitHubAPI, PersonalAccessToken};

    let pat = PersonalAccessToken::new(token);
    let config = APIConfig::with_token(pat).shared();
    let api = GitHubAPI::new(&config);

    tracing::info!(owner, repo, tag, "Looking up GitHub release");
    let release = api
        .repos
        .get_release_by_tag(owner, repo, tag)
        .send()
        .await
        .map_err(|e| {
            anyhow::anyhow!(
                "Release not found for tag '{}' in {}/{}: {}",
                tag,
                owner,
                repo,
                e
            )
        })?;

    tracing::info!(release_id = release.id, "Found release");

    let file = tokio::fs::File::open(binary)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to open binary '{}': {}", binary.display(), e))?;
    let file_size = file.metadata().await?.len();

    let query = repos::upload_release_asset::Query::builder()
        .name(asset_name)
        .build();

    tracing::info!(asset_name, bytes = file_size, "Uploading asset");

    let result = api
        .repos
        .upload_release_asset(owner, repo, release.id)
        .query(&query)
        .header("Content-Type", "application/octet-stream")
        .header("Content-Length", file_size.to_string())
        .file(file)
        .send()
        .await
        .map_err(|e| anyhow::anyhow!("Failed to upload asset '{}': {}", asset_name, e))?;

    println!("Successfully uploaded release asset:");
    println!("  Asset: {}", result.name);
    println!("  URL:   {}", result.browser_download_url);

    Ok(())
}

fn run_build(
    input: &std::path::Path,
    name: Option<&str>,
    target: Option<&str>,
    dry_run: bool,
) -> Result<()> {
    let cargo_toml = input.join("Cargo.toml");
    if !cargo_toml.exists() {
        anyhow::bail!(
            "No Cargo.toml found in input directory: {}",
            input.display()
        );
    }

    let binary_name = match name {
        Some(n) => n.to_string(),
        None => read_crate_name(input)?,
    };

    let mut cargo_args = vec!["build", "--release"];
    if let Some(t) = target {
        cargo_args.extend(["--target", t]);
    }

    let binary_dir = match target {
        Some(t) => input.join("target").join(t).join("release"),
        None => input.join("target").join("release"),
    };
    let binary_path = binary_dir.join(&binary_name);

    if dry_run {
        println!("Would run: cargo {}", cargo_args.join(" "));
        println!("  Input:  {}", input.display());
        println!("  Binary: {}", binary_path.display());
        return Ok(());
    }

    tracing::info!(input = %input.display(), binary = %binary_path.display(), "Compiling MCP server");
    println!("Compiling MCP server...");
    let status = std::process::Command::new("cargo")
        .args(&cargo_args)
        .current_dir(input)
        .status()
        .map_err(|e| anyhow::anyhow!("Failed to run cargo: {}", e))?;

    if !status.success() {
        anyhow::bail!(
            "cargo build failed. Source code is available at: {}",
            input.display()
        );
    }

    println!("Successfully compiled MCP server:");
    println!("  Binary: {}", binary_path.display());

    Ok(())
}

fn read_crate_name(input: &std::path::Path) -> Result<String> {
    let content = std::fs::read_to_string(input.join("Cargo.toml"))
        .map_err(|e| anyhow::anyhow!("Failed to read Cargo.toml: {}", e))?;
    parse_package_name(&content)
        .ok_or_else(|| anyhow::anyhow!("Could not find [package] name in Cargo.toml"))
}

/// Extract the `name` field from the `[package]` section of a Cargo.toml string.
fn parse_package_name(toml: &str) -> Option<String> {
    let mut in_package = false;
    for line in toml.lines() {
        let trimmed = line.trim();
        if trimmed == "[package]" {
            in_package = true;
        } else if trimmed.starts_with('[') {
            in_package = false;
        } else if in_package {
            if let Some(name) = parse_name_assignment(trimmed) {
                return Some(name);
            }
        }
    }
    None
}

/// Parse a `name = "value"` assignment line, returning the unquoted value.
fn parse_name_assignment(line: &str) -> Option<String> {
    let rest = line.strip_prefix("name")?;
    let rest = rest.trim().strip_prefix('=')?;
    let name = rest.trim().trim_matches('"').trim_matches('\'').to_string();
    (!name.is_empty()).then_some(name)
}

/// Walk up from `start` looking for a `.git` directory.
fn find_git_root(start: &std::path::Path) -> Result<std::path::PathBuf> {
    // Canonicalise first: a relative path like "src/@orb.yml" would otherwise
    // produce Path("") when walking up past "src", and "" cannot be
    // canonicalised.  That propagates as an absolute orb_path_relative which
    // makes worktree.join() ignore the worktree entirely.
    let start = start
        .canonicalize()
        .map_err(|e| anyhow::anyhow!("Cannot access orb path '{}': {}", start.display(), e))?;
    let mut dir = if start.is_file() {
        start.parent().unwrap_or(&start).to_path_buf()
    } else {
        start.to_path_buf()
    };
    loop {
        if dir.join(".git").exists() {
            return Ok(dir);
        }
        match dir.parent() {
            Some(p) => dir = p.to_path_buf(),
            None => anyhow::bail!(
                "Could not find git repository root starting from '{}'",
                start.display()
            ),
        }
    }
}

/// Derive orb name from the orb path.
///
/// For unpacked orbs (`@orb.yml`), uses the project directory name.
/// Handles the common `project/src/@orb.yml` structure by skipping the `src`
/// directory. For packed orbs, uses the file stem (filename without extension).
fn derive_orb_name(path: &std::path::Path) -> String {
    let filename = path.file_name().and_then(|s| s.to_str()).unwrap_or("orb");

    if filename == "@orb.yml" {
        // Get parent directory
        let parent = path.parent();
        let parent_name = parent.and_then(|p| p.file_name()).and_then(|s| s.to_str());

        // If parent is "src", go up one more level to get project name
        if parent_name == Some("src") {
            parent
                .and_then(|p| p.parent())
                .and_then(|p| p.file_name())
                .and_then(|s| s.to_str())
                .unwrap_or("orb")
                .to_string()
        } else {
            parent_name.unwrap_or("orb").to_string()
        }
    } else {
        // Use filename without extension
        path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("orb")
            .to_string()
    }
}

/// Discover the latest version tag in a git repository with the given prefix.
///
/// Returns `None` when no matching tags exist. On error (e.g. not a git repo),
/// returns `Ok(None)` rather than propagating so callers fall through to the
/// next resolution strategy.
fn discover_latest_version(repo: &std::path::Path, tag_prefix: &str) -> Result<Option<String>> {
    use primer::discover_tags;
    let tags = discover_tags(repo, tag_prefix).unwrap_or_default();
    // discover_tags returns versions sorted ascending; highest is last
    Ok(tags.into_iter().last())
}

/// Resolve the version to use for the generated MCP server.
///
/// # Version Resolution Rules (priority order)
///
/// 1. Explicit `--version` — always wins
/// 2. `git_hint` — version auto-discovered from git tags via `--git-repo`
/// 3. Fresh generation with no hints — `DEFAULT_VERSION`
/// 4. Existing output with no version — error (must specify `--version`)
///
/// The `--force` flag is required when overwriting existing output.
fn resolve_version(
    output: &std::path::Path,
    version: Option<&str>,
    force: bool,
    git_hint: Option<&str>,
) -> Result<String> {
    let cargo_toml = output.join("Cargo.toml");
    let output_exists = cargo_toml.exists();

    // Explicit version always wins (with force check if output exists)
    if let Some(v) = version {
        if output_exists && !force {
            anyhow::bail!(
                "Output directory '{}' already exists. Use --force to overwrite.",
                output.display()
            );
        }
        tracing::debug!("Using provided version");
        return Ok(v.to_string());
    }

    // Git-discovered version
    if let Some(v) = git_hint {
        if output_exists && !force {
            anyhow::bail!(
                "Output directory '{}' already exists. Use --force to overwrite.",
                output.display()
            );
        }
        tracing::debug!(version = %v, "Using git-discovered version");
        return Ok(v.to_string());
    }

    // No version available — refuse to generate with an unknown version
    let msg = if output_exists {
        format!(
            "Output directory '{}' already exists and no version could be determined.\n\
             Provide the version explicitly:\n\n\
             \x20   gen-orb-mcp generate --orb-path <PATH> --output {} --version <VERSION> --force\n\n\
             Or ensure --orb-path is inside a git repository with version tags (e.g. v6.0.0).\n\
             Use --tag-prefix if your tags use a non-standard prefix.",
            output.display(),
            output.display()
        )
    } else {
        format!(
            "No version could be determined for the generated MCP server.\n\
             Provide the version explicitly:\n\n\
             \x20   gen-orb-mcp generate --orb-path <PATH> --output {} --version <VERSION>\n\n\
             Or ensure --orb-path is inside a git repository with version tags (e.g. v6.0.0).\n\
             Use --tag-prefix if your tags use a non-standard prefix.",
            output.display()
        )
    };
    anyhow::bail!(msg)
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn test_cli_parse_generate() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_generate_with_version() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--version",
            "1.2.3",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_generate_with_force() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--version",
            "1.2.3",
            "--force",
        ]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_cli_parse_validate() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "validate", "--orb-path", "test.yml"]);
        assert!(cli.is_ok());
    }

    #[test]
    fn test_derive_orb_name_from_orb_yml() {
        use std::path::Path;
        // Standard orb structure: project/src/@orb.yml -> "project"
        let path = Path::new("/path/to/my-toolkit/src/@orb.yml");
        assert_eq!(derive_orb_name(path), "my-toolkit");

        // Non-standard structure without src: my-orb/@orb.yml -> "my-orb"
        let path = Path::new("my-orb/@orb.yml");
        assert_eq!(derive_orb_name(path), "my-orb");

        // Edge case: src/@orb.yml at root -> "orb" (no grandparent, falls back to
        // default)
        let path = Path::new("src/@orb.yml");
        assert_eq!(derive_orb_name(path), "orb");
    }

    #[test]
    fn test_derive_orb_name_from_packed() {
        use std::path::Path;
        let path = Path::new("/path/to/my-toolkit.yml");
        assert_eq!(derive_orb_name(path), "my-toolkit");

        let path = Path::new("orb.yml");
        assert_eq!(derive_orb_name(path), "orb");
    }

    #[test]
    fn test_resolve_version_fresh_with_explicit() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), Some("2.0.0"), false, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "2.0.0");
    }

    #[test]
    fn test_resolve_version_fresh_no_version_errors() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), None, false, None);
        assert!(result.is_err());
    }

    #[test]
    fn test_resolve_version_existing_without_version_fails() {
        let temp_dir = TempDir::new().unwrap();
        // Create a Cargo.toml to simulate existing output
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), None, false, None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("already exists"));
        assert!(err.contains("--version"));
    }

    #[test]
    fn test_resolve_version_existing_with_version_no_force_fails() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), Some("1.5.0"), false, None);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("--force"));
    }

    #[test]
    fn test_resolve_version_existing_with_version_and_force_succeeds() {
        let temp_dir = TempDir::new().unwrap();
        std::fs::write(
            temp_dir.path().join("Cargo.toml"),
            "[package]\nname = \"test\"",
        )
        .unwrap();

        let result = resolve_version(temp_dir.path(), Some("1.5.0"), true, None);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "1.5.0");
    }

    #[test]
    fn test_cli_parse_generate_with_prior_versions() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--prior-versions",
            "./prior",
        ]);
        assert!(cli.is_ok(), "expected --prior-versions flag to be accepted");
    }

    // Tests 11-15: prime command CLI parsing

    #[test]
    fn test_cli_parse_prime_defaults() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime"]);
        assert!(cli.is_ok(), "prime with all defaults should parse");
        if let Commands::Prime {
            orb_path,
            tag_prefix,
            earliest_version,
            since,
            prior_versions_dir,
            migrations_dir,
            rename_map,
            ephemeral,
            dry_run,
            git_repo,
        } = cli.unwrap().command
        {
            assert_eq!(orb_path.to_str().unwrap(), "src/@orb.yml");
            assert_eq!(tag_prefix, "v");
            assert!(earliest_version.is_none());
            assert!(since.is_none());
            assert_eq!(prior_versions_dir.to_str().unwrap(), "prior-versions");
            assert_eq!(migrations_dir.to_str().unwrap(), "migrations");
            assert!(rename_map.is_empty());
            assert!(!ephemeral);
            assert!(!dry_run);
            assert!(git_repo.is_none());
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_earliest_version() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--earliest-version", "4.1.0"]);
        assert!(cli.is_ok(), "prime --earliest-version should parse");
        if let Commands::Prime {
            earliest_version, ..
        } = cli.unwrap().command
        {
            assert_eq!(earliest_version.as_deref(), Some("4.1.0"));
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_since() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--since", "3 months"]);
        assert!(cli.is_ok(), "prime --since should parse");
        if let Commands::Prime { since, .. } = cli.unwrap().command {
            assert_eq!(since.as_deref(), Some("3 months"));
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_exclusive_flags() {
        // --earliest-version and --since are mutually exclusive
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "prime",
            "--earliest-version",
            "4.1.0",
            "--since",
            "6 months",
        ]);
        assert!(
            cli.is_err(),
            "prime with both --earliest-version and --since should be rejected"
        );
    }

    #[test]
    fn test_cli_parse_prime_rename_map() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "prime",
            "--rename-map",
            "common_tests_rolling=common_tests",
            "--rename-map",
            "required_builds_rolling=required_builds",
        ]);
        assert!(cli.is_ok(), "prime --rename-map should parse");
        if let Commands::Prime { rename_map, .. } = cli.unwrap().command {
            assert_eq!(rename_map.len(), 2);
            assert!(rename_map.contains(&"common_tests_rolling=common_tests".to_string()));
            assert!(rename_map.contains(&"required_builds_rolling=required_builds".to_string()));
        } else {
            panic!("expected Prime variant");
        }
    }

    #[test]
    fn test_cli_parse_prime_ephemeral() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "prime", "--ephemeral"]);
        assert!(cli.is_ok(), "prime --ephemeral should parse");
        if let Commands::Prime { ephemeral, .. } = cli.unwrap().command {
            assert!(ephemeral);
        } else {
            panic!("expected Prime variant");
        }
    }

    // Serialises tests that mutate the global CWD.
    static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    /// Regression test: `find_git_root` with a *relative* orb path must return
    /// an **absolute** path.
    ///
    /// When the user runs `gen-orb-mcp prime --orb-path src/@orb.yml` (the
    /// default), `orb_path` is relative.  `find_git_root` walks up from
    /// `src/@orb.yml` → `src` → `""` (Rust `Path::parent` of `"src"` is `""`).
    /// If the function returns `""`, `repo_abs` cannot be canonicalised, so
    /// `strip_prefix("")` on the absolute `orb_abs` returns the full absolute
    /// path.  `worktree.join(absolute_path)` then ignores the worktree and reads
    /// the current working copy — producing snapshots with current-version
    /// content for every historical tag.
    ///
    /// The fix: canonicalise `start` at the top of `find_git_root` so the
    /// walk-up always operates on absolute paths and returns an absolute result.
    #[test]
    fn test_find_git_root_returns_absolute_path_for_relative_input() {
        let _cwd_guard = CWD_LOCK.lock().unwrap();
        let original = std::env::current_dir().unwrap();

        let tmp = TempDir::new().unwrap();
        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();
        std::fs::create_dir_all(tmp.path().join("src")).unwrap();
        std::fs::write(
            tmp.path().join("src").join("@orb.yml"),
            "version: 2.1\ndescription: test",
        )
        .unwrap();

        // Change to the fake repo root so that "src/@orb.yml" is a valid
        // relative path.
        std::env::set_current_dir(tmp.path()).unwrap();

        let result = find_git_root(std::path::Path::new("src/@orb.yml"));

        // Always restore CWD before asserting so a failure doesn't leave the
        // process in the tmp directory.
        std::env::set_current_dir(&original).unwrap();

        let result = result.expect("find_git_root should succeed");
        assert!(
            result.is_absolute(),
            "find_git_root must return an absolute path, got: {:?}",
            result
        );
        assert_eq!(
            result.canonicalize().unwrap(),
            tmp.path().canonicalize().unwrap(),
        );
    }

    // --- Tests for discover_latest_version ---

    #[test]
    fn test_discover_latest_version_returns_none_for_no_tags() {
        let tmp = TempDir::new().unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        let result = discover_latest_version(tmp.path(), "v");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), None);
    }

    #[test]
    fn test_discover_latest_version_returns_highest_semver_tag() {
        let tmp = TempDir::new().unwrap();
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        std::fs::write(tmp.path().join("README.md"), "test").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(tmp.path())
            .output()
            .unwrap();
        for tag in ["v1.0.0", "v2.0.0", "v1.5.0"] {
            std::process::Command::new("git")
                .args(["tag", tag])
                .current_dir(tmp.path())
                .output()
                .unwrap();
        }
        let result = discover_latest_version(tmp.path(), "v");
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), Some("2.0.0".to_string()));
    }

    #[test]
    fn test_resolve_version_uses_git_hint_when_no_explicit_version() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), None, false, Some("3.1.0"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "3.1.0");
    }

    #[test]
    fn test_resolve_version_explicit_overrides_git_hint() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), Some("5.0.0"), false, Some("3.1.0"));
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "5.0.0");
    }

    #[test]
    fn test_resolve_version_errors_without_version_or_hint() {
        let temp_dir = TempDir::new().unwrap();
        let result = resolve_version(temp_dir.path(), None, false, None);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(msg.contains("No version could be determined"), "got: {msg}");
    }

    #[test]
    fn test_cli_parse_generate_with_tag_prefix() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
            "--tag-prefix",
            "orb-v",
        ]);
        assert!(cli.is_ok(), "generate --tag-prefix should parse");
        if let Commands::Generate { tag_prefix, .. } = cli.unwrap().command {
            assert_eq!(tag_prefix, "orb-v");
        } else {
            panic!("expected Generate variant");
        }
    }

    #[test]
    fn test_cli_parse_generate_tag_prefix_defaults_to_v() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "generate",
            "--orb-path",
            "test.yml",
            "--output",
            "./out",
        ]);
        assert!(cli.is_ok());
        if let Commands::Generate { tag_prefix, .. } = cli.unwrap().command {
            assert_eq!(tag_prefix, "v");
        } else {
            panic!("expected Generate variant");
        }
    }

    // --- save subcommand tests ---

    fn init_git_repo(dir: &std::path::Path) {
        std::process::Command::new("git")
            .args(["init"])
            .current_dir(dir)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.email", "test@test.com"])
            .current_dir(dir)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["config", "user.name", "Test"])
            .current_dir(dir)
            .output()
            .unwrap();
        // Initial commit so HEAD exists
        std::fs::write(dir.join("README.md"), "test").unwrap();
        std::process::Command::new("git")
            .args(["add", "."])
            .current_dir(dir)
            .output()
            .unwrap();
        std::process::Command::new("git")
            .args(["commit", "-m", "init"])
            .current_dir(dir)
            .output()
            .unwrap();
    }

    #[test]
    fn test_save_clean_tree_exits_without_commit() {
        let dir = TempDir::new().unwrap();
        init_git_repo(dir.path());
        let _cwd_guard = CWD_LOCK.lock().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        // Stage the path we already committed — tree is clean after staging
        let result = run_save(
            &[std::path::PathBuf::from("README.md")],
            "chore: test",
            false,
            false,
        );
        std::env::set_current_dir(&original).unwrap();
        assert!(
            result.is_ok(),
            "clean tree should exit 0 without creating a commit: {result:?}"
        );
    }

    #[test]
    fn test_save_changed_path_creates_commit() {
        let dir = TempDir::new().unwrap();
        init_git_repo(dir.path());
        std::fs::write(dir.path().join("new-file.txt"), "hello").unwrap();
        let _cwd_guard = CWD_LOCK.lock().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        let result = run_save(
            &[std::path::PathBuf::from("new-file.txt")],
            "chore: add generated file",
            false,
            false,
        );
        std::env::set_current_dir(&original).unwrap();
        assert!(
            result.is_ok(),
            "changed path should commit successfully: {result:?}"
        );
        // Verify a commit was created beyond the initial one
        let log = std::process::Command::new("git")
            .args(["log", "--oneline"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        let log_str = String::from_utf8_lossy(&log.stdout);
        assert!(
            log_str.lines().count() >= 2,
            "expected at least 2 commits, got: {log_str}"
        );
    }

    #[test]
    fn test_save_dry_run_does_not_commit() {
        let dir = TempDir::new().unwrap();
        init_git_repo(dir.path());
        std::fs::write(dir.path().join("artifact.txt"), "generated").unwrap();
        let _cwd_guard = CWD_LOCK.lock().unwrap();
        let original = std::env::current_dir().unwrap();
        std::env::set_current_dir(dir.path()).unwrap();
        let result = run_save(
            &[std::path::PathBuf::from("artifact.txt")],
            "chore: generated",
            false,
            true,
        );
        std::env::set_current_dir(&original).unwrap();
        assert!(result.is_ok(), "dry_run should succeed: {result:?}");
        // Only the initial commit should exist
        let log = std::process::Command::new("git")
            .args(["log", "--oneline"])
            .current_dir(dir.path())
            .output()
            .unwrap();
        let log_str = String::from_utf8_lossy(&log.stdout);
        assert_eq!(
            log_str.lines().count(),
            1,
            "dry_run must not create a commit, got: {log_str}"
        );
    }

    #[test]
    fn test_cli_parse_save_required_paths() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "save",
            "--paths",
            "prior-versions",
            "--paths",
            "migrations",
        ]);
        assert!(cli.is_ok(), "save with --paths should parse");
    }

    #[test]
    fn test_cli_parse_save_all_flags() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "save",
            "--paths",
            "prior-versions",
            "--message",
            "custom message",
            "--no-push",
            "--dry-run",
        ]);
        assert!(cli.is_ok(), "save with all flags should parse");
        if let Commands::Save {
            paths,
            message,
            no_push,
            dry_run,
            ..
        } = cli.unwrap().command
        {
            assert_eq!(paths, vec![std::path::PathBuf::from("prior-versions")]);
            assert_eq!(message, "custom message");
            assert!(no_push);
            assert!(dry_run);
        } else {
            panic!("expected Save variant");
        }
    }

    // --- publish subcommand tests ---

    #[test]
    fn test_publish_missing_binary_returns_error() {
        let dir = TempDir::new().unwrap();
        let result = run_publish(
            &dir.path().join("missing-binary"),
            "asset.tar.gz",
            None,
            false,
        );
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("Binary not found"),
            "error should mention missing binary, got: {msg}"
        );
    }

    #[test]
    fn test_publish_dry_run_with_missing_token_returns_error() {
        let dir = TempDir::new().unwrap();
        let binary = dir.path().join("my-binary");
        std::fs::write(&binary, b"fake binary").unwrap();
        // dry_run without GITHUB_TOKEN should fail before attempting any API call
        std::env::remove_var("GITHUB_TOKEN");
        let result = run_publish(&binary, "my-asset", Some("v1.0.0"), true);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("GITHUB_TOKEN"),
            "error should mention GITHUB_TOKEN, got: {msg}"
        );
    }

    #[test]
    fn test_publish_dry_run_missing_tag_returns_error() {
        let dir = TempDir::new().unwrap();
        let binary = dir.path().join("my-binary");
        std::fs::write(&binary, b"fake binary").unwrap();
        std::env::set_var("GITHUB_TOKEN", "fake-token");
        std::env::remove_var("CIRCLE_TAG");
        // no --tag and no CIRCLE_TAG — should fail with a clear message
        let result = run_publish(&binary, "my-asset", None, true);
        std::env::remove_var("GITHUB_TOKEN");
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("tag") || msg.contains("CIRCLE_TAG"),
            "error should mention tag or CIRCLE_TAG, got: {msg}"
        );
    }

    #[test]
    fn test_publish_dry_run_prints_parameters() {
        let dir = TempDir::new().unwrap();
        let binary = dir.path().join("my-binary");
        std::fs::write(&binary, b"fake binary").unwrap();
        std::env::set_var("GITHUB_TOKEN", "fake-token");
        std::env::set_var("CIRCLE_PROJECT_USERNAME", "jerus-org");
        std::env::set_var("CIRCLE_PROJECT_REPONAME", "my-orb");
        let result = run_publish(&binary, "my-asset-linux-x86_64", Some("v1.0.0"), true);
        std::env::remove_var("GITHUB_TOKEN");
        std::env::remove_var("CIRCLE_PROJECT_USERNAME");
        std::env::remove_var("CIRCLE_PROJECT_REPONAME");
        assert!(
            result.is_ok(),
            "dry_run with all params should succeed: {result:?}"
        );
    }

    #[test]
    fn test_cli_parse_publish_required_args() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "publish",
            "--binary",
            "/tmp/my-binary",
            "--asset-name",
            "my-binary-linux-x86_64",
        ]);
        assert!(cli.is_ok(), "publish with required args should parse");
    }

    #[test]
    fn test_cli_parse_publish_all_flags() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "publish",
            "--binary",
            "/tmp/my-binary",
            "--asset-name",
            "my-binary-linux-x86_64",
            "--tag",
            "v2.0.0",
            "--dry-run",
        ]);
        assert!(cli.is_ok(), "publish with all flags should parse");
        if let Commands::Publish {
            binary,
            asset_name,
            tag,
            dry_run,
        } = cli.unwrap().command
        {
            assert_eq!(binary.to_str().unwrap(), "/tmp/my-binary");
            assert_eq!(asset_name, "my-binary-linux-x86_64");
            assert_eq!(tag.as_deref(), Some("v2.0.0"));
            assert!(dry_run);
        } else {
            panic!("expected Publish variant");
        }
    }

    // --- build subcommand tests ---

    fn write_cargo_toml(dir: &std::path::Path, name: &str) {
        std::fs::write(
            dir.join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2021\"\n"),
        )
        .unwrap();
    }

    #[test]
    fn test_build_missing_cargo_toml_returns_error() {
        let dir = TempDir::new().unwrap();
        let result = run_build(dir.path(), None, None, false);
        assert!(result.is_err());
        let msg = result.unwrap_err().to_string();
        assert!(
            msg.contains("Cargo.toml"),
            "error should mention Cargo.toml, got: {msg}"
        );
    }

    #[test]
    fn test_build_dry_run_does_not_invoke_cargo() {
        let dir = TempDir::new().unwrap();
        write_cargo_toml(dir.path(), "my-server");
        // Not a valid Rust project — cargo would fail if invoked.
        // With dry_run=true the function must succeed without running cargo.
        let result = run_build(dir.path(), None, None, true);
        assert!(
            result.is_ok(),
            "dry_run should succeed without invoking cargo: {result:?}"
        );
    }

    #[test]
    fn test_build_name_override_accepted_in_dry_run() {
        let dir = TempDir::new().unwrap();
        write_cargo_toml(dir.path(), "my-server");
        let result = run_build(dir.path(), Some("custom-name"), None, true);
        assert!(
            result.is_ok(),
            "name override + dry_run should succeed: {result:?}"
        );
    }

    #[test]
    fn test_build_target_triple_accepted_in_dry_run() {
        let dir = TempDir::new().unwrap();
        write_cargo_toml(dir.path(), "my-server");
        let result = run_build(dir.path(), None, Some("x86_64-unknown-linux-musl"), true);
        assert!(
            result.is_ok(),
            "target + dry_run should succeed: {result:?}"
        );
    }

    #[test]
    fn test_parse_package_name_extracts_name() {
        let toml = "[package]\nname = \"my-orb-mcp\"\nversion = \"0.1.0\"\n";
        assert_eq!(
            parse_package_name(toml),
            Some("my-orb-mcp".to_string()),
            "should extract package name"
        );
    }

    #[test]
    fn test_parse_package_name_stops_at_next_section() {
        let toml = "[package]\nname = \"my-orb-mcp\"\n[dependencies]\nname = \"ignored\"\n";
        assert_eq!(parse_package_name(toml), Some("my-orb-mcp".to_string()));
    }

    #[test]
    fn test_parse_package_name_returns_none_when_absent() {
        let toml = "[dependencies]\nanyhow = \"1\"\n";
        assert_eq!(parse_package_name(toml), None);
    }

    #[test]
    fn test_read_crate_name_from_file() {
        let dir = TempDir::new().unwrap();
        write_cargo_toml(dir.path(), "test-crate");
        let result = read_crate_name(dir.path());
        assert!(result.is_ok(), "read_crate_name should succeed: {result:?}");
        assert_eq!(result.unwrap(), "test-crate");
    }

    #[test]
    fn test_cli_parse_build_required_input() {
        let cli = Cli::try_parse_from(["gen-orb-mcp", "build", "--input", "/tmp/my-server"]);
        assert!(cli.is_ok(), "build --input should parse");
    }

    #[test]
    fn test_cli_parse_build_all_flags() {
        let cli = Cli::try_parse_from([
            "gen-orb-mcp",
            "build",
            "--input",
            "/tmp/my-server",
            "--name",
            "my_server",
            "--target",
            "x86_64-unknown-linux-musl",
            "--dry-run",
        ]);
        assert!(cli.is_ok(), "build with all flags should parse");
        if let Commands::Build {
            input,
            name,
            target,
            dry_run,
        } = cli.unwrap().command
        {
            assert_eq!(input.to_str().unwrap(), "/tmp/my-server");
            assert_eq!(name.as_deref(), Some("my_server"));
            assert_eq!(target.as_deref(), Some("x86_64-unknown-linux-musl"));
            assert!(dry_run);
        } else {
            panic!("expected Build variant");
        }
    }
}