devflow-core 2.6.0

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

use crate::git::git_command;
use std::path::{Path, PathBuf};

/// A semantic version, whether read from disk or computed from git history.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Version {
    /// Major version component.
    pub major: u32,
    /// Minor version component.
    pub minor: u32,
    /// Patch version component.
    pub patch: u32,
}

impl std::fmt::Display for Version {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}.{}.{}", self.major, self.minor, self.patch)
    }
}

/// Errors produced by version operations.
#[derive(Debug, thiserror::Error)]
pub enum VersionError {
    /// Filesystem operation failed.
    #[error("version file I/O failed: {0}")]
    Io(#[from] std::io::Error),
    /// Version field could not be found or parsed.
    #[error("version parse failed: {0}")]
    Parse(String),
    /// A git command failed.
    #[error("git command failed: {0}")]
    Git(String),
    /// D-10: the highest semver tag in the repository is not reachable from
    /// `HEAD` — refuse rather than silently computing a version below the
    /// real release history (T-25-04). Typically means a `develop` -> `main`
    /// sync was squashed instead of merged (999.52), or the tag was created
    /// on an orphan ref never merged anywhere.
    #[error(
        "highest semver tag `{tag}` is not reachable from HEAD — merge its branch into \
         the current branch (or, if a develop/main sync was squashed instead of merged, \
         re-run `scripts/sync-main-to-develop.sh`), then retry"
    )]
    UnreachableBaseline {
        /// The unreachable tag's name (e.g. `"v9.9.9"`).
        tag: String,
    },
}

/// Detect the project's version file, checking Cargo.toml, then pyproject.toml,
/// then package.json. Returns the first that exists.
pub fn detect_version_file(project_root: &Path) -> Option<PathBuf> {
    for name in ["Cargo.toml", "pyproject.toml", "package.json"] {
        let path = project_root.join(name);
        if path.exists() {
            return Some(path);
        }
    }
    None
}

/// The dotted field path that holds the version in a given file.
fn field_for(path: &Path, contents: &str) -> &'static str {
    match path.file_name().and_then(|n| n.to_str()) {
        Some("Cargo.toml") => {
            if contents.contains("[workspace.package]") {
                "workspace.package.version"
            } else {
                "package.version"
            }
        }
        Some("pyproject.toml") => "project.version",
        Some("package.json") => "version",
        _ => "version",
    }
}

/// Read the MAJOR version component from a version file.
pub fn read_major_version(path: &Path) -> Result<u32, VersionError> {
    let contents = std::fs::read_to_string(path)?;
    let field = field_for(path, &contents);
    let version = find_version_in_contents(&contents, field)
        .ok_or_else(|| VersionError::Parse(format!("field `{field}` not found in {path:?}")))?;
    let major = version
        .split(['.', '+', '-'])
        .next()
        .unwrap_or("0")
        .parse::<u32>()
        .map_err(|err| VersionError::Parse(format!("invalid major in `{version}`: {err}")))?;
    Ok(major)
}

/// Count all git tags.
///
/// **Superseded (D-07):** `compute_version` no longer derives MINOR from a
/// raw tag count — use [`reachable_semver_baseline`] instead. Retained
/// (rather than deleted) because `devflow-core` has no `publish = false` and
/// this function is `pub`, so removal would be a breaking API change of a
/// published crate (same reasoning CONTEXT.md D-13 records for
/// `looks_like_devflow_process`).
#[deprecated(note = "superseded by `reachable_semver_baseline` (D-07)")]
pub fn count_git_tags(project_root: &Path) -> Result<u32, VersionError> {
    let output = git_command(project_root)
        .arg("tag")
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    let count = String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter(|l| !l.trim().is_empty())
        .count();
    Ok(count as u32)
}

/// Count commits since the most recent tag. If there are no tags yet, counts
/// all commits reachable from HEAD.
///
/// **Superseded (D-08):** `compute_version` no longer derives PATCH from
/// `git describe` distance — use [`classify_range_bump`] over
/// [`release_range_start`]'s anchored range instead. Retained (rather than
/// deleted) for the same published-crate-API reason as
/// [`count_git_tags`]'s doc comment.
#[deprecated(note = "superseded by `classify_range_bump` (D-08)")]
pub fn commits_since_last_minor_tag(project_root: &Path) -> Result<u32, VersionError> {
    let last_tag = git_command(project_root)
        .args(["describe", "--tags", "--abbrev=0"])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;

    let range = if last_tag.status.success() {
        let tag = String::from_utf8_lossy(&last_tag.stdout).trim().to_string();
        format!("{tag}..HEAD")
    } else {
        "HEAD".to_string()
    };

    let output = git_command(project_root)
        .args(["rev-list", "--count", &range])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        // No commits yet (e.g. empty repo) → zero patch.
        return Ok(0);
    }
    let count = String::from_utf8_lossy(&output.stdout)
        .trim()
        .parse::<u32>()
        .unwrap_or(0);
    Ok(count)
}

/// Enumerate every tag in the repository (no reachability restriction), keep
/// only values that parse as `vMAJOR.MINOR.PATCH` semver (a leading `v` is
/// stripped first — the `semver` crate's grammar is bare `MAJOR.MINOR.PATCH`),
/// and return the maximum by semver ordering (D-07). A stray non-semver tag
/// (e.g. this repository's `archive-planning-docs-2026-07-24`) is silently
/// excluded via `filter_map(...ok())` rather than erroring — a malformed tag
/// can never crash this path (T-25-02).
pub fn highest_semver_tag(project_root: &Path) -> Result<Option<semver::Version>, VersionError> {
    let output = git_command(project_root)
        .arg("tag")
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| line.trim().strip_prefix('v'))
        .filter_map(|stripped| semver::Version::parse(stripped).ok())
        .max())
}

/// As [`highest_semver_tag`], but restricted to tags reachable from `HEAD`
/// via `git tag --merged HEAD` — one spawn instead of an O(n) per-tag
/// `merge-base --is-ancestor` loop, mirroring `GitFlow::cleanup_merged`'s
/// existing `branch --merged` precedent in `git.rs`. This is `compute_version`'s
/// baseline (D-07).
///
/// **D-12 coupling:** this predicate's correctness depends on the `develop`
/// → `main` sync PR being MERGED, not squashed — a squashed sync breaks the
/// ancestry link this `--merged` check relies on. `compute_version`'s
/// refusal (D-10, `VersionError::UnreachableBaseline`) is the mitigation if
/// that discipline is ever violated; 999.52 is the backlog item that would
/// ship a structural repair, deliberately not in this phase.
pub fn reachable_semver_baseline(
    project_root: &Path,
) -> Result<Option<semver::Version>, VersionError> {
    let output = git_command(project_root)
        .args(["tag", "--merged", "HEAD"])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    Ok(String::from_utf8_lossy(&output.stdout)
        .lines()
        .filter_map(|line| line.trim().strip_prefix('v'))
        .filter_map(|stripped| semver::Version::parse(stripped).ok())
        .max())
}

/// Resolve `commit`'s first parent SHA, or `Ok(None)` if `commit` is a root
/// commit with no first parent.
///
/// A non-zero exit from `git rev-parse {commit}^1` means "no such parent"
/// (root commit), not a genuine spawn/IO failure — those still propagate
/// via `?` through the `Command::output()` call itself.
fn first_parent(project_root: &Path, commit: &str) -> Result<Option<String>, VersionError> {
    let output = git_command(project_root)
        .args(["rev-parse", &format!("{commit}^1")])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Ok(None);
    }
    Ok(Some(
        String::from_utf8_lossy(&output.stdout).trim().to_string(),
    ))
}

/// Resolve the commit range start for D-08's conventional-commit classifier,
/// given the baseline tag name (e.g. `"v2.0.0"`).
///
/// This exists because every release in this repository squash-merges
/// `develop` into `main`, so no develop-side commit is ever an ancestor of
/// the release tag it was squashed into — a `-X ours` sync merge-back
/// restores ancestry in the OTHER direction only (the tag becomes an
/// ancestor of `HEAD`, which is what makes D-07's `--merged HEAD`
/// reachability filter work), but the commits the tag *released* stay
/// outside its ancestry forever. A literal `baseline..HEAD` range therefore
/// re-includes the entire pre-release history on every subsequent ship —
/// measured live 2026-07-27: `v2.0.0..HEAD` is 677 non-merge commits (62
/// `feat`), against 5 (0 `feat`) for the anchored range this function
/// computes. See 25-01-PLAN.md's `<measured_correction>`.
///
/// Anchor rule (generalized 2026-07-28 to fix CR-03 — `25-REVIEW.md`,
/// `25-VERIFICATION.md` GAP 2):
/// - Walk `git rev-list --ancestry-path --reverse <tag>..HEAD` oldest-first.
///   For each candidate commit `C` in order: if `C` has no first parent (a
///   root commit), or the baseline tag is NOT an ancestor of `C`'s first
///   parent, `C` is where the tag's line joined `HEAD`'s line — return `C`
///   immediately.
/// - If every candidate's first parent already descends from the tag, the
///   tag already sat on this mainline throughout (the ordinary,
///   non-squashed case, e.g. `v1.8.0..v1.8.1`) — return the tag unchanged.
/// - If the ancestry path is empty, the tag is at `HEAD` — return the tag.
///
/// **CR-03** — the previous rule inspected only the ancestry path's FIRST
/// commit (`C1`). When a commit lands directly on trunk between the tag and
/// the sync-merge-back (a hotfix pushed straight to `main`), that
/// intervening commit becomes `C1`; its first parent IS the tag commit, so
/// `merge-base --is-ancestor <tag> <tag>` is trivially true, and the old
/// rule wrongly concluded the tag already sat on mainline — returning the
/// literal `tag..HEAD` range and re-admitting pre-release `develop` history.
/// Walking the FULL path instead of just `C1` fixes this: the sync merge
/// itself still fails the ancestor test and is returned once the walk
/// reaches it.
///
/// **Anchoring at the LAST merge commit instead (a plausible-looking
/// alternative) is WRONG on this repository.** `GitFlow::merge_feature_into_develop`
/// (`git.rs:86`) merges every phase branch into `develop` with `git merge
/// --no-ff`, so ordinary post-release feature work also produces merge
/// commits on the ancestry path — not just the sync-merge-back. Anchoring at
/// the last one would silently truncate the range at that later feature
/// merge instead of the sync merge, dropping any commits between the two
/// from classification — a `feat!:` in that position would be dropped
/// unnoticed, the exact false negative D-09 exists to prevent. See
/// `tests::feature_merge_after_sync_merge_does_not_move_the_anchor`.
pub fn release_range_start(
    project_root: &Path,
    baseline_tag: &str,
) -> Result<String, VersionError> {
    let ancestry = git_command(project_root)
        .args([
            "rev-list",
            "--ancestry-path",
            "--reverse",
            &format!("{baseline_tag}..HEAD"),
        ])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !ancestry.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&ancestry.stderr).trim().to_string(),
        ));
    }
    let path: Vec<String> = String::from_utf8_lossy(&ancestry.stdout)
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(str::to_string)
        .collect();
    if path.is_empty() {
        // Nothing after the tag — it sits at HEAD.
        return Ok(baseline_tag.to_string());
    }

    for candidate in &path {
        let Some(first_parent) = first_parent(project_root, candidate)? else {
            // `candidate` is a root commit with no first parent — the tag
            // cannot be an ancestor of something that doesn't exist; this is
            // where the tag's line joined HEAD's line.
            return Ok(candidate.clone());
        };

        let tag_is_ancestor_of_first_parent = git_command(project_root)
            .args(["merge-base", "--is-ancestor", baseline_tag, &first_parent])
            .output()
            .map(|out| out.status.success())
            .unwrap_or(false);

        if !tag_is_ancestor_of_first_parent {
            // `candidate` is where the tag's line joined HEAD's line (the
            // sync merge-back, or equivalent).
            return Ok(candidate.clone());
        }
        // `candidate` is on the mainline the tag already sat on: keep
        // walking the path toward HEAD.
    }

    // Every candidate's first parent already descended from the tag — the
    // ordinary, non-squashed release case.
    Ok(baseline_tag.to_string())
}

/// The classified conventional-commit bump for a range of commits (D-08).
/// Declaration order is the precedence order (lowest to highest), so
/// `Iterator::max()`/[`Ord::max`] over a range's individual classifications
/// yields the highest-precedence result directly.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum Bump {
    /// No commit's type maps to a version-affecting change (`docs`, `test`,
    /// `chore`, `ci`, `refactor`, `style`). `compute_version` collapses this
    /// to [`Bump::Patch`] at the call site (D-10's floor) so a range with
    /// nothing bumping still yields a distinct version.
    None,
    /// `fix`/`perf`; any recognised-but-unlisted conventional-commit type
    /// (D-10's same floor); or a commit message that failed to parse as a
    /// conventional commit at all (D-10: unrecognised/malformed → patch).
    Patch,
    /// `feat`.
    Minor,
    /// A breaking change: `!` after an optional scope and before the colon
    /// (`feat(scope)!: ...`), or a `BREAKING CHANGE:`/`BREAKING-CHANGE:`
    /// footer, regardless of the commit's own type.
    Major,
}

/// Classify the highest-precedence conventional-commit bump over
/// `--no-merges` commits in `range_start..HEAD`. `range_start` may be the
/// empty string, meaning "no baseline tag exists" — the whole history
/// reachable from `HEAD` is classified instead (`git log --no-merges HEAD`,
/// no exclusion).
///
/// Commits are read via `%H%x1f%B%x1e`: `%B` is the raw message (subject,
/// blank line, body and footers) in exactly the shape
/// `git_conventional::Commit::parse` expects, and `%x1f`/`%x1e` are git's own
/// unit/record separators — safe against arbitrary characters a commit
/// message may contain, unlike splitting on newlines.
pub fn classify_range_bump(project_root: &Path, range_start: &str) -> Result<Bump, VersionError> {
    let range = if range_start.is_empty() {
        "HEAD".to_string()
    } else {
        format!("{range_start}..HEAD")
    };
    let output = git_command(project_root)
        .args(["log", "--no-merges", &range, "--format=%H%x1f%B%x1e"])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut bump = Bump::None;
    for record in stdout.split('\u{1e}') {
        let record = record.trim_matches('\n');
        if record.is_empty() {
            continue;
        }
        let Some((_hash, message)) = record.split_once('\u{1f}') else {
            continue;
        };
        let this_bump = classify_commit_message(message.trim());
        bump = bump.max(this_bump);
    }
    Ok(bump)
}

/// Classify one commit message's bump per D-08/D-10. An unparseable message
/// (D-10: unrecognised/malformed) and a breaking-change marker (regardless of
/// type) are both checked before the type match, since either overrides a
/// recognised type's own precedence.
fn classify_commit_message(message: &str) -> Bump {
    let Ok(commit) = git_conventional::Commit::parse(message) else {
        return Bump::Patch;
    };
    if commit.breaking() {
        return Bump::Major;
    }
    let ty = commit.type_();
    if ty == git_conventional::Type::FEAT {
        Bump::Minor
    } else if ty == git_conventional::Type::FIX || ty == git_conventional::Type::PERF {
        Bump::Patch
    } else if ty == git_conventional::Type::DOCS
        || ty == git_conventional::Type::TEST
        || ty == git_conventional::Type::CHORE
        || ty == "ci"
        || ty == git_conventional::Type::REFACTOR
        || ty == git_conventional::Type::STYLE
    {
        Bump::None
    } else {
        // Any other recognised-but-unlisted type — D-10's same floor.
        Bump::Patch
    }
}

/// Keep-a-Changelog heading a changelog bullet is grouped under (D-12).
/// Declaration order is the render order [`render_changelog_body`] emits
/// sections in: breaking changes first, then what's new, then what's fixed,
/// then everything else.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum ChangelogHeading {
    /// A breaking change (`!` marker or `BREAKING CHANGE:`/`BREAKING-CHANGE:`
    /// footer), regardless of the commit's own type.
    Breaking,
    /// `feat`.
    Added,
    /// `fix`/`perf`.
    Fixed,
    /// Every other conventional-commit type (`docs`, `test`, `chore`, the
    /// string `"ci"`, `refactor`, `style`, or any other recognized-but-
    /// unlisted type), and any message that fails to parse as a
    /// conventional commit at all.
    Changed,
}

impl ChangelogHeading {
    /// This heading's Keep-a-Changelog markdown heading line.
    pub fn as_markdown_heading(self) -> &'static str {
        match self {
            ChangelogHeading::Breaking => "### Breaking",
            ChangelogHeading::Added => "### Added",
            ChangelogHeading::Fixed => "### Fixed",
            ChangelogHeading::Changed => "### Changed",
        }
    }
}

/// Maximum length, in characters, of a sanitized changelog bullet
/// ([`sanitize_changelog_subject`]).
pub const CHANGELOG_SUBJECT_MAX_CHARS: usize = 200;

/// Neutralize and bound a commit-derived changelog bullet before it reaches
/// `CHANGELOG.md` or a `tracing` line (D-12, ASVS V7, T-26-05). Commit
/// subjects are contributor-authored text — the same attacker-influenced
/// class `T-17-13`/`T-25-52` already redact — so every
/// [`char::is_control`] character is mapped to a single space, then, if the
/// result exceeds [`CHANGELOG_SUBJECT_MAX_CHARS`] characters, it is
/// truncated so the returned string is exactly `CHANGELOG_SUBJECT_MAX_CHARS`
/// characters including the trailing `… [truncated]` marker. Mirrors
/// `render_gate_context`'s properties (`pipeline_outcomes.rs:323`) — a
/// sibling, not a shared function, since that one is `pub(crate)` inside
/// `devflow-cli` and not importable from `devflow-core`.
pub fn sanitize_changelog_subject(subject: &str) -> String {
    const MARKER: &str = "… [truncated]";
    let sanitized: String = subject
        .chars()
        .map(|character| {
            if character.is_control() {
                ' '
            } else {
                character
            }
        })
        .collect();
    if sanitized.chars().count() <= CHANGELOG_SUBJECT_MAX_CHARS {
        return sanitized;
    }
    let marker_len = MARKER.chars().count().min(CHANGELOG_SUBJECT_MAX_CHARS);
    let head_len = CHANGELOG_SUBJECT_MAX_CHARS.saturating_sub(marker_len);
    let head: String = sanitized.chars().take(head_len).collect();
    let marker: String = MARKER.chars().take(marker_len).collect();
    format!("{head}{marker}")
}

/// Group `--no-merges` commits in `range_start..HEAD` by [`ChangelogHeading`]
/// (D-12). Walks the identical range and `git log --no-merges <range>
/// --format=%H%x1f%B%x1e` argv as [`classify_range_bump`] (same record
/// separators, same [`git_conventional::Commit::parse`] call) — but, unlike
/// `classify_range_bump` (which folds every commit down to a single
/// aggregate [`Bump`] value; see RESEARCH.md Pitfall 1), *collects* each
/// commit's subject into its group instead of discarding it.
/// `classify_range_bump`'s returned `Bump` is never used as changelog
/// content; this is sibling code, not a wrapper around it.
///
/// **Complete per-type mapping (D-12, Task 2), evaluated in this order:**
/// 1. `git_conventional::Commit::parse` fails → [`ChangelogHeading::Changed`],
///    bullet = the message's first line.
/// 2. `commit.breaking()` is true → [`ChangelogHeading::Breaking`] — checked
///    before the type match, mirroring `classify_commit_message`'s own
///    precedence.
/// 3. type is `feat` → [`ChangelogHeading::Added`].
/// 4. type is `fix`/`perf` → [`ChangelogHeading::Fixed`].
/// 5. every other type (`docs`, `test`, `chore`, `"ci"`, `refactor`, `style`,
///    or any other recognized-but-unlisted type) → [`ChangelogHeading::Changed`].
///
/// **Deliberate divergence from `classify_commit_message`:** an unparseable
/// message is `Bump::Patch` for versioning (D-10's floor — an unrecognized
/// commit still bumps *something*) but `Changed` here — a message with no
/// conventional type has no claim to `Fixed`. Do not "fix" this into
/// agreement; it is intentional.
///
/// Bullets preserve git-log order (newest first) within each group; groups
/// are emitted in [`ChangelogHeading`] declaration order, omitting any group
/// with no bullets. A range with no commits returns `Ok(Vec::new())`.
pub fn changelog_sections(
    project_root: &Path,
    range_start: &str,
) -> Result<Vec<(ChangelogHeading, Vec<String>)>, VersionError> {
    let range = if range_start.is_empty() {
        "HEAD".to_string()
    } else {
        format!("{range_start}..HEAD")
    };
    let output = git_command(project_root)
        .args(["log", "--no-merges", &range, "--format=%H%x1f%B%x1e"])
        .output()
        .map_err(|err| VersionError::Git(err.to_string()))?;
    if !output.status.success() {
        return Err(VersionError::Git(
            String::from_utf8_lossy(&output.stderr).trim().to_string(),
        ));
    }
    let stdout = String::from_utf8_lossy(&output.stdout);
    let mut breaking: Vec<String> = Vec::new();
    let mut added: Vec<String> = Vec::new();
    let mut fixed: Vec<String> = Vec::new();
    let mut changed: Vec<String> = Vec::new();
    for record in stdout.split('\u{1e}') {
        let record = record.trim_matches('\n');
        if record.is_empty() {
            continue;
        }
        let Some((_hash, message)) = record.split_once('\u{1f}') else {
            continue;
        };
        let message = message.trim();
        let Ok(commit) = git_conventional::Commit::parse(message) else {
            let first_line = message.lines().next().unwrap_or(message);
            changed.push(sanitize_changelog_subject(first_line));
            continue;
        };
        let subject = sanitize_changelog_subject(commit.description());
        if commit.breaking() {
            breaking.push(subject);
        } else if commit.type_() == git_conventional::Type::FEAT {
            added.push(subject);
        } else if commit.type_() == git_conventional::Type::FIX
            || commit.type_() == git_conventional::Type::PERF
        {
            fixed.push(subject);
        } else {
            changed.push(subject);
        }
    }
    let mut sections = Vec::new();
    if !breaking.is_empty() {
        sections.push((ChangelogHeading::Breaking, breaking));
    }
    if !added.is_empty() {
        sections.push((ChangelogHeading::Added, added));
    }
    if !fixed.is_empty() {
        sections.push((ChangelogHeading::Fixed, fixed));
    }
    if !changed.is_empty() {
        sections.push((ChangelogHeading::Changed, changed));
    }
    Ok(sections)
}

/// Render `sections` (from [`changelog_sections`]) as Keep-a-Changelog
/// markdown: each section's heading line, a blank line, then one `- {subject}`
/// line per bullet, with a blank line between sections. Returns an empty
/// string when `sections` is empty — the "nothing changed" fallback text is
/// [`crate::ship::prepend_changelog`]'s responsibility, not this function's.
pub fn render_changelog_body(sections: &[(ChangelogHeading, Vec<String>)]) -> String {
    let mut body = String::new();
    for (index, (heading, bullets)) in sections.iter().enumerate() {
        if index > 0 {
            body.push('\n');
        }
        body.push_str(heading.as_markdown_heading());
        body.push_str("\n\n");
        for bullet in bullets {
            body.push_str("- ");
            body.push_str(bullet);
            body.push('\n');
        }
    }
    body
}

/// Apply a classified [`Bump`] to a baseline version (D-08/D-10).
fn apply_bump(baseline: &semver::Version, bump: Bump) -> semver::Version {
    match bump {
        Bump::Major => semver::Version::new(baseline.major + 1, 0, 0),
        Bump::Minor => semver::Version::new(baseline.major, baseline.minor + 1, 0),
        // D-10: no-bump collapses to patch so every completed ship still
        // yields a distinct version.
        Bump::Patch | Bump::None => {
            semver::Version::new(baseline.major, baseline.minor, baseline.patch + 1)
        }
    }
}

/// Compute the full version: the baseline resolved from the highest
/// reachable semver tag (D-07), bumped by the conventional-commit
/// classification of the commits added since that baseline was released
/// (D-08). The version file is NOT read here (D-11) — [`write_version`] is
/// the only writer, and [`read_version`] is the only reader of what's on
/// disk.
pub fn compute_version(project_root: &Path) -> Result<Version, VersionError> {
    let highest = highest_semver_tag(project_root)?;
    let baseline = reachable_semver_baseline(project_root)?;

    // D-10: refuse rather than silently falling back to the highest
    // *reachable* tag when the true highest tag exists but is not reachable
    // from HEAD (T-25-04) — see `reachable_semver_baseline`'s doc comment for
    // the D-12 sync-discipline coupling this predicate depends on.
    if let Some(highest) = &highest {
        let unreachable = match &baseline {
            Some(reachable) => highest > reachable,
            None => true,
        };
        if unreachable {
            return Err(VersionError::UnreachableBaseline {
                tag: format!("v{highest}"),
            });
        }
    }

    let baseline_version = baseline
        .clone()
        .unwrap_or_else(|| semver::Version::new(0, 0, 0));

    let range_start = match &baseline {
        Some(tag) => release_range_start(project_root, &format!("v{tag}"))?,
        None => String::new(),
    };
    let bump = classify_range_bump(project_root, &range_start)?;
    let bumped = apply_bump(&baseline_version, bump);

    Ok(Version {
        major: bumped.major as u32,
        minor: bumped.minor as u32,
        patch: bumped.patch as u32,
    })
}

/// Read the full [`Version`] (major/minor/patch) out of whatever version file
/// `detect_version_file` resolves, mirroring [`write_version`]'s format
/// handling (including `[workspace.package]`).
///
/// Unlike [`compute_version`], this never touches git — it reports exactly
/// what was last written to the version file, not a freshly recomputed
/// minor/patch. Callers that need the version a prior [`write_version`] call
/// actually wrote (e.g. after a tag was just cut) must use this instead of
/// `compute_version`, which would see the new tag and return a different,
/// larger version.
///
/// D-11 changed what `compute_version` reads (git history only, never the
/// version file) — it did not change this function's role: `read_version`
/// still reports exactly what's on disk, unconditionally.
pub fn read_version(project_root: &Path) -> Result<Version, VersionError> {
    let path = detect_version_file(project_root)
        .ok_or_else(|| VersionError::Parse("no version file found".into()))?;
    let contents = std::fs::read_to_string(&path)?;
    let field = field_for(&path, &contents);
    let version_str = find_version_in_contents(&contents, field)
        .ok_or_else(|| VersionError::Parse(format!("field `{field}` not found in {path:?}")))?;
    parse_version_str(&version_str)
}

/// Parse a `MAJOR.MINOR.PATCH` string (optionally followed by `-`/`+`
/// metadata) into a [`Version`].
fn parse_version_str(version: &str) -> Result<Version, VersionError> {
    let mut parts = version.split(['.', '+', '-']);
    let mut next =
        |label: &str| -> Result<u32, VersionError> {
            parts.next().unwrap_or("0").parse::<u32>().map_err(|err| {
                VersionError::Parse(format!("invalid {label} in `{version}`: {err}"))
            })
        };
    let major = next("major")?;
    let minor = next("minor")?;
    let patch = next("patch")?;
    Ok(Version {
        major,
        minor,
        patch,
    })
}

/// Write `version` into the project's auto-detected version file.
pub fn write_version(project_root: &Path, version: &Version) -> Result<PathBuf, VersionError> {
    let path = detect_version_file(project_root)
        .ok_or_else(|| VersionError::Parse("no version file found".into()))?;
    let contents = std::fs::read_to_string(&path)?;
    let field = field_for(&path, &contents);
    let replaced = replace_version_in_contents(&contents, field, &version.to_string())
        .ok_or_else(|| VersionError::Parse(format!("field `{field}` not found")))?;
    // 20a / DEN-49: a workspace Cargo.toml states its version twice — once in
    // [workspace.package] version (just rewritten above), and again as an
    // explicit `version` pin on every [workspace.dependencies] entry that
    // points at a workspace member by `path`. This second pass is additive,
    // not a modification of `replace_version_in_contents`'s single-field
    // logic — pyproject.toml/package.json/plain Cargo.toml callers never
    // reach it.
    let replaced = if field == "workspace.package.version" {
        rewrite_workspace_member_pins(&replaced, &version.to_string())
    } else {
        replaced
    };
    std::fs::write(&path, replaced)?;
    Ok(path)
}

/// Additive pass (20a / DEN-49): rewrite the `version` sub-value of every
/// SINGLE-LINE `[workspace.dependencies]` inline-table entry that pins a
/// local workspace member by `path` (e.g. `devflow-core = { path =
/// "crates/devflow-core", version = "1.6.0" }`).
///
/// This is deliberately additive to `replace_version_in_contents` rather than
/// a modification of it — that function's `starts_with('{')` guard exists so
/// single-field callers (`field_for` for pyproject.toml/package.json/plain
/// Cargo.toml) never touch an inline table, and stays intact.
///
/// Scope, by construction:
/// - Only entries with a local `path` key (one starting with `crates/`) are
///   rewritten. A `version`-only third-party dependency (`serde = { version
///   = "1" }`) is left untouched — a dependency on a crate INSIDE this
///   workspace carries this workspace's version; anything else does not.
/// - Only SINGLE-LINE inline tables are handled (opening and closing `}` on
///   the same line as `path`/`version`). A multi-line inline table is a
///   documented out-of-scope limitation (review: Antigravity/Hermes MEDIUM)
///   — this repo's own self-pins are single-line (Cargo.toml:20), and the
///   line-level `starts_with('{')` guard in `find_version_in_contents`/
///   `replace_version_in_contents` could not see into one anyway.
/// - The `version = "..."` sub-value is located and replaced independent of
///   its position relative to `path` within the line (key-order-independent,
///   anchored to the `version =` token itself, not a column offset) — a
///   self-pin written `{ version = "1.6.0", path = "crates/..." }` is
///   rewritten identically to the `path`-before-`version` case.
/// - Whitespace, quote style, and any trailing comma/comment after the
///   `version` token are preserved exactly (GAP-6).
fn rewrite_workspace_member_pins(contents: &str, new_version: &str) -> String {
    let mut current = String::new();
    let mut output = String::new();
    for line in contents.lines() {
        let trimmed = line.trim();
        if let Some(header) = parse_section_header(trimmed) {
            current = header.to_string();
            output.push_str(line);
            output.push('\n');
            continue;
        }
        if current == "workspace.dependencies"
            && trimmed.contains('{')
            && trimmed.contains('}')
            && workspace_dependency_has_local_path(trimmed)
            && let Some(rewritten) = rewrite_inline_table_version(line, new_version)
        {
            output.push_str(&rewritten);
            output.push('\n');
            continue;
        }
        output.push_str(line);
        output.push('\n');
    }
    output
}

/// Split a single-line inline table's interior (`{ ... }`, braces excluded)
/// into its top-level `key = value` fragments, alongside each fragment's
/// absolute byte offset within `line`. Fragments are separated on `,` — this
/// is a hand-rolled, single-line-only split (see `rewrite_workspace_member_pins`
/// doc comment), not a general TOML parser.
fn inline_table_fragments(line: &str) -> Option<Vec<(usize, &str)>> {
    let brace_start = line.find('{')?;
    let brace_end = line.rfind('}')?;
    if brace_end <= brace_start {
        return None;
    }
    let inner = &line[brace_start + 1..brace_end];
    let mut fragments = Vec::new();
    let mut offset = brace_start + 1;
    for fragment in inner.split(',') {
        fragments.push((offset, fragment));
        offset += fragment.len() + 1; // +1 for the consumed comma
    }
    Some(fragments)
}

/// Whether a `[workspace.dependencies]` inline-table line carries a `path`
/// key whose value points at a local workspace member (starts with
/// `crates/`).
fn workspace_dependency_has_local_path(line: &str) -> bool {
    let Some(fragments) = inline_table_fragments(line) else {
        return false;
    };
    for (_, fragment) in fragments {
        let trimmed = fragment.trim();
        let Some((key, value)) = trimmed.split_once('=') else {
            continue;
        };
        if key.trim() != "path" {
            continue;
        }
        let value = value.trim();
        let Some(quote) = value.chars().next() else {
            return false;
        };
        if quote != '"' && quote != '\'' {
            return false;
        }
        let inner_value = &value[1..value.len().saturating_sub(1)];
        return inner_value.starts_with("crates/");
    }
    false
}

/// Rewrite the `version = "..."` sub-value on a single-line inline-table
/// line, preserving everything else on the line byte-for-byte. Returns
/// `None` if the line has no `version` fragment to anchor to (e.g. a
/// `path`-only member with no explicit version — nothing to rewrite).
fn rewrite_inline_table_version(line: &str, new_version: &str) -> Option<String> {
    let fragments = inline_table_fragments(line)?;
    for (frag_start, fragment) in fragments {
        let trimmed = fragment.trim();
        let Some((key, _value)) = trimmed.split_once('=') else {
            continue;
        };
        if key.trim() != "version" {
            continue;
        }
        // Locate `=` in the ORIGINAL (untrimmed) fragment to compute an
        // absolute offset into `line`.
        let eq_rel = fragment.find('=')?;
        let eq_abs = frag_start + eq_rel;
        let after_eq = eq_abs + 1;
        let rest = &line[after_eq..];
        let ws_len = rest.len() - rest.trim_start().len();
        let value_start = after_eq + ws_len;
        let value_rest = &line[value_start..];
        let quote_char = value_rest.chars().next()?;
        if quote_char != '"' && quote_char != '\'' {
            return None;
        }
        let after_quote = &value_rest[1..];
        let end_rel = after_quote.find(quote_char)?;
        let value_end = value_start + 1 + end_rel + 1;
        let remainder = &line[value_end..];

        let mut rewritten = String::with_capacity(line.len() + new_version.len());
        rewritten.push_str(&line[..value_start]);
        rewritten.push(quote_char);
        rewritten.push_str(new_version);
        rewritten.push(quote_char);
        rewritten.push_str(remainder);
        return Some(rewritten);
    }
    None
}

/// One `[workspace.dependencies]` self-pin discovered by
/// [`read_workspace_self_pins`] — a local-path dependency's name and its
/// pinned `version` sub-value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SelfPin {
    /// The dependency's name (left-hand side of `=` in `[workspace.dependencies]`).
    pub name: String,
    /// The `version = "..."` value currently pinned in the inline table.
    pub version: String,
}

/// Extract `[workspace.package] version` and every local-path
/// `[workspace.dependencies]` self-pin (crate name + pinned version) from a
/// workspace Cargo.toml's contents.
///
/// Read-only (20d / `devflow release --check`): asserts 20a's invariant
/// (`write_version` keeps every self-pin equal to the workspace version)
/// without re-implementing TOML scanning — reuses the same
/// `parse_section_header`/`find_version_in_contents`/
/// `workspace_dependency_has_local_path`/`inline_table_fragments` helpers
/// `write_version`'s additive rewrite pass already uses.
///
/// Returns `(workspace_version, pins)`. `workspace_version` is `None` when
/// the contents have no `[workspace.package] version` field (not a workspace
/// root Cargo.toml) — callers must treat that as "nothing to assert", not a
/// drift.
pub fn read_workspace_self_pins(contents: &str) -> (Option<String>, Vec<SelfPin>) {
    let workspace_version = find_version_in_contents(contents, "workspace.package.version");

    let mut current = String::new();
    let mut pins = Vec::new();
    for line in contents.lines() {
        let trimmed = line.trim();
        if let Some(header) = parse_section_header(trimmed) {
            current = header.to_string();
            continue;
        }
        if current == "workspace.dependencies"
            && trimmed.contains('{')
            && trimmed.contains('}')
            && workspace_dependency_has_local_path(trimmed)
            && let Some(fragments) = inline_table_fragments(trimmed)
        {
            let name = trimmed
                .split_once('=')
                .map(|(n, _)| n.trim().to_string())
                .unwrap_or_default();
            for (_, fragment) in fragments {
                let frag = fragment.trim();
                let Some((key, value)) = frag.split_once('=') else {
                    continue;
                };
                if key.trim() != "version" {
                    continue;
                }
                let value = value.trim().trim_matches(['"', '\'']);
                pins.push(SelfPin {
                    name: name.clone(),
                    version: value.to_string(),
                });
            }
        }
    }
    (workspace_version, pins)
}

/// Split a dotted field path into its TOML section path and the final key.
fn split_field(field: &str) -> (&str, &str) {
    match field.rsplit_once('.') {
        Some((section, key)) => (section, key),
        None => ("", field),
    }
}

/// Return the dotted table path for a TOML section header line, if any.
fn parse_section_header(trimmed: &str) -> Option<&str> {
    let inner = if trimmed.starts_with("[[") && trimmed.ends_with("]]") {
        trimmed.strip_prefix("[[")?.strip_suffix("]]")?
    } else {
        trimmed.strip_prefix('[')?.strip_suffix(']')?
    };
    Some(inner.trim())
}

fn find_version_in_contents(contents: &str, field: &str) -> Option<String> {
    let (section, key) = split_field(field);
    let mut current = "";
    for line in contents.lines() {
        let trimmed = line.trim();
        if let Some(header) = parse_section_header(trimmed) {
            current = header;
            continue;
        }
        if current != section {
            continue;
        }
        if let Some((lhs, value)) = trimmed.split_once(['=', ':']) {
            let lhs_key = lhs.trim().trim_matches('"').trim_matches('\'');
            if lhs_key != key {
                continue;
            }
            let value = value.trim();
            if value.starts_with('{') {
                continue;
            }
            // Anchor on the opening quote and scan forward for the matching
            // closing quote, ignoring everything after it (e.g. a trailing
            // `# comment`), rather than `trim_matches` on the whole tail —
            // that would only strip a quote sitting at the very end of the
            // remaining string, missing it entirely when a comment follows
            // the closing quote on the same line. Symmetric with
            // `replace_version_in_contents`'s write-path remainder handling.
            return match value.chars().next() {
                Some(q @ ('"' | '\'')) => {
                    value[1..].find(q).map(|end| value[1..1 + end].to_string())
                }
                _ => {
                    let end = value.find([' ', '\t', ',', '#']).unwrap_or(value.len());
                    Some(value[..end].to_string())
                }
            };
        }
    }
    None
}

fn replace_version_in_contents(contents: &str, field: &str, new_version: &str) -> Option<String> {
    let (section, key) = split_field(field);
    let mut current = "";
    let mut changed = false;
    let mut output = String::new();
    for line in contents.lines() {
        let trimmed = line.trim();
        if let Some(header) = parse_section_header(trimmed) {
            current = header;
            output.push_str(line);
            output.push('\n');
            continue;
        }
        if !changed
            && current == section
            && let Some((left, value)) = line.split_once(['=', ':'])
        {
            let left_key = left.trim().trim_matches('"').trim_matches('\'');
            if left_key == key && !value.trim().starts_with('{') {
                let separator: &str = if trimmed.contains('=') { " = " } else { ": " };
                let trimmed_value = value.trim();
                let needs_quote = trimmed_value.starts_with('"') || trimmed_value.starts_with('\'');
                let quote_char: &str = if trimmed_value.starts_with('\'') {
                    "'"
                } else {
                    "\""
                };
                // Capture whatever follows the version token itself (a
                // trailing `,` in JSON, a trailing `# comment` in TOML) so it
                // survives the rewrite instead of being silently dropped
                // (GAP-6).
                let remainder = if needs_quote {
                    // Token ends at the closing quote; skip the opening
                    // quote and scan for the matching close.
                    trimmed_value[1..]
                        .find(quote_char)
                        .map(|end| &trimmed_value[end + 2..])
                        .unwrap_or("")
                } else {
                    // Unquoted: token ends at the first whitespace, `,`, or `#`.
                    let end = trimmed_value
                        .find([' ', '\t', ',', '#'])
                        .unwrap_or(trimmed_value.len());
                    &trimmed_value[end..]
                };
                output.push_str(left.trim_end());
                output.push_str(separator);
                if needs_quote {
                    output.push_str(quote_char);
                    output.push_str(new_version);
                    output.push_str(quote_char);
                } else {
                    output.push_str(new_version);
                }
                output.push_str(remainder.trim_end());
                output.push('\n');
                changed = true;
                continue;
            }
        }
        output.push_str(line);
        output.push('\n');
    }
    changed.then_some(output)
}

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

    fn git(root: &Path, args: &[&str]) {
        let ok = crate::test_support::git_command(root)
            .args(args)
            .output()
            .unwrap()
            .status
            .success();
        assert!(ok, "git {args:?} failed");
    }

    fn init_repo(root: &Path) {
        git(root, &["init", "-q"]);
        git(root, &["config", "user.email", "test@example.com"]);
        git(root, &["config", "user.name", "Test"]);
        git(root, &["config", "commit.gpgsign", "false"]);
        git(root, &["config", "tag.gpgsign", "false"]);
        git(root, &["config", "core.hooksPath", "/dev/null"]);
    }

    fn commit(root: &Path, name: &str) {
        std::fs::write(root.join(name), name).unwrap();
        git(root, &["add", "."]);
        git(root, &["commit", "-q", "-m", &format!("add {name}")]);
    }

    /// As [`commit`], but with an explicit commit message — needed for
    /// conventional-commit classification fixtures, where the message
    /// content (not the file name) is what's under test.
    fn commit_msg(root: &Path, name: &str, message: &str) {
        std::fs::write(root.join(name), name).unwrap();
        git(root, &["add", "."]);
        git(root, &["commit", "-q", "-m", message]);
    }

    /// One-line `tag` helper of the same shape as `git`/`init_repo`/`commit`.
    fn tag(root: &Path, name: &str) {
        git(root, &["tag", name]);
    }

    fn current_branch(root: &Path) -> String {
        let output = crate::test_support::git_command(root)
            .args(["symbolic-ref", "--short", "HEAD"])
            .output()
            .unwrap();
        assert!(output.status.success(), "symbolic-ref --short HEAD failed");
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    fn checkout_new(root: &Path, branch: &str) {
        git(root, &["checkout", "-b", branch]);
    }

    fn checkout(root: &Path, branch: &str) {
        git(root, &["checkout", branch]);
    }

    /// Simulate `scripts/sync-main-to-develop.sh`'s content-preserving
    /// `-X ours` merge: a real merge commit (so ancestry is restored) whose
    /// tree is unaffected (so nothing about `develop`'s own content changes).
    fn merge_ours(root: &Path, branch: &str, message: &str) {
        git(root, &["merge", "-s", "ours", "-m", message, branch]);
    }

    /// Simulate the shape `GitFlow::merge_feature_into_develop`
    /// (`crates/devflow-core/src/git.rs:86`) produces for every phase branch
    /// merged into `develop`: a real, ordinary `--no-ff` merge commit.
    /// Ordinary post-release feature work lands this way too, which is what
    /// makes it a merge commit on the ancestry path in addition to the
    /// sync-merge-back — the reason `release_range_start` cannot simply
    /// anchor at "the last merge commit."
    fn merge_no_ff(root: &Path, branch: &str, message: &str) {
        git(root, &["merge", "--no-ff", "-m", message, branch]);
    }

    /// Capture `HEAD`'s commit SHA, mirroring `current_branch`'s construction.
    fn head_sha(root: &Path) -> String {
        let output = crate::test_support::git_command(root)
            .args(["rev-parse", "HEAD"])
            .output()
            .unwrap();
        assert!(output.status.success(), "rev-parse HEAD failed");
        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[test]
    fn detect_prefers_cargo_then_pyproject_then_package_json() {
        let dir = tempfile::tempdir().unwrap();
        assert!(detect_version_file(dir.path()).is_none());
        std::fs::write(dir.path().join("package.json"), "{\"version\":\"1.0.0\"}").unwrap();
        assert!(
            detect_version_file(dir.path())
                .unwrap()
                .ends_with("package.json")
        );
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion=\"1.0.0\"",
        )
        .unwrap();
        assert!(
            detect_version_file(dir.path())
                .unwrap()
                .ends_with("Cargo.toml")
        );
    }

    #[test]
    fn read_major_from_workspace_package() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("Cargo.toml");
        std::fs::write(
            &file,
            "[workspace.package]\nversion = \"2.5.7\"\nedition = \"2024\"\n",
        )
        .unwrap();
        assert_eq!(read_major_version(&file).unwrap(), 2);
    }

    #[test]
    fn inline_table_version_does_not_shadow_workspace_package() {
        assert_eq!(parse_section_header("[[bin]]"), Some("bin"));

        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("Cargo.toml");
        std::fs::write(
            &file,
            "[[bin]]\nname = \"devflow\"\n\
             [workspace.dependencies]\nserde = { version = \"1\", features = [\"derive\"] }\n\
             [workspace.package]\nversion = \"1.2.0\"\n",
        )
        .unwrap();

        assert_eq!(read_major_version(&file).unwrap(), 1);
        write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(file).unwrap();
        assert!(contents.contains("serde = { version = \"1\""));
        assert!(contents.contains("[workspace.package]\nversion = \"2.3.4\""));
    }

    #[test]
    fn read_major_from_package_json() {
        let dir = tempfile::tempdir().unwrap();
        let file = dir.path().join("package.json");
        std::fs::write(&file, "{\n  \"version\": \"3.1.0\"\n}\n").unwrap();
        assert_eq!(read_major_version(&file).unwrap(), 3);
    }

    #[test]
    fn docs_only_commits_after_tag_yield_patch_floor() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v2.0.0");
        commit_msg(root, "b.txt", "docs: update readme");
        commit_msg(root, "c.txt", "docs: fix typo");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn feat_commit_after_tag_yields_minor_bump() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v2.0.0");
        commit_msg(root, "b.txt", "docs: update readme");
        commit_msg(root, "c.txt", "feat(x): add new capability");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 1,
                patch: 0
            }
        );
    }

    #[test]
    fn fix_commit_after_tag_yields_patch_bump() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v2.0.0");
        commit_msg(root, "b.txt", "fix(x): correct off-by-one");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn no_semver_tag_at_all_yields_documented_empty_repo_contract() {
        // Empty-repo contract (D-07/D-08 with no baseline tag): baseline is
        // 0.0.0, and the very first commit's own classification applies
        // directly — a `feat` yields the minor floor, `0.1.0`.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "feat: initial capability");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 0,
                minor: 1,
                patch: 0
            }
        );
    }

    #[test]
    fn squash_sync_topology_classifies_only_post_merge_commits() {
        // Reproduces this repository's real release shape: `develop` work is
        // squash-merged into a fresh commit on the trunk (no ancestry back to
        // develop's originals), then a content-preserving `-X ours` merge
        // syncs the trunk back into develop, restoring ancestry in the OTHER
        // direction only. The classifier must see only the commit(s) added
        // AFTER that sync merge, not develop's pre-squash originals.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "base.txt", "chore: init");
        let trunk = current_branch(root);

        checkout_new(root, "develop");
        commit_msg(root, "d1.txt", "feat: develop work one");
        commit_msg(root, "d2.txt", "feat: develop work two");

        checkout(root, &trunk);
        commit_msg(root, "sq1.txt", "feat: squashed release of develop work");
        tag(root, "v2.0.0");

        checkout(root, "develop");
        merge_ours(
            root,
            &trunk,
            "merge: sync main back into develop after release",
        );
        commit_msg(root, "f1.txt", "fix: patch after sync");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn two_squash_sync_cycles_anchor_to_the_second_merge_only() {
        // Pins the property release_range_start's doc comment names: because
        // reachable_semver_baseline always selects the highest reachable
        // tag, the ancestry path from that tag to HEAD crosses exactly one
        // sync merge — so inspecting only C1's first parent is sufficient
        // even with TWO release cycles in history. If baseline selection
        // ever regressed to anchor at the first cycle's merge instead of the
        // second, this fixture's first-cycle `feat` (d1) would leak back
        // into the classified range and wrongly produce a minor bump.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "base.txt", "chore: init");
        let trunk = current_branch(root);

        checkout_new(root, "develop");
        commit_msg(root, "d1.txt", "feat: first cycle work");

        checkout(root, &trunk);
        commit_msg(root, "sq1.txt", "feat: first squashed release");
        tag(root, "v2.0.0");

        checkout(root, "develop");
        merge_ours(
            root,
            &trunk,
            "merge: sync main back into develop after release (1)",
        );
        commit_msg(root, "d3.txt", "feat: second cycle work");

        checkout(root, &trunk);
        commit_msg(root, "sq2.txt", "feat: second squashed release");
        tag(root, "v2.1.0");

        checkout(root, "develop");
        merge_ours(
            root,
            &trunk,
            "merge: sync main back into develop after release (2)",
        );
        commit_msg(root, "f1.txt", "fix: patch after second sync");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 1,
                patch: 1
            }
        );
    }

    /// Reproduces CR-03 (`25-REVIEW.md`): the current `release_range_start`
    /// inspects only the ancestry path's FIRST commit (`C1`) and tests
    /// whether the baseline tag is an ancestor of `C1`'s first parent. When a
    /// commit lands directly on trunk between the tag and the sync-merge-back
    /// (a hotfix pushed straight to `main`), that intervening commit becomes
    /// `C1` — its first parent IS the tag commit, so
    /// `git merge-base --is-ancestor <tag> <tag>` is trivially true, the
    /// function wrongly concludes the tag already sat on mainline, and it
    /// returns the literal `tag..HEAD` range — reintroducing the pre-release
    /// `develop` history the whole D-08 anchor exists to exclude.
    ///
    /// RED until Task 2 lands (`release_range_start` walks the whole
    /// ancestry path instead of only `C1`).
    #[test]
    fn trunk_commit_between_tag_and_sync_merge_still_anchors_at_the_sync_merge() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "base.txt", "chore: init");
        let trunk = current_branch(root);

        checkout_new(root, "develop");
        commit_msg(root, "d1.txt", "feat: develop work one");
        commit_msg(root, "d2.txt", "feat: develop work two");

        checkout(root, &trunk);
        commit_msg(root, "sq1.txt", "feat: squashed release of develop work");
        tag(root, "v2.0.0");

        // Still on trunk: the intervening direct-trunk commit that turns
        // CR-03's C1-only heuristic into a false positive.
        commit_msg(root, "hot.txt", "fix: hotfix pushed straight to main");

        checkout(root, "develop");
        merge_ours(
            root,
            &trunk,
            "merge: sync main back into develop after release",
        );
        let sync_merge = head_sha(root);
        commit_msg(root, "f1.txt", "fix: patch after sync");

        assert_eq!(
            release_range_start(root, "v2.0.0").unwrap(),
            sync_merge,
            "anchor must be the sync merge, not the hotfix's tag-ancestor first parent"
        );
        assert_eq!(
            compute_version(root).unwrap(),
            Version {
                major: 2,
                minor: 0,
                patch: 1
            },
            "pre-fix this yields 2.1.0: the range collapses to tag..HEAD and \
             re-admits d1/d2's two feat commits"
        );
    }

    /// Tripwire pinning this plan's deliberate deviation from
    /// `25-REVIEW.md`/`25-VERIFICATION.md`'s fix sketch ("anchor at the last
    /// merge commit in the ancestry path"). `GitFlow::merge_feature_into_develop`
    /// (`crates/devflow-core/src/git.rs:86`) merges every phase branch into
    /// `develop` with `git merge --no-ff`, so ordinary POST-RELEASE feature
    /// work also produces merge commits on the ancestry path — not just the
    /// sync-merge-back. Measured live against this repository 2026-07-28
    /// (`git rev-list --ancestry-path --reverse v2.0.0..develop`): the
    /// correct anchor is `c92229e` (the sync merge), but the literal "last
    /// merge commit" rule would return `819987b` (a later, unrelated PR
    /// merge), whose range silently drops an intervening commit from
    /// classification. Today that dropped commit is a `docs:` commit and
    /// nothing breaks; a `feat!:` in that same position would be dropped
    /// instead — a false negative that lets a major bump ship unattended,
    /// exactly what D-09 exists to prevent.
    ///
    /// This test is GREEN before AND after Task 2: it is green today (this
    /// is what the CURRENT C1-only code already gets right), and it must
    /// stay green under the generalized full-ancestry-path rule Task 2
    /// implements. It goes RED only under the review's literal "last merge
    /// commit" sketch — do not simplify the implementation into that sketch.
    ///
    /// Deviation from this plan's literal construction: without the
    /// intervening `chore: continue develop work after sync` commit below,
    /// `git rev-list --ancestry-path --reverse` places the feature branch's
    /// single-parent commit (`ft1`) BEFORE the sync-merge commit itself in
    /// its output — a real, measured property of that exact shape (verified
    /// live 2026-07-28; see 25-09-SUMMARY.md), not test flakiness — which
    /// made the fixture as originally specified fail pre-fix (asserting
    /// behavior the current C1-only code does not actually have). Per this
    /// plan's own instruction ("If Test 2 fails pre-fix, the fixture is
    /// malformed — stop and fix it"), one ordinary intervening develop
    /// commit was inserted between the sync merge and the feature branch's
    /// creation, which is itself realistic (post-release develop work
    /// commonly precedes the next feature branch) and restores C1 = the
    /// sync merge under the current implementation without changing either
    /// assertion.
    #[test]
    fn feature_merge_after_sync_merge_does_not_move_the_anchor() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "base.txt", "chore: init");
        let trunk = current_branch(root);

        checkout_new(root, "develop");
        commit_msg(root, "d1.txt", "feat: develop work one");

        checkout(root, &trunk);
        commit_msg(root, "sq1.txt", "feat: squashed release of develop work");
        tag(root, "v2.0.0");

        checkout(root, "develop");
        merge_ours(
            root,
            &trunk,
            "merge: sync main back into develop after release",
        );
        let sync_merge = head_sha(root);
        commit_msg(root, "tail.txt", "chore: continue develop work after sync");

        checkout_new(root, "feature/phase-99");
        commit_msg(root, "ft1.txt", "feat: post-release capability");
        checkout(root, "develop");
        merge_no_ff(
            root,
            "feature/phase-99",
            "Merge pull request #99 from feature/phase-99",
        );
        commit_msg(root, "f1.txt", "fix: patch after the feature merge");

        assert_eq!(
            release_range_start(root, "v2.0.0").unwrap(),
            sync_merge,
            "anchor must be the sync merge, not the later feature-branch pull-request merge"
        );
        assert_eq!(
            compute_version(root).unwrap(),
            Version {
                major: 2,
                minor: 1,
                patch: 0
            },
            "ft1's feat must be inside the classified range"
        );
    }

    #[test]
    fn unreachable_highest_tag_refuses_rather_than_falling_back() {
        // D-10: when the highest semver tag overall is not reachable from
        // HEAD, compute_version must refuse — never silently fall back to
        // the highest *reachable* tag (which would compute a version below
        // the real release history, T-25-04).
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        let main_branch = current_branch(root);

        git(root, &["checkout", "--orphan", "orphan-release"]);
        git(
            root,
            &["commit", "--allow-empty", "-q", "-m", "chore: orphan"],
        );
        tag(root, "v9.9.9");
        git(root, &["checkout", &main_branch]);

        let err = compute_version(root).unwrap_err();
        match err {
            VersionError::UnreachableBaseline { tag } => {
                assert_eq!(tag, "v9.9.9", "refusal must name the unreachable tag");
            }
            other => {
                panic!("expected UnreachableBaseline (never a silent smaller Ok), got: {other:?}")
            }
        }
    }

    #[test]
    fn range_with_no_bumping_commits_yields_patch_floor() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "docs: update readme");
        commit_msg(root, "c.txt", "chore: tidy up");
        commit_msg(root, "d.txt", "ci: tweak workflow");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 1,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn malformed_commit_message_yields_patch_not_crash_or_major() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(
            root,
            "b.txt",
            "just a plain message with no conventional type prefix!!!",
        );

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 1,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn exclamation_before_colon_yields_major() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "feat(scope)!: drop legacy api");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 0,
                patch: 0
            }
        );
    }

    #[test]
    fn breaking_change_footer_yields_major_even_with_fix_subject() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        git(
            root,
            &[
                "commit",
                "--allow-empty",
                "-q",
                "-m",
                "fix: patch a thing\n\nBREAKING CHANGE: removes an implicit default",
            ],
        );

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 2,
                minor: 0,
                patch: 0
            }
        );
    }

    #[test]
    fn exclamation_only_in_description_does_not_yield_major() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "fix: stop the crash!!!");

        let v = compute_version(root).unwrap();
        assert_eq!(
            v,
            Version {
                major: 1,
                minor: 0,
                patch: 1
            }
        );
    }

    #[test]
    fn write_version_replaces_in_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let path = write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("version = \"2.3.4\""));
    }

    #[test]
    fn write_version_replaces_in_workspace_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        let path = write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(&path).unwrap();
        assert!(contents.contains("[workspace.package]\nversion = \"2.3.4\""));
    }

    #[test]
    fn write_version_errors_without_version_file() {
        let dir = tempfile::tempdir().unwrap();
        assert!(matches!(
            write_version(
                dir.path(),
                &Version {
                    major: 1,
                    minor: 0,
                    patch: 0
                }
            ),
            Err(VersionError::Parse(_))
        ));
    }

    #[test]
    fn read_version_round_trips_through_write_version_in_plain_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"0.1.0\"\n",
        )
        .unwrap();
        let written = Version {
            major: 2,
            minor: 3,
            patch: 4,
        };
        write_version(dir.path(), &written).unwrap();
        assert_eq!(read_version(dir.path()).unwrap(), written);
    }

    #[test]
    fn read_version_round_trips_through_write_version_in_workspace_cargo_toml() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace.package]\nversion = \"0.1.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        let written = Version {
            major: 5,
            minor: 6,
            patch: 7,
        };
        write_version(dir.path(), &written).unwrap();
        assert_eq!(read_version(dir.path()).unwrap(), written);
    }

    #[test]
    fn read_version_round_trips_through_write_version_in_package_json() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "{\n  \"version\": \"0.1.0\"\n}\n",
        )
        .unwrap();
        let written = Version {
            major: 1,
            minor: 9,
            patch: 12,
        };
        write_version(dir.path(), &written).unwrap();
        assert_eq!(read_version(dir.path()).unwrap(), written);
    }

    #[test]
    fn read_version_errors_without_version_file() {
        let dir = tempfile::tempdir().unwrap();
        assert!(matches!(
            read_version(dir.path()),
            Err(VersionError::Parse(_))
        ));
    }

    #[test]
    fn write_version_preserves_trailing_comma_in_package_json() {
        // GAP-6: replace_version_in_contents reassembles the matched line as
        // `left.trim_end() + separator + quoted_version + '\n'`, discarding
        // everything in `value` after the version token. For a real
        // package.json where `version` is not the last key, that eats the
        // mandatory trailing comma and produces invalid JSON. Parsing is the
        // assertion that matters here — a substring check would be a
        // vacuous fixture that can't reach this defect.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("package.json"),
            "{\n  \"name\": \"x\",\n  \"version\": \"0.1.0\",\n  \"private\": true\n}\n",
        )
        .unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("package.json")).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&contents).unwrap_or_else(|err| {
            panic!("package.json no longer parses as JSON: {err}\n{contents}")
        });
        assert_eq!(parsed["name"], "x");
        assert_eq!(parsed["private"], true);
        assert_eq!(parsed["version"], "2.3.4");
    }

    #[test]
    fn write_version_preserves_trailing_comment_in_toml() {
        // GAP-6, TOML variant: a trailing `# comment` after the quoted
        // version is discarded by the same line-reassembly defect.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"0.1.0\"  # pinned\n",
        )
        .unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents.contains("version = \"2.3.4\"  # pinned"),
            "expected trailing comment to survive, got: {contents}"
        );
    }

    #[test]
    fn write_version_preserves_trailing_comment_in_single_quoted_toml() {
        // GAP-6, TOML literal-string variant (17-13 review IN-03): the
        // remainder scan keys off the OPENING quote character, so the
        // single-quote branch is a distinct path from the double-quote case
        // above and needs its own fixture.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = '0.1.0'  # pinned\n",
        )
        .unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 2,
                minor: 3,
                patch: 4,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents.contains("version = '2.3.4'  # pinned"),
            "expected single-quoted value and trailing comment to survive, got: {contents}"
        );
    }

    #[test]
    fn read_version_extracts_clean_value_with_trailing_comment() {
        // CR-01 (phase 20 review): `find_version_in_contents` used to
        // `trim_matches` the whole tail of the line, which only strips a
        // quote sitting at the very end of the remaining string. With a
        // trailing `# comment` after the closing quote, the real closing
        // quote is never stripped and the corrupted value fails to parse.
        // `write_version` already preserves this exact pattern (GAP-6); the
        // read path must be symmetric with it.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"1.7.0\"  # pinned release version\n",
        )
        .unwrap();
        assert_eq!(
            read_version(dir.path()).unwrap(),
            Version {
                major: 1,
                minor: 7,
                patch: 0
            }
        );
    }

    #[test]
    fn read_version_extracts_clean_value_without_trailing_comment() {
        // Bare `version = "1.7.0"` (no comment) must still work.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nversion = \"1.7.0\"\n",
        )
        .unwrap();
        assert_eq!(
            read_version(dir.path()).unwrap(),
            Version {
                major: 1,
                minor: 7,
                patch: 0
            }
        );
    }

    #[test]
    fn read_workspace_self_pins_extracts_clean_workspace_version_with_trailing_comment() {
        // CR-01: `read_workspace_self_pins` calls `find_version_in_contents`
        // for `workspace_version` too — a trailing comment next to
        // `[workspace.package] version` must not corrupt the value
        // `check_self_pin` compares pins against.
        let (workspace_version, _pins) = read_workspace_self_pins(
            "[workspace.package]\nversion = \"1.7.0\"  # pinned release version\nedition = \"2024\"\n",
        );
        assert_eq!(workspace_version.as_deref(), Some("1.7.0"));
    }

    #[test]
    fn read_version_does_not_recompute_from_git_tags() {
        // read_version must report exactly what's on disk, not a freshly
        // computed minor/patch — this is the property VersionBump/
        // ChangelogAppend ordering depends on (version.rs must never see a
        // tag VersionBump just created and derive a different number).
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        std::fs::write(root.join("Cargo.toml"), "[package]\nversion = \"2.0.0\"\n").unwrap();
        commit(root, "a.txt");
        write_version(
            root,
            &Version {
                major: 2,
                minor: 0,
                patch: 0,
            },
        )
        .unwrap();
        git(root, &["tag", "v2.0.0"]);
        commit(root, "b.txt");
        commit(root, "c.txt");
        // compute_version would recompute from git history (baseline v2.0.0,
        // bumped by whatever the two later commits classify to) instead of
        // reporting the version file. read_version must still report exactly
        // what's on disk: 2.0.0.
        assert_eq!(
            read_version(root).unwrap(),
            Version {
                major: 2,
                minor: 0,
                patch: 0
            }
        );
    }

    #[test]
    fn write_version_rewrites_workspace_dependency_self_pin() {
        // 20a / DEN-49: a published Cargo workspace states its version twice —
        // once in [workspace.package] version, and again as an explicit
        // `version` pin on every [workspace.dependencies] entry that points
        // at a workspace member by `path` (Cargo has no interpolation for
        // dependency versions, and a path dependency of a *published* crate
        // requires an explicit version). write_version must rewrite BOTH in
        // one write, or the self-pin ships stale and `cargo publish` rejects
        // the upload as a duplicate on release day (shipped broken twice:
        // v1.5.0 by 7ad260c, v1.6.0 by PR #15).
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
             [workspace.dependencies]\n\
             devflow-core = { path = \"crates/devflow-core\", version = \"1.6.0\" }\n",
        )
        .unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents.contains("[workspace.package]\nversion = \"1.7.0\""),
            "expected [workspace.package] version to be rewritten, got: {contents}"
        );
        assert!(
            contents
                .contains("devflow-core = { path = \"crates/devflow-core\", version = \"1.7.0\" }"),
            "expected the [workspace.dependencies] self-pin to be rewritten to 1.7.0 \
             alongside [workspace.package] version, got: {contents}"
        );
    }

    #[test]
    fn write_version_no_ops_on_missing_workspace_dependencies_section() {
        // 20a/empty: a workspace Cargo.toml with no [workspace.dependencies]
        // section at all must not panic — the additive pass simply never
        // matches and the file is otherwise rewritten normally.
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("Cargo.toml"),
            "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n",
        )
        .unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert_eq!(
            contents,
            "[workspace.package]\nversion = \"1.7.0\"\nedition = \"2024\"\n"
        );
    }

    #[test]
    fn write_version_no_ops_on_member_with_no_version_key() {
        // 20a/empty: a [workspace.dependencies] entry with a local `path`
        // but no `version` key at all is left unchanged — nothing to
        // rewrite, and no panic.
        let dir = tempfile::tempdir().unwrap();
        let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
             [workspace.dependencies]\n\
             devflow-core = { path = \"crates/devflow-core\" }\n";
        std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents.contains("devflow-core = { path = \"crates/devflow-core\" }"),
            "expected the version-less path member to be left byte-identical, got: {contents}"
        );
    }

    #[test]
    fn write_version_leaves_third_party_version_only_dep_untouched() {
        // 20a/adjacency: a third-party version-only dep sitting adjacent to
        // a local path member is left byte-for-byte unchanged — only the
        // path member's version sub-value is rewritten.
        let dir = tempfile::tempdir().unwrap();
        let third_party_line = "serde = { version = \"1\", features = [\"derive\"] }";
        let toml = format!(
            "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
             [workspace.dependencies]\n\
             devflow-core = {{ path = \"crates/devflow-core\", version = \"1.6.0\" }}\n\
             {third_party_line}\n"
        );
        std::fs::write(dir.path().join("Cargo.toml"), &toml).unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents
                .contains("devflow-core = { path = \"crates/devflow-core\", version = \"1.7.0\" }"),
            "expected the local path member's version to be rewritten, got: {contents}"
        );
        assert!(
            contents.contains(third_party_line),
            "expected the third-party version-only dep to be byte-identical, got: {contents}"
        );
    }

    #[test]
    fn write_version_preserves_comment_and_quote_in_workspace_dependency_pin() {
        // GAP-6, inline-table variant: a self-pin line with a trailing
        // comment and single-quoted values keeps its comment and quote
        // style after rewrite.
        let dir = tempfile::tempdir().unwrap();
        let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
             [workspace.dependencies]\n\
             devflow-core = { path = 'crates/devflow-core', version = '1.6.0' }  # pinned\n";
        std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents.contains(
                "devflow-core = { path = 'crates/devflow-core', version = '1.7.0' }  # pinned"
            ),
            "expected single-quote style and trailing comment to survive the rewrite, got: {contents}"
        );
    }

    #[test]
    fn write_version_rewrites_self_pin_regardless_of_key_order() {
        // review: inline-table key-order — the version sub-value is
        // rewritten whether it appears BEFORE or AFTER path in the inline
        // table; the replacement is anchored strictly to the path=/
        // version= tokens, not a column offset.
        let dir = tempfile::tempdir().unwrap();
        let toml = "[workspace.package]\nversion = \"1.6.0\"\nedition = \"2024\"\n\n\
             [workspace.dependencies]\n\
             devflow-core = { version = \"1.6.0\", path = \"crates/devflow-core\" }\n";
        std::fs::write(dir.path().join("Cargo.toml"), toml).unwrap();
        write_version(
            dir.path(),
            &Version {
                major: 1,
                minor: 7,
                patch: 0,
            },
        )
        .unwrap();
        let contents = std::fs::read_to_string(dir.path().join("Cargo.toml")).unwrap();
        assert!(
            contents
                .contains("devflow-core = { version = \"1.7.0\", path = \"crates/devflow-core\" }"),
            "expected version to be rewritten regardless of key order, got: {contents}"
        );
    }

    #[test]
    fn changelog_sections_groups_a_feat_commit_under_added() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "feat: add the widget endpoint");

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(
            sections,
            vec![(
                ChangelogHeading::Added,
                vec!["add the widget endpoint".to_string()]
            )]
        );
    }

    #[test]
    fn render_changelog_body_renders_heading_and_bullets() {
        let sections = vec![(
            ChangelogHeading::Added,
            vec!["add the widget endpoint".to_string()],
        )];
        let body = render_changelog_body(&sections);
        assert_eq!(body, "### Added\n\n- add the widget endpoint\n");
    }

    /// D-12 Task 2: fix/perf -> Fixed; docs/chore/test/ci/refactor/style all
    /// -> one Changed section, in git-log order (newest first). Each
    /// expected value is written out literally, never recomputed from the
    /// mapping under test (test-signal-rejection.md rejection pattern 2).
    #[test]
    fn changelog_sections_maps_every_recognized_type() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "fix: correct y");
        commit_msg(root, "c.txt", "perf: speed up z");
        commit_msg(root, "d.txt", "docs: clarify readme");
        commit_msg(root, "e.txt", "chore: bump dep");
        commit_msg(root, "f.txt", "test: add case");
        commit_msg(root, "g.txt", "ci: pin image");
        commit_msg(root, "h.txt", "refactor: extract helper");
        commit_msg(root, "i.txt", "style: reformat");

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(
            sections,
            vec![
                (
                    ChangelogHeading::Fixed,
                    vec!["speed up z".to_string(), "correct y".to_string()]
                ),
                (
                    ChangelogHeading::Changed,
                    vec![
                        "reformat".to_string(),
                        "extract helper".to_string(),
                        "pin image".to_string(),
                        "add case".to_string(),
                        "bump dep".to_string(),
                        "clarify readme".to_string(),
                    ]
                ),
            ]
        );
    }

    /// D-12 Task 2: both breaking-change forms (the `!` marker and a
    /// `BREAKING CHANGE:` footer) route to `Breaking`, never `Added`/`Fixed`,
    /// regardless of the commit's own type — checked before the type match,
    /// mirroring `classify_commit_message`'s own precedence.
    #[test]
    fn changelog_sections_routes_breaking_changes_to_their_own_heading() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "feat(api)!: drop the legacy flag");
        git(
            root,
            &[
                "commit",
                "--allow-empty",
                "-q",
                "-m",
                "fix: patch a thing\n\nBREAKING CHANGE: removes an implicit default",
            ],
        );

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(
            sections,
            vec![(
                ChangelogHeading::Breaking,
                vec![
                    "patch a thing".to_string(),
                    "drop the legacy flag".to_string()
                ]
            )]
        );
    }

    /// D-12 Task 2: a message that fails `git_conventional::Commit::parse`
    /// still contributes a bullet (must_haves.truths) — grouped as `Changed`,
    /// never dropped. Deliberate divergence from `classify_commit_message`
    /// (which maps the same failure to `Bump::Patch` for versioning): a
    /// message with no conventional type has no claim to `Fixed`.
    #[test]
    fn changelog_sections_treats_unparseable_messages_as_changed() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(
            root,
            "b.txt",
            "just a plain message with no conventional type prefix!!!",
        );

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(
            sections,
            vec![(
                ChangelogHeading::Changed,
                vec!["just a plain message with no conventional type prefix!!!".to_string()]
            )]
        );
    }

    #[test]
    fn changelog_sections_returns_no_sections_for_an_empty_range() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(sections, Vec::new());
        assert_eq!(render_changelog_body(&sections), "");
    }

    /// D-12/ASVS V7 (Task 3), mirrors `render_gate_context`'s properties
    /// (`pipeline_outcomes.rs:323`): every `char::is_control()` character is
    /// neutralized, an over-length subject is capped at exactly
    /// `CHANGELOG_SUBJECT_MAX_CHARS` including the truncation marker, and a
    /// short ordinary subject passes through unchanged.
    #[test]
    fn sanitize_changelog_subject_neutralizes_controls_and_caps_length() {
        let controls = "line 1\u{1b}[2J\tline 2\u{7}";
        let sanitized = sanitize_changelog_subject(controls);
        assert!(
            sanitized.chars().all(|c| !c.is_control()),
            "expected no control characters, got: {sanitized:?}"
        );

        let long = "x".repeat(5000);
        let capped = sanitize_changelog_subject(&long);
        assert!(capped.chars().count() <= CHANGELOG_SUBJECT_MAX_CHARS);
        assert!(capped.ends_with("… [truncated]"));

        let short = "add the widget endpoint";
        assert_eq!(sanitize_changelog_subject(short), short);
    }

    /// D-12/ASVS V7 (Task 3): asserts on `changelog_sections`' output (the
    /// public boundary), not on `sanitize_changelog_subject` alone — proving
    /// the call site exists, not merely the helper.
    #[test]
    fn changelog_sections_sanitizes_subjects_before_grouping() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit_msg(root, "a.txt", "chore: init");
        tag(root, "v1.0.0");
        commit_msg(root, "b.txt", "feat: add \u{1b}[31mcolored\u{1b}[0m widget");

        let sections = changelog_sections(root, "v1.0.0").unwrap();
        assert_eq!(sections.len(), 1);
        let (heading, bullets) = &sections[0];
        assert_eq!(*heading, ChangelogHeading::Added);
        assert_eq!(bullets.len(), 1);
        assert!(
            bullets[0].chars().all(|c| !c.is_control()),
            "expected no control characters in the grouped bullet, got: {:?}",
            bullets[0]
        );
    }

    // -----------------------------------------------------------------
    // 27-03 (D-01/D-03): tag reads resolve the caller's own repository
    // under a hostile GIT_DIR, not an unrelated one.
    // -----------------------------------------------------------------

    /// D-03: `count_git_tags`/`highest_semver_tag` resolve `root`'s own tags
    /// even when the process inherited a hostile `GIT_DIR` pointed at an
    /// unrelated repository — proven with a real spawned `git` process, not
    /// by inspecting a `Command` object alone. Mirrors
    /// `origin_main_ancestor_status_holds_under_a_hostile_git_dir`
    /// (`git.rs`, 27-01): `count_git_tags`/`highest_semver_tag` take only
    /// `project_root`, so the hostile `GIT_DIR` this test's own `<verify>`
    /// entries exercise (`GIT_DIR=<hostile>/.git cargo test ... this test`)
    /// is injected the same way any inherited-env attack reaches these
    /// functions in production: via the whole process's environment, then
    /// down into the spawned child unless the constructor scrubs it. Before
    /// this plan's migration, both bare `Command::new("git")` sites this
    /// test exercises inherit that `GIT_DIR` unscrubbed and silently read
    /// the hostile repository instead — an empty repository with zero tags
    /// is the clearest contrast against `root`'s two, so this test fails
    /// pre-migration under the hostile harness and passes once
    /// `git_command` scrubs it.
    // `count_git_tags` is deprecated (D-07) but still `pub`; this test still
    // exercises its own scrub, independent of `compute_version`'s supersession.
    /// 27-REVIEW WR-01: this test previously set no hostile environment at
    /// all — it asserted ordinary-path behavior and claimed a hostile-
    /// `GIT_DIR` proof, so it passed identically with or without the scrub.
    /// It now uses the spawned-child shape this phase established in
    /// `staleness.rs`: `GIT_DIR` is never set on this process (Rust 2024
    /// `unsafe`, unsound under threaded tests — Phase 25 D-14), only on one
    /// freshly spawned child re-invoking this binary filtered to this test.
    #[test]
    #[allow(deprecated)]
    fn tag_reads_resolve_caller_root_under_a_hostile_git_dir() {
        const INNER_ROOT: &str = "DEVFLOW_27_03_TAG_READS_INNER_ROOT";

        if let Ok(root) = std::env::var(INNER_ROOT) {
            // Inner mode: GIT_DIR points at a foreign repository that has
            // no tags at all, scoped to this child process only.
            let root = std::path::PathBuf::from(root);

            assert_eq!(
                count_git_tags(&root).unwrap(),
                2,
                "count_git_tags must resolve root's own two tags, not a \
                 hostile GIT_DIR's repository"
            );
            assert_eq!(
                highest_semver_tag(&root).unwrap(),
                Some(semver::Version::new(0, 2, 0)),
                "highest_semver_tag must resolve root's own highest tag, not \
                 a hostile GIT_DIR's repository"
            );
            return;
        }

        // Outer mode: the real repository has two tags; the foreign one has
        // none. Unscrubbed, the child would read the foreign repository and
        // see zero tags / no baseline.
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path();
        init_repo(root);
        commit(root, "a.txt");
        tag(root, "v0.1.0");
        commit(root, "b.txt");
        tag(root, "v0.2.0");

        let foreign = tempfile::tempdir().unwrap();
        init_repo(foreign.path());

        let exe = std::env::current_exe().expect("current_exe for child re-invocation");
        let out = std::process::Command::new(&exe)
            // Substring filter, NOT `--exact`: the binary's real test name is
            // module-qualified (`version::tests::tag_reads_...`), so `--exact`
            // against the bare name matches nothing, runs zero tests, and
            // still exits 0 — a false green that made the first version of
            // this fix as vacuous as the test it replaced.
            .arg("tag_reads_resolve_caller_root_under_a_hostile_git_dir")
            .arg("--test-threads=1")
            .env(INNER_ROOT, root.to_str().unwrap())
            .env("GIT_DIR", foreign.path().join(".git"))
            .output()
            .expect("spawn hostile child test process");

        let stdout = String::from_utf8_lossy(&out.stdout);
        // Assert the child actually RAN the test, not merely that it exited
        // 0. A filter that matches nothing exits 0 with "0 passed", so the
        // exit status alone cannot distinguish "proved it" from "ran nothing".
        assert!(
            stdout.contains("1 passed"),
            "child test process must have run exactly the inner test; \
             stdout:\n{stdout}"
        );
        assert!(
            out.status.success(),
            "child test process (hostile GIT_DIR pointed at an unrelated \
             foreign repository with no tags) must still resolve root's own \
             tags; child exit status {:?}\nstdout:\n{stdout}",
            out.status
        );
    }
}