anodizer 0.15.5

A Rust-native release automation tool inspired by GoReleaser
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
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
//! Integration tests for the unified `anodizer changelog` command.
//!
//! `anodizer changelog` refreshes the pending `## [Unreleased]` section
//! (`--format keep-a-changelog`, default), emits GitHub-body notes
//! (`--format release-notes`), or a JSON array (`--format json`). The refresh
//! path must work across all three config modes:
//!   1. single-crate (`crates:` with one entry + `version_sync`),
//!   2. workspace-lockstep (`[workspace.package].version`),
//!   3. workspace per-crate (flat `crates:` with independent versions).
//!
//! Also covers the positional range parsing (omitted / `a..b` / single `<tag>`),
//! the `--write` + non-kac error, the preview-extracts-only-the-section
//! contract, and `--crate` filtering.

use std::fs;
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;

/// Whether output contains a changelog-STAGE skip line ("skipped
/// changelog — snapshot mode ..." / "skipped changelog — `skip` ...").
/// Deliberately tighter than `contains("skipped changelog")` so the
/// changelog.ai line ("skipped changelog.ai enhancement ...") from an
/// AI-configured fixture can never false-match.
fn mentions_changelog_stage_skip(s: &str) -> bool {
    s.contains("skipped changelog — ")
}

fn anodizer() -> Command {
    Command::new(env!("CARGO_BIN_EXE_anodizer"))
}

fn run_git(dir: &Path, args: &[&str]) {
    let out = anodizer_core::test_helpers::output_with_spawn_retry(
        || {
            let mut cmd = Command::new("git");
            cmd.current_dir(dir).args(args);
            cmd
        },
        "git",
    );
    assert!(
        out.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

fn git_init(dir: &Path) {
    run_git(dir, &["init", "-q", "-b", "master"]);
    run_git(dir, &["config", "user.email", "test@test.com"]);
    run_git(dir, &["config", "user.name", "Test"]);
    run_git(dir, &["config", "commit.gpgsign", "false"]);
}

fn git_add_commit(dir: &Path, message: &str) {
    run_git(dir, &["add", "-A"]);
    run_git(dir, &["commit", "-q", "-m", message]);
}

fn read(dir: &Path, rel: &str) -> String {
    fs::read_to_string(dir.join(rel)).unwrap()
}

struct RunResult {
    stdout: String,
    stderr: String,
    success: bool,
}

fn changelog(dir: &Path, args: &[&str]) -> RunResult {
    let out = anodizer()
        .current_dir(dir)
        .arg("changelog")
        .args(args)
        .output()
        .unwrap();
    RunResult {
        stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
        stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
        success: out.status.success(),
    }
}

/// Assert that the `## [Unreleased]` section of `text` contains NO `### `
/// heading other than the supplied `allowed_group_titles`. A flat aggregate
/// must never graft a `### <crate>` OR `### <project_name>` subsection — the
/// aggregate is keyed by `project_name`, so a brittle "no `### <crate>` name"
/// check misses a regressed render guard that grafts `### <project_name>`.
/// Restricting the scan to the `[Unreleased]` block keeps curated H3s in older
/// released sections from tripping the assertion.
fn assert_no_subsection_graft(text: &str, allowed_group_titles: &[&str]) {
    let mut in_unreleased = false;
    for line in text.lines() {
        if line.starts_with("## ") {
            in_unreleased = line.contains("Unreleased");
            continue;
        }
        if in_unreleased && line.starts_with("### ") {
            let title = line.trim_start_matches("### ").trim();
            assert!(
                allowed_group_titles.contains(&title),
                "unexpected `### {title}` subsection grafted into [Unreleased] \
                 (allowed group titles: {allowed_group_titles:?}):\n{text}"
            );
        }
    }
}

// ---------------------------------------------------------------------------
// Mode 1: single-crate refresh + write
// ---------------------------------------------------------------------------

fn single_crate_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/app\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/app/src")).unwrap();
    fs::write(
        root.join("crates/app/Cargo.toml"),
        "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/app/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: single
changelog: {}
crates:
  - name: app
    path: crates/app
    tag_template: "v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/app/src/lib.rs"), "// touched\n").unwrap();
    git_add_commit(root, "feat: add a thing");
    tmp
}

#[test]
fn single_crate_preview_shows_unreleased_only() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q"]);
    assert!(r.success, "preview failed: {}\n{}", r.stdout, r.stderr);
    assert!(
        r.stdout.contains("Unreleased"),
        "preview must show the [Unreleased] heading: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("add a thing"),
        "preview must show the new commit: {}",
        r.stdout
    );
    // Preview does not write the file.
    assert!(
        !root.join("CHANGELOG.md").exists(),
        "preview must not write CHANGELOG.md"
    );
}

#[test]
fn single_crate_write_refreshes_file() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--write"]);
    assert!(r.success, "write failed: {}\n{}", r.stdout, r.stderr);
    // Bare `changelog: {}` routes to the workspace-root CHANGELOG.md.
    let cl = read(root, "CHANGELOG.md");
    assert!(cl.contains("Unreleased"), "expected [Unreleased]: {cl}");
    assert!(cl.contains("add a thing"), "expected the commit: {cl}");
    // No commit was made: the write is a working-tree edit only.
    let status = anodizer_core::test_helpers::output_with_spawn_retry(
        || {
            let mut cmd = Command::new("git");
            cmd.current_dir(root)
                .args(["status", "--porcelain", "CHANGELOG.md"]);
            cmd
        },
        "git",
    );
    let out = String::from_utf8_lossy(&status.stdout);
    assert!(
        out.contains("CHANGELOG.md"),
        "CHANGELOG.md must be an uncommitted working-tree edit, status: {out:?}"
    );
}

#[test]
fn single_crate_write_preserves_released_history() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // Seed a released section + footer that the refresh must preserve.
    fs::write(
        root.join("CHANGELOG.md"),
        "# Changelog\n\n## [Unreleased]\n\n## [0.1.0] - 2026-01-01\n\n- first release\n\n[Unreleased]: http://x/compare/v0.1.0...HEAD\n",
    )
    .unwrap();
    let r = changelog(root, &["-q", "--write"]);
    assert!(r.success, "write failed: {}\n{}", r.stdout, r.stderr);
    let cl = read(root, "CHANGELOG.md");
    assert!(cl.contains("## [0.1.0]"), "released history dropped: {cl}");
    assert!(cl.contains("first release"), "released body dropped: {cl}");
    assert!(cl.contains("add a thing"), "new commit missing: {cl}");
    assert!(cl.contains("compare/v0.1.0"), "footer dropped: {cl}");
}

// ---------------------------------------------------------------------------
// Mode 2: workspace-lockstep
// ---------------------------------------------------------------------------

#[test]
fn lockstep_write_refreshes_root_changelog() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n\n[workspace.package]\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    for name in ["core", "cli"] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion.workspace = true\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: lockstep\nchangelog: {}\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// touched\n").unwrap();
    git_add_commit(root, "feat: lockstep change");

    let r = changelog(root, &["-q", "--write"]);
    assert!(
        r.success,
        "lockstep write failed: {}\n{}",
        r.stdout, r.stderr
    );
    let cl = read(root, "CHANGELOG.md");
    assert!(cl.contains("Unreleased"), "expected [Unreleased]: {cl}");
    assert!(cl.contains("lockstep change"), "expected the commit: {cl}");
    // One aggregate root file; no per-crate files for a bare changelog config.
    assert!(
        !root.join("crates/core/CHANGELOG.md").exists(),
        "lockstep refresh must not write per-crate files"
    );
}

/// A lockstep repo whose `tag.tag_prefix` is `release-v` tags releases
/// `release-v0.1.0`. The refresh must bound the range from THAT tag — not a
/// hardcoded `v*` that misses it and degrades to full history (the recurring
/// 3-mode prefix-drift bug). Asserts only the post-tag commit appears.
#[test]
fn lockstep_honors_custom_tag_prefix_for_range() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\"]\nresolver = \"2\"\n\n[workspace.package]\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/core/src")).unwrap();
    fs::write(
        root.join("crates/core/Cargo.toml"),
        "[package]\nname = \"core\"\nversion.workspace = true\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/core/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: lockstep\nchangelog: {}\ntag:\n  tag_prefix: \"release-v\"\n",
    )
    .unwrap();
    git_init(root);
    // A commit + the custom-prefixed tag, then a post-tag commit. Only the
    // post-tag commit may appear in the refreshed [Unreleased] range.
    fs::write(root.join("crates/core/src/lib.rs"), "// pre-tag\n").unwrap();
    git_add_commit(root, "feat: before the release tag");
    run_git(root, &["tag", "release-v0.1.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// post-tag\n").unwrap();
    git_add_commit(root, "feat: after the release tag");

    let r = changelog(root, &["-q", "--write"]);
    assert!(
        r.success,
        "lockstep custom-prefix write failed: {}\n{}",
        r.stdout, r.stderr
    );
    let cl = read(root, "CHANGELOG.md");
    assert!(
        cl.contains("after the release tag"),
        "post-tag commit missing: {cl}"
    );
    assert!(
        !cl.contains("before the release tag"),
        "range degraded to full history — pre-tag commit leaked (prefix \"release-v\" was ignored): {cl}"
    );
}

// ---------------------------------------------------------------------------
// Mode 3: workspace per-crate
// ---------------------------------------------------------------------------

fn per_crate_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (name, ver) in [("core", "0.1.0"), ("cli", "0.2.0")] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"{ver}\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: percrate
changelog:
  files:
    per_crate: true
crates:
  - name: core
    path: crates/core
    tag_template: "core-v{{ .Version }}"
    version_sync:
      enabled: true
  - name: cli
    path: crates/cli
    tag_template: "cli-v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "core-v0.1.0"]);
    run_git(root, &["tag", "cli-v0.2.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core touched\n").unwrap();
    git_add_commit(root, "feat: core change");
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli touched\n").unwrap();
    git_add_commit(root, "fix: cli change");
    tmp
}

#[test]
fn per_crate_write_refreshes_each_crate_file() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--write"]);
    assert!(
        r.success,
        "per-crate write failed: {}\n{}",
        r.stdout, r.stderr
    );
    let core = read(root, "crates/core/CHANGELOG.md");
    let cli = read(root, "crates/cli/CHANGELOG.md");
    assert!(core.contains("core change"), "core section missing: {core}");
    assert!(cli.contains("cli change"), "cli section missing: {cli}");
    // Each crate's range is bounded by ITS own tag, so the other crate's
    // commit must not bleed in.
    assert!(
        !core.contains("cli change"),
        "cli commit leaked into core: {core}"
    );
    assert!(
        !cli.contains("core change"),
        "core commit leaked into cli: {cli}"
    );
}

#[test]
fn per_crate_preview_separates_multiple_targets() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q"]);
    assert!(r.success, "preview failed: {}\n{}", r.stdout, r.stderr);
    // Two per-crate files → attributable `--- <path> ---` separators.
    assert!(
        r.stdout.contains("--- crates/core/CHANGELOG.md ---"),
        "missing core separator: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("--- crates/cli/CHANGELOG.md ---"),
        "missing cli separator: {}",
        r.stdout
    );
}

#[test]
fn per_crate_filter_restricts_to_one_crate() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--write", "--crate", "core"]);
    assert!(
        r.success,
        "filtered write failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        root.join("crates/core/CHANGELOG.md").exists(),
        "--crate core must refresh core"
    );
    assert!(
        !root.join("crates/cli/CHANGELOG.md").exists(),
        "--crate core must not touch cli"
    );
}

// ---------------------------------------------------------------------------
// Range parsing: single tag resolves crate + predecessor
// ---------------------------------------------------------------------------

#[test]
fn single_tag_resolves_owning_crate_and_predecessor() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    // Add an older core tag so the predecessor of core-v0.3.0 is core-v0.2.0.
    run_git(root, &["tag", "core-v0.2.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core 0.3\n").unwrap();
    git_add_commit(root, "feat: core toward 0.3");
    run_git(root, &["tag", "core-v0.3.0"]);

    // `changelog core-v0.3.0 --format json` targets ONLY core, range
    // core-v0.2.0..core-v0.3.0.
    let r = changelog(root, &["-q", "core-v0.3.0", "--format", "json"]);
    assert!(
        r.success,
        "single-tag json failed: {}\n{}",
        r.stdout, r.stderr
    );
    let v: serde_json::Value = serde_json::from_str(&r.stdout).unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 1, "single tag pins to one crate: {}", r.stdout);
    assert_eq!(arr[0]["crate"], "core");
    assert_eq!(
        arr[0]["from"], "core-v0.2.0",
        "predecessor wrong: {}",
        r.stdout
    );
    assert_eq!(arr[0]["to"], "core-v0.3.0");
}

// ---------------------------------------------------------------------------
// release-notes format (regression: grouped-bullet body)
// ---------------------------------------------------------------------------

#[test]
fn release_notes_format_emits_grouped_bullets() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // The standalone `changelog` command is a LOCAL preview: it renders a tag's
    // window WITHOUT requiring HEAD to sit at that tag (no checkout). Tag the
    // feat commit as v0.2.0, then add a FURTHER commit so HEAD is BEHIND the
    // v0.2.0 tag's checkout state, proving the tag-at-HEAD guard is bypassed for
    // the preview.
    run_git(root, &["tag", "v0.2.0"]);
    fs::write(root.join("crates/app/src/lib.rs"), "// moved past v0.2.0\n").unwrap();
    git_add_commit(root, "chore: move HEAD past the tag");
    let r = changelog(root, &["-q", "v0.2.0", "--format", "release-notes"]);
    assert!(
        r.success,
        "release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        !r.stderr.contains("does not point at HEAD"),
        "the standalone preview must NOT require HEAD at the tag: {}",
        r.stderr
    );
    assert!(
        r.stdout.contains("add a thing"),
        "release notes must list the commit: {}",
        r.stdout
    );
}

/// anodizer authors its own version-sync bump commits (`chore(release): bump
/// …`). They are release machinery and must NOT appear in generated notes by
/// default — even when the repo configures no `changelog.filters` block.
#[test]
fn release_notes_excludes_version_sync_bump_by_default() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    fs::write(root.join("crates/app/src/lib.rs"), "// bumped\n").unwrap();
    git_add_commit(root, "chore(release): bump workspace → 0.2.0 [skip ci]");
    // A Revert of a bump is a real correction, not machinery — it must be KEPT
    // (the exclude pattern is anchored, so `Revert "chore(release): bump …"`
    // does not match).
    fs::write(root.join("crates/app/src/lib.rs"), "// reverted\n").unwrap();
    git_add_commit(root, "Revert \"chore(release): bump workspace → 0.2.0\"");
    let r = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(
        r.success,
        "release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("add a thing"),
        "the real commit must still appear: {}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("[skip ci]"),
        "the version-sync bump commit (carrying [skip ci]) must be excluded: {}",
        r.stdout
    );
    assert!(
        r.stdout.contains("Revert"),
        "a Revert of a bump is a real correction and must be kept: {}",
        r.stdout
    );
}

/// `changelog.filters.exclude_version_sync_commits: false` opts back in — the
/// bump commit is kept in the generated notes.
#[test]
fn release_notes_keeps_version_sync_bump_when_opted_out() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: single
changelog:
  filters:
    exclude_version_sync_commits: false
crates:
  - name: app
    path: crates/app
    tag_template: "v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_add_commit(root, "chore: opt out of version-sync exclusion");
    fs::write(root.join("crates/app/src/lib.rs"), "// bumped\n").unwrap();
    git_add_commit(root, "chore(release): bump workspace → 0.2.0 [skip ci]");
    let r = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(
        r.success,
        "release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("bump workspace"),
        "opt-out must keep the version-sync bump commit: {}",
        r.stdout
    );
}

/// The exclusion must also apply to the DEFAULT `keep-a-changelog` format and to
/// `--format json` — not just `release-notes`. These share the render path that
/// previously re-derived filters without the version-sync auto-exclude, so the
/// default `changelog` / `--write` / committed `CHANGELOG.md` leaked the bump.
#[test]
fn keep_a_changelog_and_json_also_exclude_version_sync_bump() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    fs::write(root.join("crates/app/src/lib.rs"), "// bumped\n").unwrap();
    git_add_commit(root, "chore(release): bump workspace → 0.2.0 [skip ci]");

    // Default format = keep-a-changelog (previews the [Unreleased] section).
    let kac = changelog(root, &["-q"]);
    assert!(kac.success, "kac failed: {}\n{}", kac.stdout, kac.stderr);
    assert!(
        kac.stdout.contains("add a thing"),
        "kac must show the real commit: {}",
        kac.stdout
    );
    assert!(
        !kac.stdout.contains("[skip ci]"),
        "kac must exclude the version-sync bump commit: {}",
        kac.stdout
    );

    let json = changelog(root, &["-q", "--format", "json"]);
    assert!(
        json.success,
        "json failed: {}\n{}",
        json.stdout, json.stderr
    );
    assert!(
        !json.stdout.contains("[skip ci]"),
        "json must exclude the version-sync bump commit: {}",
        json.stdout
    );
}

/// anodizer's three bump-subject builders must all carry the `chore(release):
/// bump ` prefix the auto-exclude matches. Drive a real `anodizer tag` through
/// the single-crate version_sync path (the builder that used to emit
/// `chore: bump … to …`) and confirm the written subject is matchable — a guard
/// against the builders drifting away from `VERSION_SYNC_BUMP_PATTERN`.
#[test]
fn real_single_crate_tag_bump_subject_matches_exclude_prefix() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // `--crate app` drives the single-crate version_sync bump-commit builder
    // (the one that emitted `chore: bump … to …` before normalization).
    let out = anodizer()
        .current_dir(root)
        .args(["tag", "--crate", "app"])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "tag failed: {}\n{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    let log = anodizer_core::test_helpers::output_with_spawn_retry(
        || {
            let mut cmd = Command::new("git");
            cmd.current_dir(root).args(["log", "-1", "--format=%s"]);
            cmd
        },
        "git",
    );
    let subject = String::from_utf8_lossy(&log.stdout);
    let subject = subject.trim();
    assert!(
        subject.starts_with("chore(release): bump "),
        "the single-crate version-sync bump subject must carry the auto-exclude \
         prefix, got: {subject:?}"
    );
}

/// Bare `changelog --format release-notes` (no positional, no `--snapshot`) with
/// the last tag BEHIND HEAD must render the pending last-tag..HEAD window — the
/// same set kac/json show for the identical state — with NO release-time guards:
/// no tag-at-HEAD error, no `skipping changelog` line.
#[test]
fn bare_release_notes_renders_pending_window_no_guards() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // single_crate_repo leaves v0.1.0 tagged with one post-tag commit ("add a
    // thing") on HEAD — the pending window.
    let r = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(
        r.success,
        "bare release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        !r.stderr.contains("does not point at HEAD"),
        "bare preview must NOT require a checkout: {}",
        r.stderr
    );
    assert!(
        !mentions_changelog_stage_skip(&r.stdout) && !mentions_changelog_stage_skip(&r.stderr),
        "bare preview must NOT hit the snapshot-skip gate: {}\n{}",
        r.stdout,
        r.stderr
    );
    assert!(
        r.stdout.contains("add a thing"),
        "bare preview must show the pending commit: {}",
        r.stdout
    );
}

/// Workspace-LOCKSTEP shape: `[workspace.package].version` set, members
/// inheriting it, one shared `v*` tag track, the last tag BEHIND HEAD. Bare
/// `changelog --format release-notes` (no checkout, NO `--snapshot`) must render
/// the pending aggregate body and exit success — proving the tag-at-HEAD guard
/// is bypassed in lockstep mode too (the mandatory third config-mode axis).
#[test]
fn lockstep_release_notes_renders_pending_window_no_guards() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n\n[workspace.package]\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    for name in ["core", "cli"] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion.workspace = true\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: lockstep\nchangelog: {}\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    // Post-tag commit leaves the shared `v0.1.0` tag BEHIND HEAD: the pending
    // aggregate window is v0.1.0..HEAD.
    fs::write(root.join("crates/core/src/lib.rs"), "// touched\n").unwrap();
    git_add_commit(root, "feat: lockstep pending change");

    let r = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(
        r.success,
        "lockstep release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        !r.stderr.contains("does not point at HEAD"),
        "lockstep preview must NOT require a checkout: {}",
        r.stderr
    );
    assert!(
        !mentions_changelog_stage_skip(&r.stdout) && !mentions_changelog_stage_skip(&r.stderr),
        "lockstep preview must NOT hit the snapshot-skip gate: {}\n{}",
        r.stdout,
        r.stderr
    );
    assert!(
        r.stdout.contains("lockstep pending change"),
        "lockstep preview must show the pending aggregate commit: {}",
        r.stdout
    );
}

/// `changelog --snapshot --format release-notes` against a fixture WITHOUT
/// `changelog.snapshot: true` must still render — the standalone command bypasses
/// the snapshot-skip config gate that the release pipeline honors.
#[test]
fn snapshot_release_notes_renders_without_config_opt_in() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // single_crate_repo's config is `changelog: {}` — snapshot opt-in is UNSET.
    let r = changelog(root, &["-q", "--snapshot", "--format", "release-notes"]);
    assert!(
        r.success,
        "snapshot release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        !mentions_changelog_stage_skip(&r.stdout) && !mentions_changelog_stage_skip(&r.stderr),
        "the standalone command must bypass the `changelog.snapshot` gate: {}\n{}",
        r.stdout,
        r.stderr
    );
    assert!(
        r.stdout.contains("add a thing"),
        "snapshot preview must show the pending commit: {}",
        r.stdout
    );
}

// ---------------------------------------------------------------------------
// json format shape
// ---------------------------------------------------------------------------

#[test]
fn json_format_emits_sorted_array_with_crate_field() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--format", "json"]);
    assert!(r.success, "json failed: {}\n{}", r.stdout, r.stderr);
    let v: serde_json::Value = serde_json::from_str(&r.stdout).unwrap();
    let arr = v.as_array().expect("json output must be an array");
    assert_eq!(arr.len(), 2, "one element per crate: {}", r.stdout);
    // Sorted by crate name: cli before core.
    assert_eq!(arr[0]["crate"], "cli");
    assert_eq!(arr[1]["crate"], "core");
    // Each element carries the documented payload fields.
    for elem in arr {
        assert!(elem.get("crate").is_some());
        assert!(elem.get("to").is_some());
        assert!(elem.get("groups").is_some());
    }
}

// ---------------------------------------------------------------------------
// --write + non-kac format error (end-to-end through clap)
// ---------------------------------------------------------------------------

#[test]
fn write_with_release_notes_format_is_rejected() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--write", "--format", "release-notes"]);
    assert!(!r.success, "--write + release-notes must fail");
    assert!(
        r.stderr.contains("--write is only valid"),
        "expected the write/format error: {}",
        r.stderr
    );
}

#[test]
fn explicit_range_overrides_auto_discovery() {
    let tmp = single_crate_repo();
    let root = tmp.path();
    // `changelog v0.1.0..HEAD --format json` feeds the exact range.
    let r = changelog(root, &["-q", "v0.1.0..HEAD", "--format", "json"]);
    assert!(r.success, "range json failed: {}\n{}", r.stdout, r.stderr);
    let v: serde_json::Value = serde_json::from_str(&r.stdout).unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr[0]["from"], "v0.1.0");
    assert_eq!(arr[0]["to"], "HEAD");
}

// ---------------------------------------------------------------------------
// Range consistency: empty-from = full history, uniformly across formats
// ---------------------------------------------------------------------------

/// A single-crate repo with two tagged releases and a commit AFTER the latest
/// tag, so "since the last release" (v0.2.0..HEAD) is a strict subset of full
/// history. The pre-v0.2.0 `feat:` commit ("early feature") is the discriminator:
/// it appears under full history but not under the pending window.
fn two_release_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/app\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/app/src")).unwrap();
    fs::write(
        root.join("crates/app/Cargo.toml"),
        "[package]\nname = \"app\"\nversion = \"0.2.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/app/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: two-release
changelog:
  snapshot: true
crates:
  - name: app
    path: crates/app
    tag_template: "v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/app/src/lib.rs"), "// early\n").unwrap();
    git_add_commit(root, "feat: early feature");
    run_git(root, &["tag", "v0.2.0"]);
    fs::write(root.join("crates/app/src/lib.rs"), "// late\n").unwrap();
    git_add_commit(root, "fix: late fix");
    tmp
}

/// Collect every commit `summary` across all groups + nested subgroups of one
/// json changelog element.
fn json_summaries(elem: &serde_json::Value) -> Vec<String> {
    fn walk(group: &serde_json::Value, out: &mut Vec<String>) {
        if let Some(entries) = group.get("entries").and_then(|e| e.as_array()) {
            for e in entries {
                if let Some(s) = e.get("summary").and_then(|s| s.as_str()) {
                    out.push(s.to_string());
                }
            }
        }
        if let Some(subs) = group.get("subgroups").and_then(|g| g.as_array()) {
            for sub in subs {
                walk(sub, out);
            }
        }
    }
    let mut out = Vec::new();
    if let Some(groups) = elem.get("groups").and_then(|g| g.as_array()) {
        for g in groups {
            walk(g, &mut out);
        }
    }
    out
}

fn json_summaries_for_range(root: &Path, range: Option<&str>) -> Vec<String> {
    let mut args = vec!["-q"];
    if let Some(r) = range {
        args.push(r);
    }
    args.extend(["--format", "json"]);
    let r = changelog(root, &args);
    assert!(
        r.success,
        "json {range:?} failed: {}\n{}",
        r.stdout, r.stderr
    );
    let v: serde_json::Value = serde_json::from_str(&r.stdout).unwrap();
    let arr = v.as_array().unwrap();
    assert_eq!(arr.len(), 1, "single-crate repo yields one element");
    json_summaries(&arr[0])
}

fn release_notes_for_range(root: &Path, range: Option<&str>) -> String {
    let mut args = vec!["-q"];
    if let Some(r) = range {
        args.push(r);
    }
    args.extend(["--snapshot", "--format", "release-notes"]);
    let r = changelog(root, &args);
    assert!(
        r.success,
        "release-notes {range:?} failed: {}\n{}",
        r.stdout, r.stderr
    );
    r.stdout
}

/// `changelog ..` and `changelog ..HEAD` must converge: both are full history
/// and both include the pre-v0.2.0 commit, for json AND release-notes.
#[test]
fn full_history_dotdot_and_dotdot_head_converge() {
    let tmp = two_release_repo();
    let root = tmp.path();

    // json: identical commit sets, and both include the early (pre-latest-tag)
    // commit — proving empty-from = full history, not last-tag.
    let mut a = json_summaries_for_range(root, Some(".."));
    let mut b = json_summaries_for_range(root, Some("..HEAD"));
    a.sort();
    b.sort();
    assert_eq!(
        a, b,
        "`..` and `..HEAD` json must be identical: {a:?} vs {b:?}"
    );
    assert!(
        a.iter().any(|s| s.contains("early feature")),
        "full history must include the pre-v0.2.0 commit: {a:?}"
    );
    assert!(
        a.iter().any(|s| s.contains("late fix")),
        "full history must include the post-v0.2.0 commit: {a:?}"
    );

    // release-notes: both include the early commit (same full-history bound).
    for range in [Some(".."), Some("..HEAD")] {
        let notes = release_notes_for_range(root, range);
        assert!(
            notes.contains("early feature"),
            "release-notes {range:?} (full history) must include the early commit:\n{notes}"
        );
        assert!(
            notes.contains("late fix"),
            "release-notes {range:?} (full history) must include the late commit:\n{notes}"
        );
    }
}

/// The omitted form (pending / since-last-release) must NOT equal `..`: it
/// covers only commits since v0.2.0, excluding the early one.
#[test]
fn omitted_range_is_pending_not_full_history() {
    let tmp = two_release_repo();
    let root = tmp.path();

    let omitted = json_summaries_for_range(root, None);
    assert!(
        omitted.iter().all(|s| !s.contains("early feature")),
        "omitted (pending) range must exclude the pre-v0.2.0 commit: {omitted:?}"
    );
    assert!(
        omitted.iter().any(|s| s.contains("late fix")),
        "omitted (pending) range must include the post-v0.2.0 commit: {omitted:?}"
    );

    let full = json_summaries_for_range(root, Some(".."));
    assert!(
        full.len() > omitted.len(),
        "full history must cover strictly more than the pending window: full={full:?} pending={omitted:?}"
    );
}

/// For the SAME range arg, json and release-notes must surface the SAME commit
/// set — for the OMITTED (pending) range, full history (`..HEAD`), and an
/// explicit `v0.1.0..HEAD`.
#[test]
fn cross_format_commit_set_is_consistent() {
    let tmp = two_release_repo();
    let root = tmp.path();

    // OMITTED (pending): HEAD is one commit ahead of the latest tag (v0.2.0).
    // Both formats must bound at v0.2.0 — including the post-tag "late fix" and
    // EXCLUDING the pre-tag "early feature". This is the regression guard: a
    // prior build leaked full history through `--snapshot --format
    // release-notes` because `resolve_prev_tag` dropped the auto-discovered
    // previous tag when it equalled the snapshot's current `Tag`.
    let pending_json = json_summaries_for_range(root, None);
    let pending_notes = release_notes_for_range(root, None);
    assert!(
        pending_json.iter().any(|s| s.contains("late fix")),
        "json pending must include the post-tag commit: {pending_json:?}"
    );
    assert!(
        pending_json.iter().all(|s| !s.contains("early feature")),
        "json pending must EXCLUDE the pre-tag commit: {pending_json:?}"
    );
    assert!(
        pending_notes.contains("late fix"),
        "release-notes pending must include the post-tag commit:\n{pending_notes}"
    );
    assert!(
        !pending_notes.contains("early feature"),
        "release-notes pending must EXCLUDE the pre-tag commit (full-history leak):\n{pending_notes}"
    );

    // Full history: early + late appear in BOTH formats.
    let full_json = json_summaries_for_range(root, Some("..HEAD"));
    let full_notes = release_notes_for_range(root, Some("..HEAD"));
    for needle in ["early feature", "late fix"] {
        assert!(
            full_json.iter().any(|s| s.contains(needle)),
            "json full history missing {needle:?}: {full_json:?}"
        );
        assert!(
            full_notes.contains(needle),
            "release-notes full history missing {needle:?}:\n{full_notes}"
        );
    }

    // Explicit `v0.1.0..HEAD`: starts at v0.1.0, so early + late both appear in
    // BOTH formats (the v0.1.0 "initial" commit is the lower bound, excluded).
    let exp_json = json_summaries_for_range(root, Some("v0.1.0..HEAD"));
    let exp_notes = release_notes_for_range(root, Some("v0.1.0..HEAD"));
    for needle in ["early feature", "late fix"] {
        assert!(
            exp_json.iter().any(|s| s.contains(needle)),
            "json v0.1.0..HEAD missing {needle:?}: {exp_json:?}"
        );
        assert!(
            exp_notes.contains(needle),
            "release-notes v0.1.0..HEAD missing {needle:?}:\n{exp_notes}"
        );
    }
}

/// Single-crate, HEAD one commit ahead of the latest tag: the OMITTED pending
/// range through `--snapshot --format release-notes` must show exactly the
/// since-last-release set (the post-tag "late fix"), never the pre-tag "early
/// feature" — matching the json and keep-a-changelog pending output. The
/// snapshot `Tag` resolves to the latest existing tag (v0.2.0) here, the exact
/// condition under which release-notes previously leaked full history.
#[test]
fn snapshot_release_notes_pending_matches_engine_formats() {
    let tmp = two_release_repo();
    let root = tmp.path();

    let notes = release_notes_for_range(root, None);
    assert!(
        notes.contains("late fix"),
        "release-notes pending must include the post-tag commit:\n{notes}"
    );
    assert!(
        !notes.contains("early feature"),
        "release-notes pending leaked the pre-tag commit (full-history bug):\n{notes}"
    );

    // The same pending set must come out of json and keep-a-changelog.
    let json = json_summaries_for_range(root, None);
    assert!(json.iter().any(|s| s.contains("late fix")), "{json:?}");
    assert!(
        json.iter().all(|s| !s.contains("early feature")),
        "{json:?}"
    );

    let kac = changelog(root, &["-q"]);
    assert!(kac.success, "kac failed: {}\n{}", kac.stdout, kac.stderr);
    assert!(
        kac.stdout.contains("late fix") && !kac.stdout.contains("early feature"),
        "kac pending mismatch:\n{}",
        kac.stdout
    );
}

/// Workspace per-crate: each crate's pending release-notes window is bounded at
/// ITS OWN last tag, never full history and never the other crate's commits.
/// Both crates have HEAD ahead of their latest tag, so this exercises the
/// snapshot previous-tag resolution per crate (mode-agnostic regression).
fn per_crate_snapshot_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (name, ver) in [("core", "0.2.0"), ("cli", "0.3.0")] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"{ver}\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: percrate-snap
changelog:
  snapshot: true
  files:
    per_crate: true
crates:
  - name: core
    path: crates/core
    tag_template: "core-v{{ .Version }}"
    version_sync:
      enabled: true
  - name: cli
    path: crates/cli
    tag_template: "cli-v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_init(root);
    // Each crate gets a pre-tag commit, then a tag, then a post-tag commit, so
    // "since last release" is a strict subset of full history for both.
    git_add_commit(root, "initial");
    run_git(root, &["tag", "core-v0.1.0"]);
    run_git(root, &["tag", "cli-v0.1.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core early\n").unwrap();
    git_add_commit(root, "feat: core early");
    run_git(root, &["tag", "core-v0.2.0"]);
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli early\n").unwrap();
    git_add_commit(root, "feat: cli early");
    run_git(root, &["tag", "cli-v0.3.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core late\n").unwrap();
    git_add_commit(root, "fix: core late");
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli late\n").unwrap();
    git_add_commit(root, "fix: cli late");
    tmp
}

#[test]
fn per_crate_snapshot_release_notes_bounds_at_each_crate_tag() {
    let tmp = per_crate_snapshot_repo();
    let root = tmp.path();

    // core's pending window is core-v0.2.0..HEAD: "core late", not "core early".
    let core = release_notes_for_crate(root, "core");
    assert!(
        core.contains("core late"),
        "core pending must include its post-tag commit:\n{core}"
    );
    assert!(
        !core.contains("core early"),
        "core pending leaked its pre-tag commit (full-history bug):\n{core}"
    );
    assert!(
        !core.contains("cli late") && !core.contains("cli early"),
        "cli commits leaked into core's notes:\n{core}"
    );

    // cli's pending window is cli-v0.3.0..HEAD: "cli late", not "cli early".
    let cli = release_notes_for_crate(root, "cli");
    assert!(
        cli.contains("cli late"),
        "cli pending must include its post-tag commit:\n{cli}"
    );
    assert!(
        !cli.contains("cli early"),
        "cli pending leaked its pre-tag commit (full-history bug):\n{cli}"
    );
    assert!(
        !cli.contains("core late") && !cli.contains("core early"),
        "core commits leaked into cli's notes:\n{cli}"
    );
}

/// Run `anodizer changelog --crate <name> --snapshot --format release-notes`
/// (omitted range = pending) and return stdout.
fn release_notes_for_crate(root: &Path, crate_name: &str) -> String {
    let r = changelog(
        root,
        &[
            "-q",
            "--crate",
            crate_name,
            "--snapshot",
            "--format",
            "release-notes",
        ],
    );
    assert!(
        r.success,
        "release-notes --crate {crate_name} failed: {}\n{}",
        r.stdout, r.stderr
    );
    r.stdout
}

// ---------------------------------------------------------------------------
// Same-prefix shared-root collapse: N crates all on `v{{ Version }}` routing to
// one shared root CHANGELOG.md are a SINGLE flat lockstep aggregate, not N
// multi-track `### <crate>` subsections.
// ---------------------------------------------------------------------------

/// A flat `crates:` workspace whose members ALL share `tag_template:
/// "v{{ Version }}"` and route to one shared root (no `per_crate`/`root`
/// config), with a curated flat `## [Unreleased]`, a `v0.1.0` tag, and post-tag
/// commits. The curated `### <Heading>` titles deliberately do NOT match the
/// configured `groups:` — the exact shape that tripped the multi-track
/// heuristic and grafted a spurious `### <crate>` subsection.
fn same_prefix_shared_root_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (name, ver) in [("core", "0.1.0"), ("cli", "0.1.0")] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"{ver}\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: aggregate
changelog:
  groups:
    - title: Features
      regexp: "^feat"
crates:
  - name: core
    path: crates/core
    tag_template: "v{{ .Version }}"
  - name: cli
    path: crates/cli
    tag_template: "v{{ .Version }}"
"#,
    )
    .unwrap();
    // Curated flat [Unreleased] whose H3 titles (`### Docs`, `### Fixes`) are NOT
    // configured group titles — the multi-track-misread trap.
    fs::write(
        root.join("CHANGELOG.md"),
        "# Changelog\n\n## [Unreleased]\n\n### Docs\n\n- hand-written prose\n\n### Fixes\n\n- curated fix note\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core\n").unwrap();
    git_add_commit(root, "feat: aggregate change in core");
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli\n").unwrap();
    git_add_commit(root, "feat: aggregate change in cli");
    tmp
}

#[test]
fn same_prefix_shared_root_collapses_to_one_flat_unreleased() {
    let tmp = same_prefix_shared_root_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q"]);
    assert!(r.success, "preview failed: {}\n{}", r.stdout, r.stderr);

    // ONE flat [Unreleased] section, no `--- <path> ---` per-crate separators.
    assert_eq!(
        r.stdout.matches("## [Unreleased]").count(),
        1,
        "expected exactly one [Unreleased] section: {}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("---"),
        "flat aggregate must not emit per-crate separators: {}",
        r.stdout
    );
    // No `### <crate>` NOR `### <project_name>` graft (the aggregate is keyed by
    // `aggregate`): reject any [Unreleased] H3 that isn't the configured group.
    assert!(
        !r.stdout.contains("### core") && !r.stdout.contains("### cli"),
        "flat aggregate must not graft a `### <crate>` subsection: {}",
        r.stdout
    );
    assert_no_subsection_graft(&r.stdout, &["Features"]);
    // The regenerated body reflects BOTH members' post-tag commits (whole-repo).
    assert!(
        r.stdout.contains("aggregate change in core")
            && r.stdout.contains("aggregate change in cli"),
        "regenerated flat body must aggregate every member's commits: {}",
        r.stdout
    );
}

#[test]
fn same_prefix_shared_root_write_is_flat() {
    let tmp = same_prefix_shared_root_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "--write"]);
    assert!(r.success, "write failed: {}\n{}", r.stdout, r.stderr);
    let cl = read(root, "CHANGELOG.md");
    assert_eq!(
        cl.matches("## [Unreleased]").count(),
        1,
        "written file must keep a single [Unreleased]: {cl}"
    );
    assert!(
        !cl.contains("### core") && !cl.contains("### cli"),
        "written file must not graft a `### <crate>` subsection: {cl}"
    );
    assert_no_subsection_graft(&cl, &["Features"]);
    assert!(
        cl.contains("aggregate change in core") && cl.contains("aggregate change in cli"),
        "written flat body must aggregate every member's commits: {cl}"
    );
    // No per-crate files for a shared-root aggregate.
    assert!(
        !root.join("crates/core/CHANGELOG.md").exists()
            && !root.join("crates/cli/CHANGELOG.md").exists(),
        "flat aggregate must not write per-crate files"
    );
}

/// release-notes on a same-prefix shared-root repo collapses to ONE aggregate
/// body — no `### <crate>`/`### <project_name>` graft, no `--- <crate> ---`
/// per-crate separators, both members' commits in one block. HEAD is tagged
/// `v0.2.0` and the EXPLICIT `v0.1.0..v0.2.0` range drives a non-empty body
/// (the changelog stage requires HEAD at the upper tag). An explicit range
/// (unlike a single-tag positional, which pins to the tag's owning crate)
/// applies to every target, exercising the no-filter aggregate collapse.
#[test]
fn same_prefix_shared_root_release_notes_is_one_aggregate() {
    let tmp = same_prefix_shared_root_repo();
    let root = tmp.path();
    run_git(root, &["tag", "v0.2.0"]);
    let r = changelog(root, &["-q", "v0.1.0..v0.2.0", "--format", "release-notes"]);
    assert!(
        r.success,
        "release-notes failed: {}\n{}",
        r.stdout, r.stderr
    );
    let out = &r.stdout;
    // ONE aggregate body: no per-crate `--- <crate> ---` separators.
    assert!(
        !out.contains("---\ncore\n---") && !out.contains("---\ncli\n---"),
        "release-notes flat aggregate must not emit per-crate separators: {out}"
    );
    // No `### <crate>` NOR `### <project_name>` graft.
    for c in ["### core", "### cli", "### aggregate"] {
        assert!(
            !out.contains(c),
            "spurious `{c}` graft in release-notes: {out}"
        );
    }
    // Both members' commits land in the single aggregate body (whole-repo).
    assert!(
        out.contains("aggregate change in core") && out.contains("aggregate change in cli"),
        "release-notes aggregate body must span every member's commits: {out}"
    );
}

/// Contrast: a workspace with DISTINCT tag prefixes (`core-v*` + `cli-v*`)
/// curating a multi-track root must STILL refresh each crate's own
/// `### <crate>` subsection — the collapse must not regress genuine multi-track.
#[test]
fn distinct_prefix_multitrack_keeps_crate_subsections() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (name, ver) in [("core", "0.1.0"), ("cli", "0.2.0")] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"{ver}\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: multitrack
changelog:
  groups:
    - title: Features
      regexp: "^feat"
crates:
  - name: core
    path: crates/core
    tag_template: "core-v{{ .Version }}"
  - name: cli
    path: crates/cli
    tag_template: "cli-v{{ .Version }}"
"#,
    )
    .unwrap();
    // Curated multi-track root: a `### core` + `### cli` subsection each.
    fs::write(
        root.join("CHANGELOG.md"),
        "# Changelog\n\n## [Unreleased]\n\n### core\n\n- old core note\n\n### cli\n\n- old cli note\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "core-v0.1.0"]);
    run_git(root, &["tag", "cli-v0.2.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core\n").unwrap();
    git_add_commit(root, "feat: distinct core change");
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli\n").unwrap();
    git_add_commit(root, "feat: distinct cli change");

    let r = changelog(root, &["-q", "--write"]);
    assert!(
        r.success,
        "multitrack write failed: {}\n{}",
        r.stdout, r.stderr
    );
    let cl = read(root, "CHANGELOG.md");
    // Both crate subsections survive; each regenerated from its own track.
    assert!(
        cl.contains("### core") && cl.contains("### cli"),
        "genuine multi-track must keep both `### <crate>` subsections: {cl}"
    );
    assert!(
        cl.contains("distinct core change"),
        "core subsection must regenerate from core's commits: {cl}"
    );
    assert!(
        cl.contains("distinct cli change"),
        "cli subsection must regenerate from cli's commits: {cl}"
    );
}

/// The comprehensive dogfood regression mirroring anodizer's own
/// `.anodizer.yaml`: N crates all on `v{{ Version }}`, a `changelog:` block with
/// a commit `format` carrying `{{ .SHA }}` / `{{ .Message }}` /
/// `{{ .AuthorUsername }}` + groups, a shared root, a curated flat
/// `## [Unreleased]` whose H3 titles diverge from the configured groups, a `v*`
/// tag, and post-tag commits. The combined output must be CLEAN:
///   (a) ONE flat [Unreleased], no `### <crate>` graft;
///   (b) single `* ` bullets, no `* *`;
///   (c) authors render as NAMES, no empty `()`;
///   (d) generated bullets reflect the since-tag commits.
#[test]
fn dogfood_flat_aggregate_render_is_clean() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\", \"crates/api\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for name in ["core", "cli", "api"] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"0.5.0\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: dogfood
changelog:
  use: github-native
  format: "* {{ .SHA }} {{ .Message }} ({{ .AuthorUsername }})"
  abbrev: 12
  groups:
    - title: Features
      regexp: "^feat"
      order: 0
    - title: Bug Fixes
      regexp: "^fix"
      order: 1
crates:
  - name: core
    path: crates/core
    tag_template: "v{{ .Version }}"
  - name: cli
    path: crates/cli
    tag_template: "v{{ .Version }}"
  - name: api
    path: crates/api
    tag_template: "v{{ .Version }}"
"#,
    )
    .unwrap();
    // Curated flat [Unreleased] whose H3 titles diverge from the groups.
    fs::write(
        root.join("CHANGELOG.md"),
        "# Changelog\n\n## [Unreleased]\n\n### CI / Workflows\n\n- curated CI note\n\n### Docs\n\n- curated docs note\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.5.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// core\n").unwrap();
    git_add_commit(root, "feat: dogfood core capability");
    fs::write(root.join("crates/cli/src/lib.rs"), "// cli\n").unwrap();
    git_add_commit(root, "fix: dogfood cli bug");

    // Default format (keep-a-changelog). github-native falls back to `git`
    // locally (no GitHub login), so author names come from the local commits.
    let r = changelog(root, &["-q"]);
    assert!(
        r.success,
        "dogfood preview failed: {}\n{}",
        r.stdout, r.stderr
    );
    let out = &r.stdout;

    // (a) one flat [Unreleased], no `### <crate>` NOR `### <project_name>`
    // graft. The aggregate is keyed by project_name (`dogfood`), so a regressed
    // render-side `single_track` guard would graft `### dogfood`, not
    // `### core`; assert against both, and robustly reject ANY `### ` heading in
    // the [Unreleased] block that isn't a configured group title.
    assert_eq!(
        out.matches("## [Unreleased]").count(),
        1,
        "expected one flat [Unreleased]: {out}"
    );
    for c in ["### core", "### cli", "### api", "### dogfood"] {
        assert!(!out.contains(c), "spurious `{c}` graft: {out}");
    }
    assert_no_subsection_graft(out, &["Features", "Bug Fixes"]);
    // (b) no `* *` double bullets.
    assert!(!out.contains("* *"), "double bullet emitted: {out}");
    // (c) author renders as a NAME, no empty `()`.
    assert!(
        out.contains("(Test)"),
        "author must render as the committer name: {out}"
    );
    assert!(!out.contains("()"), "empty author parens emitted: {out}");
    // (d) generated bullets reflect the since-tag commits.
    assert!(
        out.contains("dogfood core capability") && out.contains("dogfood cli bug"),
        "regenerated body must reflect since-tag commits: {out}"
    );
}

// ---------------------------------------------------------------------------
// github-native preview: the standalone command renders from LOCAL git instead
// of GitHub (whose body is generated at release time), requires no token, and
// never emits empty.
// ---------------------------------------------------------------------------

/// A single-crate repo configured `changelog.use: github-native` with a
/// `release.github` repo. The standalone `changelog --format release-notes`
/// must render LOCAL scm bullets (the pending window), emit the one-line
/// "previewing changelog from local git" note, require NO token, and be NON-empty.
fn github_native_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/app\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/app/src")).unwrap();
    fs::write(
        root.join("crates/app/Cargo.toml"),
        "[package]\nname = \"app\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/app/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: gh-native
changelog:
  use: github-native
crates:
  - name: app
    path: crates/app
    tag_template: "v{{ .Version }}"
    release:
      github:
        owner: octocat
        name: app
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/app/src/lib.rs"), "// touched\n").unwrap();
    git_add_commit(root, "feat: github-native local preview");
    tmp
}

#[test]
fn github_native_release_notes_previews_from_local_git() {
    let tmp = github_native_repo();
    let root = tmp.path();
    // No token set in the environment: a real github-native release would
    // require one, but the local preview must not.
    let mut cmd = anodizer();
    cmd.current_dir(root)
        .arg("changelog")
        .args(["-q", "--format", "release-notes"])
        .env_remove("GITHUB_TOKEN")
        .env_remove("ANODIZER_GITHUB_TOKEN");
    let out = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        out.status.success(),
        "github-native preview failed: {stdout}\n{stderr}"
    );
    assert!(
        !stderr.contains("requires a GitHub token"),
        "github-native preview must NOT require a token: {stderr}"
    );
    assert!(
        stderr.contains("previewing changelog from local git"),
        "github-native preview must emit the one-line fallback note: {stderr}"
    );
    assert!(
        stdout.contains("github-native local preview"),
        "github-native preview must render the local commit (non-empty): {stdout}"
    );
}

// ---------------------------------------------------------------------------
// Multi-track (distinct tag prefixes) release-notes preview: each crate's
// pending window renders without a checkout, bounded at its own tag.
// ---------------------------------------------------------------------------

/// Multi-track (distinct-prefix `core-v*` / `cli-v*`) repo with each crate's
/// last tag BEHIND HEAD. `changelog --crate <name> --format release-notes`
/// (NO `--snapshot`, no checkout) must render that crate's pending window
/// bounded at its own tag — proving the preview bypass works in the per-crate
/// mode too.
#[test]
fn multitrack_release_notes_preview_bounds_at_each_crate_tag() {
    let tmp = per_crate_repo();
    let root = tmp.path();
    // per_crate_repo: core-v0.1.0 + cli-v0.2.0 tagged, then "feat: core change"
    // and "fix: cli change" on HEAD (each the pending window for its crate).
    let core = changelog(
        root,
        &["-q", "--crate", "core", "--format", "release-notes"],
    );
    assert!(
        core.success,
        "core release-notes preview failed: {}\n{}",
        core.stdout, core.stderr
    );
    assert!(
        !core.stderr.contains("does not point at HEAD"),
        "multitrack preview must NOT require a checkout: {}",
        core.stderr
    );
    assert!(
        core.stdout.contains("core change"),
        "core preview must show its pending commit: {}",
        core.stdout
    );
    assert!(
        !core.stdout.contains("cli change"),
        "cli commit leaked into core's preview: {}",
        core.stdout
    );

    let cli = changelog(root, &["-q", "--crate", "cli", "--format", "release-notes"]);
    assert!(
        cli.success,
        "cli release-notes preview failed: {}\n{}",
        cli.stdout, cli.stderr
    );
    assert!(
        cli.stdout.contains("cli change"),
        "cli preview must show its pending commit: {}",
        cli.stdout
    );
    assert!(
        !cli.stdout.contains("core change"),
        "core commit leaked into cli's preview: {}",
        cli.stdout
    );
}

// ---------------------------------------------------------------------------
// Flat-aggregate coherence guard: members sharing one tag prefix must agree on
// `[package].version` (one tag can't carry two versions). The guard fires
// identically for changelog / tag / bump.
// ---------------------------------------------------------------------------

/// A flat `crates:` workspace whose members share `tag_template:
/// "v{{ Version }}"` but carry the supplied (possibly divergent) versions.
fn flat_aggregate_versions_repo(core_ver: &str, cli_ver: &str) -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (name, ver) in [("core", core_ver), ("cli", cli_ver)] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion = \"{ver}\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: agg
changelog: {}
crates:
  - name: core
    path: crates/core
    tag_template: "v{{ .Version }}"
  - name: cli
    path: crates/cli
    tag_template: "v{{ .Version }}"
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    tmp
}

fn assert_coherence_error(stderr: &str) {
    assert!(
        stderr.contains("core") && stderr.contains("cli"),
        "{stderr}"
    );
    assert!(
        stderr.contains("0.5.0") && stderr.contains("0.1.0"),
        "names differing versions: {stderr}"
    );
    assert!(
        stderr.contains("prefix 'v'"),
        "names shared prefix: {stderr}"
    );
    assert!(
        stderr.contains("[workspace.package].version"),
        "steers toward lockstep: {stderr}"
    );
    assert!(
        stderr.contains("distinct tag_template prefix"),
        "steers toward independent prefixes: {stderr}"
    );
}

#[test]
fn changelog_rejects_divergent_flat_aggregate_versions() {
    let tmp = flat_aggregate_versions_repo("0.5.0", "0.1.0");
    let r = changelog(tmp.path(), &["-q"]);
    assert!(
        !r.success,
        "divergent flat aggregate must error: {}",
        r.stdout
    );
    assert_coherence_error(&r.stderr);
}

#[test]
fn changelog_accepts_agreeing_flat_aggregate_versions() {
    let tmp = flat_aggregate_versions_repo("0.2.0", "0.2.0");
    let r = changelog(tmp.path(), &["-q"]);
    assert!(
        r.success,
        "all-agree flat aggregate must work: {}\n{}",
        r.stdout, r.stderr
    );
}

#[test]
fn tag_rejects_divergent_flat_aggregate_versions() {
    let tmp = flat_aggregate_versions_repo("0.5.0", "0.1.0");
    let out = anodizer()
        .current_dir(tmp.path())
        .args(["tag", "--dry-run", "-q"])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "tag must error on divergent versions"
    );
    assert_coherence_error(&String::from_utf8_lossy(&out.stderr));
}

#[test]
fn bump_rejects_divergent_flat_aggregate_versions() {
    let tmp = flat_aggregate_versions_repo("0.5.0", "0.1.0");
    let out = anodizer()
        .current_dir(tmp.path())
        .args(["bump", "patch", "--workspace", "--dry-run", "-q"])
        .output()
        .unwrap();
    assert!(
        !out.status.success(),
        "bump must error on divergent versions"
    );
    assert_coherence_error(&String::from_utf8_lossy(&out.stderr));
}

// ---------------------------------------------------------------------------
// Subdirectory invocation: `changelog` must resolve the workspace root from
// the config (not the cwd), so a run from `crates/<x>` produces the same
// `[Unreleased]` preview as a run from the repo root — across all three modes.
// Regression guard for the cwd-as-root bug (known-bugs #4).
// ---------------------------------------------------------------------------

/// Run `changelog -q` against an explicit `--config` (the root `.anodizer.yaml`)
/// from `run_dir`. The explicit config isolates the workspace-root concern: the
/// fix derives the root by walking up from the config's parent, so the same
/// config resolves the same root whether `run_dir` is the repo root or a
/// subdirectory beneath it.
fn changelog_preview_from(run_dir: &Path, config: &Path) -> RunResult {
    changelog(
        run_dir,
        &["-q", "--config", config.to_str().expect("utf8 config path")],
    )
}

fn assert_subdir_matches_root(fixture: &TempDir, subdir: &str) {
    let root = fixture.path();
    let config = root.join(".anodizer.yaml");
    let from_root = changelog_preview_from(root, &config);
    assert!(
        from_root.success,
        "root invocation failed: {}\n{}",
        from_root.stdout, from_root.stderr
    );
    let from_subdir = changelog_preview_from(&root.join(subdir), &config);
    assert!(
        from_subdir.success,
        "subdir invocation failed: {}\n{}",
        from_subdir.stdout, from_subdir.stderr
    );
    assert_eq!(
        from_subdir.stdout, from_root.stdout,
        "changelog preview from {subdir} must match the repo-root preview \
         (workspace root resolved against cwd instead of the config)"
    );
}

#[test]
fn single_crate_changelog_from_subdir_matches_root() {
    let tmp = single_crate_repo();
    assert_subdir_matches_root(&tmp, "crates/app");
}

#[test]
fn lockstep_changelog_from_subdir_matches_root() {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n\n[workspace.package]\nversion = \"0.1.0\"\n",
    )
    .unwrap();
    for name in ["core", "cli"] {
        fs::create_dir_all(root.join(format!("crates/{name}/src"))).unwrap();
        fs::write(
            root.join(format!("crates/{name}/Cargo.toml")),
            format!("[package]\nname = \"{name}\"\nversion.workspace = true\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(format!("crates/{name}/src/lib.rs")), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: lockstep\nchangelog: {}\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(root.join("crates/core/src/lib.rs"), "// touched\n").unwrap();
    git_add_commit(root, "feat: lockstep change");

    assert_subdir_matches_root(&tmp, "crates/core");
}

#[test]
fn per_crate_changelog_from_subdir_matches_root() {
    let tmp = per_crate_repo();
    assert_subdir_matches_root(&tmp, "crates/cli");
}

// ---------------------------------------------------------------------------
// Config-shape × format matrix: the changelog command must render correctly
// across the FINITE set of config-shape encodings, in every format, leaving no
// preview `dist/` artifact. This is the exhaustive guard against a shape that
// is only tested under one encoding (the class of bug that left
// `workspaces:`-multi-track release-notes empty).
// ---------------------------------------------------------------------------

/// One config-shape encoding the changelog command must support.
struct ShapeCase {
    /// Diagnostic label.
    name: &'static str,
    /// `.anodizer.yaml` body.
    yaml: &'static str,
    /// `Cargo.toml` workspace members.
    members: &'static [&'static str],
    /// `(crate_dir, package_name, version)` per member.
    crates: &'static [(&'static str, &'static str, &'static str)],
    /// `(tag, on_commit_index)` to create after the listed commits — the seed
    /// commit is index 0. A post-tag commit per track makes the pending window
    /// non-empty.
    tags: &'static [&'static str],
    /// Post-seed commits (subject lines); each touches the crate dir named in
    /// `.0`. Applied in order AFTER `tags` are placed on the seed commit.
    post_tag_commits: &'static [(&'static str, &'static str)],
    /// Substrings every release-notes / json render must contain (one per
    /// track's post-tag commit), proving all tracks rendered non-empty.
    must_contain: &'static [&'static str],
    /// Expected element count for `--format json` (one per rendered track).
    json_len: usize,
}

/// Build a fixture repo for a [`ShapeCase`]: write the workspace + crates +
/// config, seed-commit + tag, then apply each post-tag commit.
fn build_shape_repo(case: &ShapeCase) -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    let members = case
        .members
        .iter()
        .map(|m| format!("\"{m}\""))
        .collect::<Vec<_>>()
        .join(", ");
    // Lockstep shapes declare `[workspace.package].version`; the YAML body
    // signals this by leaving every crate at `version.workspace = true`.
    let ws_pkg = if case.crates.iter().any(|(_, _, v)| *v == "workspace") {
        "\n[workspace.package]\nversion = \"0.1.0\"\n"
    } else {
        ""
    };
    fs::write(
        root.join("Cargo.toml"),
        format!("[workspace]\nmembers = [{members}]\nresolver = \"2\"\n{ws_pkg}"),
    )
    .unwrap();
    for (dir, name, ver) in case.crates {
        fs::create_dir_all(root.join(dir).join("src")).unwrap();
        let ver_line = if *ver == "workspace" {
            "version.workspace = true".to_string()
        } else {
            format!("version = \"{ver}\"")
        };
        fs::write(
            root.join(dir).join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\n{ver_line}\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(dir).join("src/lib.rs"), "").unwrap();
    }
    fs::write(root.join(".anodizer.yaml"), case.yaml).unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    for tag in case.tags {
        run_git(root, &["tag", tag]);
    }
    for (dir, subject) in case.post_tag_commits {
        fs::write(root.join(dir).join("src/lib.rs"), format!("// {subject}\n")).unwrap();
        git_add_commit(root, subject);
    }
    tmp
}

/// The finite set of config-shape encodings. Each must render every format.
fn shape_matrix() -> Vec<ShapeCase> {
    vec![
        // 1. Single crate (explicit one-entry `crates:`), pending = post-tag.
        ShapeCase {
            name: "single",
            yaml: "project_name: single\nchangelog: {}\ncrates:\n  - name: app\n    path: crates/app\n    tag_template: \"v{{ Version }}\"\n",
            members: &["crates/app"],
            crates: &[("crates/app", "app", "0.1.0")],
            tags: &["v0.1.0"],
            post_tag_commits: &[("crates/app", "feat: single change")],
            must_contain: &["single change"],
            json_len: 1,
        },
        // 2. Lockstep: `[workspace.package].version`, no `crates:`/`workspaces:`.
        ShapeCase {
            name: "lockstep",
            yaml: "project_name: lockstep\nchangelog: {}\n",
            members: &["crates/core", "crates/cli"],
            crates: &[
                ("crates/core", "core", "workspace"),
                ("crates/cli", "cli", "workspace"),
            ],
            tags: &["v0.1.0"],
            post_tag_commits: &[("crates/core", "feat: lockstep change")],
            must_contain: &["lockstep change"],
            json_len: 1,
        },
        // 3. Flat-aggregate: flat `crates:`, ALL sharing one `v*` prefix.
        ShapeCase {
            name: "flat-aggregate",
            yaml: "project_name: aggregate\nchangelog: {}\ncrates:\n  - name: core\n    path: crates/core\n    tag_template: \"v{{ Version }}\"\n  - name: cli\n    path: crates/cli\n    tag_template: \"v{{ Version }}\"\n",
            members: &["crates/core", "crates/cli"],
            crates: &[
                ("crates/core", "core", "0.1.0"),
                ("crates/cli", "cli", "0.1.0"),
            ],
            tags: &["v0.1.0"],
            post_tag_commits: &[
                ("crates/core", "feat: aggregate core change"),
                ("crates/cli", "feat: aggregate cli change"),
            ],
            // Flat aggregate collapses to ONE whole-repo body spanning both.
            must_contain: &["aggregate core change", "aggregate cli change"],
            json_len: 1,
        },
        // 4. PerCrate via flat `crates:` with DISTINCT prefixes (populates
        //    config.crates).
        ShapeCase {
            name: "percrate-flat",
            yaml: "project_name: percrate\nchangelog:\n  files:\n    per_crate: true\ncrates:\n  - name: core\n    path: crates/core\n    tag_template: \"core-v{{ Version }}\"\n  - name: cli\n    path: crates/cli\n    tag_template: \"cli-v{{ Version }}\"\n",
            members: &["crates/core", "crates/cli"],
            crates: &[
                ("crates/core", "core", "0.1.0"),
                ("crates/cli", "cli", "0.2.0"),
            ],
            tags: &["core-v0.1.0", "cli-v0.2.0"],
            post_tag_commits: &[
                ("crates/core", "feat: flat core change"),
                ("crates/cli", "fix: flat cli change"),
            ],
            must_contain: &["flat core change", "flat cli change"],
            json_len: 2,
        },
        // 5. PerCrate via top-level `workspaces:` (leaves config.crates EMPTY —
        //    the cfgd shape that broke release-notes). github-native to also
        //    prove the local-git preview fallback in this shape.
        ShapeCase {
            name: "percrate-workspaces-ghnative",
            yaml: "project_name: cfgd\nchangelog:\n  use: github-native\nworkspaces:\n  - name: core\n    crates:\n      - name: cfgd-core\n        path: crates/core\n        tag_template: \"core-v{{ Version }}\"\n  - name: cli\n    crates:\n      - name: cfgd\n        path: crates/cli\n        tag_template: \"v{{ Version }}\"\n",
            members: &["crates/core", "crates/cli"],
            crates: &[
                ("crates/core", "cfgd-core", "0.1.0"),
                ("crates/cli", "cfgd", "0.1.0"),
            ],
            tags: &["core-v0.1.0", "v0.1.0"],
            post_tag_commits: &[
                ("crates/core", "feat: ws core change"),
                ("crates/cli", "fix: ws cli change"),
            ],
            must_contain: &["ws core change", "ws cli change"],
            json_len: 2,
        },
    ]
}

/// Assert NO `dist/CHANGELOG.md` exists under `root` (a preview must never
/// persist a dist artifact).
fn assert_no_dist_changelog(root: &Path, label: &str) {
    assert!(
        !root.join("dist/CHANGELOG.md").exists(),
        "[{label}] preview must not write dist/CHANGELOG.md"
    );
}

#[test]
fn config_shape_matrix_renders_all_formats() {
    for case in shape_matrix() {
        let tmp = build_shape_repo(&case);
        let root = tmp.path();
        let label = case.name;
        let is_ghnative = case.yaml.contains("use: github-native");

        // --- kac (default) preview: renders [Unreleased], no dist artifact. ---
        let kac = changelog(root, &["-q"]);
        assert!(
            kac.success,
            "[{label}] kac failed: {}\n{}",
            kac.stdout, kac.stderr
        );
        assert!(
            kac.stdout.contains("Unreleased"),
            "[{label}] kac must render [Unreleased]: {}",
            kac.stdout
        );
        assert_no_dist_changelog(root, label);

        // --- release-notes (no --crate): every track non-empty. ---
        let rn = changelog(root, &["-q", "--format", "release-notes"]);
        assert!(
            rn.success,
            "[{label}] release-notes failed: {}\n{}",
            rn.stdout, rn.stderr
        );
        assert!(
            !rn.stdout.trim().is_empty(),
            "[{label}] release-notes body must be non-empty"
        );
        for needle in case.must_contain {
            assert!(
                rn.stdout.contains(needle),
                "[{label}] release-notes missing {needle:?}:\n{}",
                rn.stdout
            );
        }
        assert!(
            !mentions_changelog_stage_skip(&rn.stdout)
                && !mentions_changelog_stage_skip(&rn.stderr),
            "[{label}] release-notes must not hit the snapshot-skip gate: {}\n{}",
            rn.stdout,
            rn.stderr
        );
        if is_ghnative {
            assert!(
                rn.stderr.contains("previewing changelog from local git"),
                "[{label}] github-native release-notes must emit the local-git note: {}",
                rn.stderr
            );
            assert!(
                !rn.stderr.contains("requires a GitHub token"),
                "[{label}] github-native preview must not require a token: {}",
                rn.stderr
            );
        }
        assert_no_dist_changelog(root, label);

        // --- json: valid array, one element per rendered track. ---
        let js = changelog(root, &["-q", "--format", "json"]);
        assert!(
            js.success,
            "[{label}] json failed: {}\n{}",
            js.stdout, js.stderr
        );
        let v: serde_json::Value = serde_json::from_str(&js.stdout)
            .unwrap_or_else(|e| panic!("[{label}] json parse failed: {e}\n{}", js.stdout));
        let arr = v
            .as_array()
            .unwrap_or_else(|| panic!("[{label}] json must be an array"));
        assert_eq!(
            arr.len(),
            case.json_len,
            "[{label}] json element count: {}",
            js.stdout
        );
        assert_no_dist_changelog(root, label);

        // --- snapshot release-notes: renders without `changelog.snapshot:
        //     true` (the standalone command bypasses the config gate). ---
        let snap = changelog(root, &["-q", "--snapshot", "--format", "release-notes"]);
        assert!(
            snap.success,
            "[{label}] snapshot release-notes failed: {}\n{}",
            snap.stdout, snap.stderr
        );
        assert!(
            !mentions_changelog_stage_skip(&snap.stdout)
                && !mentions_changelog_stage_skip(&snap.stderr),
            "[{label}] snapshot release-notes must bypass the config gate: {}\n{}",
            snap.stdout,
            snap.stderr
        );
        for needle in case.must_contain {
            assert!(
                snap.stdout.contains(needle),
                "[{label}] snapshot release-notes missing {needle:?}:\n{}",
                snap.stdout
            );
        }
        assert_no_dist_changelog(root, label);
    }
}

// ---------------------------------------------------------------------------
// Per-crate scope: the single resolver routes all three formats. A multi-track
// repo must scope each track to its OWN crate dir; a global `changelog.paths`
// can only NARROW that scope (intersect), never REPLACE it across tracks.
// ---------------------------------------------------------------------------

/// Build a cfgd-shape distinct-prefix multi-track repo: `core` and `cli` each
/// tagged on their own track, each with a post-tag commit ONLY in its own dir,
/// plus a workspace-root `Cargo.toml`-only commit. `paths_block` is inserted
/// verbatim under the `changelog:` block (e.g. a global `paths:` list).
fn build_multitrack_scope_repo(paths_block: &str) -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (dir, name) in [("crates/core", "core"), ("crates/cli", "cli")] {
        fs::create_dir_all(root.join(dir).join("src")).unwrap();
        fs::write(
            root.join(dir).join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(dir).join("src/lib.rs"), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        format!(
            "project_name: cfgd\nchangelog:{paths_block}\ncrates:\n  \
             - name: core\n    path: crates/core\n    tag_template: \"core-v{{{{ Version }}}}\"\n  \
             - name: cli\n    path: crates/cli\n    tag_template: \"cli-v{{{{ Version }}}}\"\n"
        ),
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "core-v0.1.0"]);
    run_git(root, &["tag", "cli-v0.1.0"]);

    // One commit per track, touching ONLY that track's dir.
    fs::write(root.join("crates/core/src/lib.rs"), "// c\n").unwrap();
    git_add_commit(root, "feat: core only change");
    fs::write(root.join("crates/cli/src/lib.rs"), "// c\n").unwrap();
    git_add_commit(root, "fix: cli only change");
    // A workspace-manifest-only commit (no crate dir touched).
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n# bump\n",
    )
    .unwrap();
    git_add_commit(root, "chore: workspace manifest bump");

    tmp
}

/// JSON summaries for `--crate <name>`: returns the concatenated commit
/// summaries of the single rendered track.
fn json_summaries_for_crate(root: &Path, name: &str) -> String {
    let r = changelog(root, &["-q", "--crate", name, "--format", "json"]);
    assert!(
        r.success,
        "json --crate {name} failed: {}\n{}",
        r.stdout, r.stderr
    );
    let v: serde_json::Value = serde_json::from_str(&r.stdout)
        .unwrap_or_else(|e| panic!("json parse failed: {e}\n{}", r.stdout));
    v.to_string()
}

/// Assert that across kac, json, and release-notes, the `--crate <name>` render
/// contains `own` and never the OTHER track's `foreign` commit — proving each
/// track scopes to its own dir in EVERY format.
fn assert_track_isolation(root: &Path, name: &str, own: &str, foreign: &str) {
    let kac = changelog(root, &["-q", "--crate", name]);
    assert!(
        kac.success,
        "kac --crate {name} failed: {}\n{}",
        kac.stdout, kac.stderr
    );
    let rn = changelog(root, &["-q", "--crate", name, "--format", "release-notes"]);
    assert!(
        rn.success,
        "rn --crate {name} failed: {}\n{}",
        rn.stdout, rn.stderr
    );
    let js = json_summaries_for_crate(root, name);

    for (fmt, body) in [
        ("kac", &kac.stdout),
        ("release-notes", &rn.stdout),
        ("json", &js),
    ] {
        assert!(
            body.contains(own),
            "[{fmt}] --crate {name} must contain its own commit {own:?}:\n{body}"
        );
        assert!(
            !body.contains(foreign),
            "[{fmt}] --crate {name} must NOT contain the other track's commit {foreign:?}:\n{body}"
        );
    }
}

#[test]
fn multitrack_each_track_scopes_to_its_own_dir_all_formats() {
    let tmp = build_multitrack_scope_repo("");
    let root = tmp.path();
    assert_track_isolation(root, "core", "core only change", "cli only change");
    assert_track_isolation(root, "cli", "cli only change", "core only change");
}

#[test]
fn multitrack_superset_paths_match_no_paths_proving_intersect_not_replace() {
    // WITH a global `changelog.paths` superset (cfgd's exact shape): the old
    // "replace" behavior made every track resolve to `crates/**` and render
    // identical sections. The intersect makes the superset a no-op, so the
    // result must match the no-paths case track-for-track.
    let paths = "\n  paths:\n    - \"crates/**\"\n    - Cargo.toml\n    - Cargo.lock";
    let tmp = build_multitrack_scope_repo(paths);
    let root = tmp.path();
    assert_track_isolation(root, "core", "core only change", "cli only change");
    assert_track_isolation(root, "cli", "cli only change", "core only change");
}

#[test]
fn aggregate_includes_manifest_only_commit() {
    // The aggregate (no `--crate`) scopes to the union of crate dirs + the
    // workspace manifests, so a commit touching only `Cargo.toml` appears.
    // A flat-aggregate (shared `v*` prefix) renders one whole-release body.
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/core/src")).unwrap();
    fs::write(
        root.join("crates/core/Cargo.toml"),
        "[package]\nname = \"core\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/core/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: agg\nchangelog: {}\ncrates:\n  \
         - name: core\n    path: crates/core\n    tag_template: \"v{{ Version }}\"\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\"]\nresolver = \"2\"\n# dep bump\n",
    )
    .unwrap();
    git_add_commit(root, "chore: workspace manifest only bump");

    let rn = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(rn.success, "rn failed: {}\n{}", rn.stdout, rn.stderr);
    assert!(
        rn.stdout.contains("workspace manifest only bump"),
        "aggregate must include the Cargo.toml-only commit:\n{}",
        rn.stdout
    );
    let js = changelog(root, &["-q", "--format", "json"]);
    assert!(
        js.stdout.contains("workspace manifest only bump"),
        "aggregate json must include the Cargo.toml-only commit:\n{}",
        js.stdout
    );
}

#[test]
fn narrowing_paths_drop_an_excluded_crates_commits_from_aggregate() {
    // The precise intersect: a `changelog.paths` that excludes `crates/cli`
    // narrows the aggregate so cli's commit drops while core's survives.
    let paths = "\n  paths:\n    - \"crates/core/**\"";
    let tmp = build_multitrack_scope_repo(paths);
    let root = tmp.path();
    // The aggregate render: use a shared-prefix flat aggregate is not this
    // shape (distinct prefixes ⇒ per-crate), so assert via the cli track that
    // narrowing to core/** drops cli's own commit.
    let rn = changelog(root, &["-q", "--crate", "cli", "--format", "release-notes"]);
    assert!(rn.success, "rn failed: {}\n{}", rn.stdout, rn.stderr);
    // cli's track scopes to crates/cli, but the narrowing filter only admits
    // crates/core/** — so cli's commit is filtered out entirely.
    assert!(
        !rn.stdout.contains("cli only change"),
        "narrowing paths (crates/core/**) must drop cli's commit:\n{}",
        rn.stdout
    );
    // core's track survives the narrowing.
    let core = changelog(
        root,
        &["-q", "--crate", "core", "--format", "release-notes"],
    );
    assert!(
        core.stdout.contains("core only change"),
        "core's commit must survive crates/core/** narrowing:\n{}",
        core.stdout
    );
}

/// Build a flat-aggregate (shared `v*` prefix → ONE aggregate track scoping to
/// the crate-dir union + manifests) with a `crates/core/**` narrowing filter.
/// The surviving core commit carries a MULTI-LINE body + `Co-Authored-By:`
/// trailer so the narrowed `--name-only` git path can be proven to preserve the
/// full body, not just the subject. cli's commit + the manifest-only commit are
/// outside `crates/core/**` and must drop.
fn build_narrowing_body_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    for (dir, name) in [("crates/core", "core"), ("crates/cli", "cli")] {
        fs::create_dir_all(root.join(dir).join("src")).unwrap();
        fs::write(
            root.join(dir).join("Cargo.toml"),
            format!("[package]\nname = \"{name}\"\nversion = \"0.1.0\"\nedition = \"2024\"\n"),
        )
        .unwrap();
        fs::write(root.join(dir).join("src/lib.rs"), "").unwrap();
    }
    fs::write(
        root.join(".anodizer.yaml"),
        "project_name: aggregate\nchangelog:\n  paths:\n    - \"crates/core/**\"\ncrates:\n  \
         - name: core\n    path: crates/core\n    tag_template: \"v{{ Version }}\"\n  \
         - name: cli\n    path: crates/cli\n    tag_template: \"v{{ Version }}\"\n",
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);

    // Surviving core commit: multi-line body + co-author trailer.
    fs::write(root.join("crates/core/src/lib.rs"), "// c\n").unwrap();
    run_git(root, &["add", "-A"]);
    run_git(
        root,
        &[
            "commit",
            "-q",
            "-m",
            "feat: core narrowed change\n\nbody line one\nbody line two\n\nCo-Authored-By: Charlie <charlie@c.com>",
        ],
    );
    // Dropped: cli commit (outside crates/core/**).
    fs::write(root.join("crates/cli/src/lib.rs"), "// c\n").unwrap();
    git_add_commit(root, "fix: cli narrowed-out change");
    // Dropped: manifest-only commit.
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/core\", \"crates/cli\"]\nresolver = \"2\"\n# bump\n",
    )
    .unwrap();
    git_add_commit(root, "chore: manifest narrowed-out change");

    tmp
}

#[test]
fn narrowed_aggregate_preserves_full_body_and_coauthor_and_drops_excluded() {
    // The narrowed `--name-only` git path must agree with the metadata-only
    // path on BODY content, not just the subject: the surviving core commit's
    // co-author (parsed from its multi-line body trailer) must appear, while
    // commits outside `crates/core/**` drop.
    let tmp = build_narrowing_body_repo();
    let root = tmp.path();

    let js = changelog(root, &["-q", "--format", "json"]);
    assert!(js.success, "json failed: {}\n{}", js.stdout, js.stderr);
    let v: serde_json::Value = serde_json::from_str(&js.stdout)
        .unwrap_or_else(|e| panic!("json parse failed: {e}\n{}", js.stdout));
    let blob = v.to_string();

    assert!(
        blob.contains("core narrowed change"),
        "surviving core commit subject missing:\n{}",
        js.stdout
    );
    // The co-author is extracted from the commit BODY; its presence proves the
    // narrowed `--name-only` parse preserved the full multi-line body.
    assert!(
        blob.contains("Charlie"),
        "narrowed render dropped the co-author from the multi-line body \
         (body truncation regression):\n{}",
        js.stdout
    );
    // Excluded commits must not appear.
    assert!(
        !blob.contains("cli narrowed-out change"),
        "cli commit outside crates/core/** must drop:\n{}",
        js.stdout
    );
    assert!(
        !blob.contains("manifest narrowed-out change"),
        "manifest-only commit outside crates/core/** must drop:\n{}",
        js.stdout
    );

    // release-notes (same narrowed path) agrees on the surviving subject.
    let rn = changelog(root, &["-q", "--format", "release-notes"]);
    assert!(rn.success, "rn failed: {}\n{}", rn.stdout, rn.stderr);
    assert!(
        rn.stdout.contains("core narrowed change")
            && !rn.stdout.contains("cli narrowed-out change"),
        "release-notes narrowed render disagrees with json:\n{}",
        rn.stdout
    );
}

// ---------------------------------------------------------------------------
// Upper-bound honoring: an explicit `<from>..<to>` / single `<tag>` must NOT
// leak commits made AFTER `<to>`. Regression for the release-notes path
// rendering `<from>..HEAD` (dropping the upper bound) while json honored it.
// ---------------------------------------------------------------------------

/// A single-crate repo with three tags (v0.1.0/v0.2.0/v0.3.0) and one commit
/// AFTER the latest tag, on HEAD. Commit subjects are distinct per inter-tag
/// window so a range render can be checked for exactly which commits it spans.
fn bounded_range_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"crates/app\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("crates/app/src")).unwrap();
    fs::write(
        root.join("crates/app/Cargo.toml"),
        "[package]\nname = \"app\"\nversion = \"0.3.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("crates/app/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: bounded
changelog: {}
crates:
  - name: app
    path: crates/app
    tag_template: "v{{ .Version }}"
    version_sync:
      enabled: true
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "initial");
    run_git(root, &["tag", "v0.1.0"]);
    // v0.1.0..v0.2.0 window.
    fs::write(root.join("crates/app/src/lib.rs"), "// a\n").unwrap();
    git_add_commit(root, "feat: WINDOW_ONE change");
    run_git(root, &["tag", "v0.2.0"]);
    // v0.2.0..v0.3.0 window.
    fs::write(root.join("crates/app/src/lib.rs"), "// b\n").unwrap();
    git_add_commit(root, "feat: WINDOW_TWO change");
    run_git(root, &["tag", "v0.3.0"]);
    // After the latest tag, on HEAD — must never appear in a bounded range.
    fs::write(root.join("crates/app/src/lib.rs"), "// c\n").unwrap();
    git_add_commit(root, "feat: POST_TAG change");
    tmp
}

/// `changelog <from>..<to> --format release-notes` must render exactly the
/// `<from>..<to>` window: the in-range commit IS present and the post-`<to>`
/// HEAD commit is ABSENT. Pins the bug where release-notes ignored `<to>` and
/// rendered `<from>..HEAD`.
#[test]
fn release_notes_explicit_range_honors_upper_bound() {
    let tmp = bounded_range_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "v0.1.0..v0.2.0", "--format", "release-notes"]);
    assert!(r.success, "range render failed: {}\n{}", r.stdout, r.stderr);
    assert!(
        r.stdout.contains("WINDOW_ONE change"),
        "in-range commit (v0.1.0..v0.2.0) must be present:\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("WINDOW_TWO change"),
        "v0.2.0..v0.3.0 commit is above the upper bound v0.2.0 and must be absent:\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("POST_TAG change"),
        "post-v0.3.0 HEAD commit leaked past the upper bound v0.2.0 \
         (release-notes ignored `<to>` and walked to HEAD):\n{}",
        r.stdout
    );
}

/// `changelog <tag> --format release-notes` resolves to `predecessor..<tag>`,
/// so the post-`<tag>` HEAD commit must be ABSENT (same upper-bound bug as the
/// explicit-range form).
#[test]
fn release_notes_single_tag_excludes_post_tag_commits() {
    let tmp = bounded_range_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "v0.3.0", "--format", "release-notes"]);
    assert!(
        r.success,
        "single-tag render failed: {}\n{}",
        r.stdout, r.stderr
    );
    // predecessor of v0.3.0 is v0.2.0, so the window is v0.2.0..v0.3.0.
    assert!(
        r.stdout.contains("WINDOW_TWO change"),
        "the v0.2.0..v0.3.0 commit must be present for `changelog v0.3.0`:\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("POST_TAG change"),
        "post-v0.3.0 HEAD commit leaked into `changelog v0.3.0` \
         (single-tag upper bound v0.3.0 ignored, walked to HEAD):\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("WINDOW_ONE change"),
        "the v0.1.0..v0.2.0 commit is below the lower bound (predecessor v0.2.0) \
         and must be absent:\n{}",
        r.stdout
    );
}

/// An OPEN lower bound with an explicit upper bound (`..<to>`) walks only the
/// ancestors of `<to>` — directly exercising `get_commits_reachable_paths_in`
/// (the None-lower + Some-upper quadrant). The commit reachable from `<to>` IS
/// present; the v0.2.0..v0.3.0 commit (above `<to>`) and the post-v0.3.0 HEAD
/// commit are ABSENT, so the open-lower path bounds at `<to>`, never HEAD.
#[test]
fn release_notes_open_lower_bounded_upper_walks_ancestors_of_to() {
    let tmp = bounded_range_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "..v0.2.0", "--format", "release-notes"]);
    assert!(
        r.success,
        "open-lower render failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("WINDOW_ONE change"),
        "commit reachable from v0.2.0 must be present for `..v0.2.0`:\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("WINDOW_TWO change"),
        "the v0.2.0..v0.3.0 commit is NOT an ancestor of v0.2.0 and must be absent:\n{}",
        r.stdout
    );
    assert!(
        !r.stdout.contains("POST_TAG change"),
        "post-v0.3.0 HEAD commit is not an ancestor of v0.2.0 and must be absent \
         (open-lower path walked to HEAD instead of bounding at v0.2.0):\n{}",
        r.stdout
    );
}

/// An OMITTED upper bound (`<from>..`, open-ended) must STAY "up to HEAD" — the
/// pending window — so the fix doesn't regress the default path: the post-tag
/// HEAD commit IS present here.
#[test]
fn release_notes_open_upper_bound_still_reaches_head() {
    let tmp = bounded_range_repo();
    let root = tmp.path();
    let r = changelog(root, &["-q", "v0.2.0..", "--format", "release-notes"]);
    assert!(
        r.success,
        "open-range render failed: {}\n{}",
        r.stdout, r.stderr
    );
    assert!(
        r.stdout.contains("POST_TAG change"),
        "open upper bound `v0.2.0..` must still reach HEAD (pending window):\n{}",
        r.stdout
    );
    assert!(
        r.stdout.contains("WINDOW_TWO change"),
        "the v0.2.0..v0.3.0 commit must be present in the open `v0.2.0..` range:\n{}",
        r.stdout
    );
}

// ---------------------------------------------------------------------------
// --crate validation + workspace overlay resolution
// ---------------------------------------------------------------------------

/// A `workspaces:` fixture whose workspace carries its OWN `changelog.groups`
/// (a title no default config produces), one member crate, a `member-v0.1.0`
/// baseline tag, and a pending `feat:` commit scoped to the member.
fn workspaces_member_repo() -> TempDir {
    let tmp = TempDir::new().unwrap();
    let root = tmp.path();
    fs::write(
        root.join("Cargo.toml"),
        "[workspace]\nmembers = [\"tools/member\"]\nresolver = \"2\"\n",
    )
    .unwrap();
    fs::create_dir_all(root.join("tools/member/src")).unwrap();
    fs::write(
        root.join("tools/member/Cargo.toml"),
        "[package]\nname = \"member\"\nversion = \"0.1.0\"\nedition = \"2024\"\n",
    )
    .unwrap();
    fs::write(root.join("tools/member/src/lib.rs"), "").unwrap();
    fs::write(
        root.join(".anodizer.yaml"),
        r#"project_name: mono
workspaces:
  - name: tools
    changelog:
      groups:
        - title: Workspace Features
          regexp: "^feat"
          order: 0
    crates:
      - name: member
        path: tools/member
        tag_template: "member-v{{ .Version }}"
"#,
    )
    .unwrap();
    git_init(root);
    git_add_commit(root, "feat: initial member");
    run_git(root, &["tag", "member-v0.1.0"]);
    fs::write(root.join("tools/member/src/lib.rs"), "// gadget\n").unwrap();
    git_add_commit(root, "feat: add gadget");
    tmp
}

/// End-to-end pin for the release-notes workspace overlay: `--crate` naming a
/// `workspaces[].crates` member must resolve THAT workspace's track — its
/// per-workspace `changelog` config (here a `groups` title only the overlay
/// can supply) shapes the rendered notes, and the pending commit lands in it.
#[test]
fn release_notes_crate_filter_applies_workspace_overlay() {
    let tmp = workspaces_member_repo();
    let stdout = release_notes_for_crate(tmp.path(), "member");
    assert!(
        stdout.contains("Workspace Features"),
        "the member's workspace-level changelog.groups must shape the notes \
         (overlay applied), got:\n{stdout}"
    );
    assert!(
        stdout.contains("add gadget"),
        "the member's pending commit must appear in its notes, got:\n{stdout}"
    );
}

/// `changelog --crate <unknown>` is a hard error naming the known crates on
/// EVERY format — refresh previously warned and exited 0, release-notes
/// rendered nothing and exited 0, so a typo looked like "no changes".
#[test]
fn changelog_unknown_crate_hard_errors_on_every_format() {
    let tmp = workspaces_member_repo();
    for format_args in [
        &["--crate", "nope"][..],
        &["--crate", "nope", "--format", "release-notes"][..],
        &["--crate", "nope", "--format", "json"][..],
    ] {
        let r = changelog(tmp.path(), format_args);
        assert!(
            !r.success,
            "changelog {format_args:?} must fail on an unknown crate, got stdout:\n{}",
            r.stdout
        );
        assert!(
            r.stderr.contains("nope") && r.stderr.contains("member"),
            "error must name the unknown crate and the known ones, got:\n{}",
            r.stderr
        );
    }
}