beads_rust 0.2.14

Agent-first issue tracker (SQLite + JSONL)
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
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
mod common;

use beads_rust::storage::SqliteStorage;
use common::cli::{BrWorkspace, extract_json_payload, run_br, run_br_with_env};
use serde_json::Value;
use std::fs;

fn parse_created_id(stdout: &str) -> String {
    let line = stdout.lines().next().unwrap_or("");
    // Handle both formats: "Created bd-xxx: title" and "âś“ Created bd-xxx: title"
    let normalized = line.strip_prefix("âś“ ").unwrap_or(line);
    let id_part = normalized
        .strip_prefix("Created ")
        .and_then(|rest| rest.split(':').next())
        .unwrap_or("");
    id_part.trim().to_string()
}

fn create_issue_with_description(
    workspace: &BrWorkspace,
    title: &str,
    issue_type: Option<&str>,
    description: Option<&str>,
    label: &str,
) -> String {
    let mut args = vec!["create".to_string(), title.to_string()];
    if let Some(kind) = issue_type {
        args.push("--type".to_string());
        args.push(kind.to_string());
    }
    if let Some(text) = description {
        args.push("--description".to_string());
        args.push(text.to_string());
    }
    let create = run_br(workspace, args, label);
    assert!(create.status.success(), "create failed: {}", create.stderr);
    parse_created_id(&create.stdout)
}

fn run_lint_json(workspace: &BrWorkspace, mut args: Vec<String>, label: &str) -> Value {
    args.push("--json".to_string());
    let lint = run_br(workspace, args, label);
    assert!(lint.status.success(), "lint json failed: {}", lint.stderr);
    let payload = extract_json_payload(&lint.stdout);
    serde_json::from_str(&payload).expect("parse lint json")
}

fn overwrite_local_tombstone_title(workspace: &BrWorkspace, id: &str, title: &str) {
    let db_path = workspace.root.join(".beads").join("beads.db");
    let storage = SqliteStorage::open(&db_path).expect("open local beads db");
    let mut issue = storage
        .get_issue(id)
        .expect("read issue from db")
        .expect("issue should exist in db");
    assert_eq!(
        issue.status.as_str(),
        "tombstone",
        "local override helper expects a tombstone issue"
    );
    issue.title = title.to_string();
    storage
        .upsert_issue_for_import(&issue)
        .expect("write divergent local tombstone");
}

fn assert_issue_title_and_clean_sync_state(
    workspace: &BrWorkspace,
    id: &str,
    expected_title: &str,
    show_label: &str,
    status_label: &str,
) {
    let show = run_br(workspace, ["show", id, "--json"], show_label);
    assert!(show.status.success(), "show failed: {}", show.stderr);
    let payload = extract_json_payload(&show.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse show json");
    let record = if json.is_array() {
        json.as_array().and_then(|rows| rows.first()).cloned()
    } else {
        Some(json.clone())
    }
    .expect("show should return a record");
    assert_eq!(record["status"].as_str(), Some("tombstone"));
    assert_eq!(record["title"].as_str(), Some(expected_title));

    let status = run_br(workspace, ["sync", "--status", "--json"], status_label);
    assert!(status.status.success(), "status failed: {}", status.stderr);
    let payload = extract_json_payload(&status.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse status json");
    assert_eq!(
        json["dirty_count"].as_u64(),
        Some(0),
        "import should not re-dirty tombstones that were already present in JSONL"
    );
}

#[test]
fn e2e_error_handling() {
    let _log = common::test_log("e2e_error_handling");
    let workspace = BrWorkspace::new();

    let list_uninit = run_br(&workspace, ["list"], "list_uninitialized");
    assert!(!list_uninit.status.success());

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Bad status"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let id = parse_created_id(&create.stdout);

    let bad_priority = run_br(
        &workspace,
        ["list", "--priority-min", "9"],
        "list_bad_priority",
    );
    assert!(!bad_priority.status.success());

    let bad_ready_priority = run_br(
        &workspace,
        ["ready", "--priority", "9"],
        "ready_bad_priority",
    );
    assert!(!bad_ready_priority.status.success());

    let bad_label = run_br(
        &workspace,
        ["update", &id, "--add-label", "bad label"],
        "update_bad_label",
    );
    assert!(!bad_label.status.success());

    let show_missing = run_br(&workspace, ["show", "bd-doesnotexist"], "show_missing");
    assert!(!show_missing.status.success());

    let delete_missing = run_br(&workspace, ["delete", "bd-doesnotexist"], "delete_missing");
    assert!(!delete_missing.status.success());

    let beads_dir = workspace.root.join(".beads");
    let issues_path = beads_dir.join("issues.jsonl");
    fs::write(
        &issues_path,
        "<<<<<<< HEAD\n{}\n=======\n{}\n>>>>>>> branch\n",
    )
    .expect("write conflict jsonl");

    let sync_bad = run_br(&workspace, ["sync", "--import-only"], "sync_bad_jsonl");
    assert!(!sync_bad.status.success());
}

#[test]
fn e2e_sync_force_import_keeps_jsonl_authoritative_for_existing_tombstones() {
    let _log =
        common::test_log("e2e_sync_force_import_keeps_jsonl_authoritative_for_existing_tombstones");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(
        &workspace,
        ["create", "JSONL tombstone title", "--json"],
        "create",
    );
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let created: Value =
        serde_json::from_str(&extract_json_payload(&create.stdout)).expect("create json");
    let id = created["id"].as_str().expect("issue id").to_string();

    let flush_open = run_br(&workspace, ["sync", "--flush-only"], "flush_open");
    assert!(
        flush_open.status.success(),
        "flush open failed: {}",
        flush_open.stderr
    );

    let delete = run_br(
        &workspace,
        ["delete", &id, "--force", "--no-auto-flush"],
        "delete",
    );
    assert!(delete.status.success(), "delete failed: {}", delete.stderr);

    let flush_tombstone = run_br(&workspace, ["sync", "--flush-only"], "flush_tombstone");
    assert!(
        flush_tombstone.status.success(),
        "flush tombstone failed: {}",
        flush_tombstone.stderr
    );

    overwrite_local_tombstone_title(&workspace, &id, "stale local tombstone title");

    let import = run_br(
        &workspace,
        ["sync", "--import-only", "--force", "--json"],
        "force_import",
    );
    assert!(
        import.status.success(),
        "force import failed: {}",
        import.stderr
    );

    assert_issue_title_and_clean_sync_state(
        &workspace,
        &id,
        "JSONL tombstone title",
        "show_after_force_import",
        "status_after_force_import",
    );
}

#[test]
fn e2e_sync_rebuild_keeps_jsonl_authoritative_for_existing_tombstones() {
    let _log =
        common::test_log("e2e_sync_rebuild_keeps_jsonl_authoritative_for_existing_tombstones");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(
        &workspace,
        ["create", "JSONL tombstone title", "--json"],
        "create",
    );
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let created: Value =
        serde_json::from_str(&extract_json_payload(&create.stdout)).expect("create json");
    let id = created["id"].as_str().expect("issue id").to_string();

    let flush_open = run_br(&workspace, ["sync", "--flush-only"], "flush_open");
    assert!(
        flush_open.status.success(),
        "flush open failed: {}",
        flush_open.stderr
    );

    let delete = run_br(
        &workspace,
        ["delete", &id, "--force", "--no-auto-flush"],
        "delete",
    );
    assert!(delete.status.success(), "delete failed: {}", delete.stderr);

    let flush_tombstone = run_br(&workspace, ["sync", "--flush-only"], "flush_tombstone");
    assert!(
        flush_tombstone.status.success(),
        "flush tombstone failed: {}",
        flush_tombstone.stderr
    );

    overwrite_local_tombstone_title(&workspace, &id, "stale local tombstone title");

    let rebuild = run_br(
        &workspace,
        ["sync", "--import-only", "--rebuild", "--json"],
        "rebuild_import",
    );
    assert!(
        rebuild.status.success(),
        "rebuild import failed: {}",
        rebuild.stderr
    );

    assert_issue_title_and_clean_sync_state(
        &workspace,
        &id,
        "JSONL tombstone title",
        "show_after_rebuild_import",
        "status_after_rebuild_import",
    );
}

#[test]
fn e2e_update_tombstone_rejected() {
    let _log = common::test_log("e2e_update_tombstone_rejected");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "To delete", "--json"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let created: Value =
        serde_json::from_str(&extract_json_payload(&create.stdout)).expect("create json");
    let id = created["id"].as_str().expect("issue id");

    let delete = run_br(
        &workspace,
        [
            "delete",
            id,
            "--force",
            "--reason",
            "Delete for update regression",
        ],
        "delete",
    );
    assert!(delete.status.success(), "delete failed: {}", delete.stderr);

    let update = run_br(
        &workspace,
        ["update", id, "--status", "open", "--json"],
        "update_tombstone",
    );
    assert!(!update.status.success(), "tombstone update should fail");
    assert_eq!(update.status.code(), Some(4), "exit code should be 4");

    let json = parse_error_json(&update.stderr).expect("should be valid error json");
    assert!(verify_error_structure(&json), "missing required fields");
    assert_eq!(json["error"]["code"], "VALIDATION_FAILED");
    assert!(
        json["error"]["message"]
            .as_str()
            .is_some_and(|message| message.contains("cannot update tombstone issue")),
        "error should explain that tombstones cannot be updated"
    );

    let show = run_br(&workspace, ["show", id, "--json"], "show_tombstone");
    assert!(show.status.success(), "show failed: {}", show.stderr);
    let show_json: Value =
        serde_json::from_str(&extract_json_payload(&show.stdout)).expect("show json");
    assert_eq!(show_json[0]["status"], "tombstone");
}

#[test]
fn e2e_update_invalid_parent_does_not_partially_apply_other_changes() {
    let _log = common::test_log("e2e_update_invalid_parent_does_not_partially_apply_other_changes");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Original title", "--json"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let created: Value =
        serde_json::from_str(&extract_json_payload(&create.stdout)).expect("create json");
    let id = created["id"].as_str().expect("issue id").to_string();

    let update = run_br(
        &workspace,
        [
            "update",
            &id,
            "--title",
            "Changed title",
            "--parent",
            "bd-missing",
        ],
        "update_invalid_parent",
    );
    assert!(
        !update.status.success(),
        "invalid parent update should fail"
    );

    let show = run_br(
        &workspace,
        ["show", &id, "--json"],
        "show_after_invalid_parent",
    );
    assert!(show.status.success(), "show failed: {}", show.stderr);
    let shown: Value =
        serde_json::from_str(&extract_json_payload(&show.stdout)).expect("show json");
    assert_eq!(shown[0]["title"].as_str(), Some("Original title"));
    assert!(shown[0]["parent"].is_null());
}

#[test]
fn e2e_update_self_parent_does_not_partially_apply_other_changes() {
    let _log = common::test_log("e2e_update_self_parent_does_not_partially_apply_other_changes");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(
        &workspace,
        ["create", "Self parent target", "--json"],
        "create",
    );
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let created: Value =
        serde_json::from_str(&extract_json_payload(&create.stdout)).expect("create json");
    let id = created["id"].as_str().expect("issue id").to_string();

    let update = run_br(
        &workspace,
        ["update", &id, "--status", "in_progress", "--parent", &id],
        "update_self_parent",
    );
    assert!(!update.status.success(), "self parent update should fail");

    let show = run_br(
        &workspace,
        ["show", &id, "--json"],
        "show_after_self_parent",
    );
    assert!(show.status.success(), "show failed: {}", show.stderr);
    let shown: Value =
        serde_json::from_str(&extract_json_payload(&show.stdout)).expect("show json");
    assert_eq!(shown[0]["status"].as_str(), Some("open"));
    assert!(shown[0]["parent"].is_null());
}

#[test]
fn e2e_dependency_errors() {
    let _log = common::test_log("e2e_dependency_errors");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let issue_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(
        issue_a.status.success(),
        "create A failed: {}",
        issue_a.stderr
    );
    let id_a = parse_created_id(&issue_a.stdout);

    let issue_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(
        issue_b.status.success(),
        "create B failed: {}",
        issue_b.stderr
    );
    let id_b = parse_created_id(&issue_b.stdout);

    let self_dep = run_br(&workspace, ["dep", "add", &id_a, &id_a], "dep_self");
    assert!(!self_dep.status.success(), "self dependency should fail");

    let add = run_br(&workspace, ["dep", "add", &id_a, &id_b], "dep_add");
    assert!(add.status.success(), "dep add failed: {}", add.stderr);

    let cycle = run_br(&workspace, ["dep", "add", &id_b, &id_a], "dep_cycle");
    assert!(!cycle.status.success(), "cycle dependency should fail");
}

#[test]
fn e2e_dep_add_blocks_ignores_non_blocking_cycle_edges() {
    let _log = common::test_log("e2e_dep_add_blocks_ignores_non_blocking_cycle_edges");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let issue_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(
        issue_a.status.success(),
        "create A failed: {}",
        issue_a.stderr
    );
    let id_a = parse_created_id(&issue_a.stdout);

    let issue_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(
        issue_b.status.success(),
        "create B failed: {}",
        issue_b.stderr
    );
    let id_b = parse_created_id(&issue_b.stdout);

    let related = run_br(
        &workspace,
        ["dep", "add", &id_a, &id_b, "--type", "related"],
        "dep_related",
    );
    assert!(
        related.status.success(),
        "related dep add failed: {}",
        related.stderr
    );

    let blocks = run_br(
        &workspace,
        ["dep", "add", &id_b, &id_a, "--type", "blocks"],
        "dep_blocks",
    );
    assert!(
        blocks.status.success(),
        "blocking dep should ignore non-blocking related edge: {}",
        blocks.stderr
    );
}

#[test]
fn e2e_sync_invalid_orphans() {
    let _log = common::test_log("e2e_sync_invalid_orphans");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Sync issue"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let bad_orphans = run_br(
        &workspace,
        ["sync", "--import-only", "--force", "--orphans", "weird"],
        "sync_bad_orphans",
    );
    assert!(
        !bad_orphans.status.success(),
        "invalid orphans mode should fail"
    );
}

#[test]
fn e2e_sync_rename_prefix_applies_after_missing_db_recovery_with_force() {
    let _log =
        common::test_log("e2e_sync_rename_prefix_applies_after_missing_db_recovery_with_force");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let create = run_br(&workspace, ["create", "Seed issue"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let original_id = parse_created_id(&create.stdout);
    let mismatched_id = format!(
        "other-{}",
        original_id
            .split_once('-')
            .map(|(_, remainder)| remainder)
            .expect("created issue id should include a prefix")
    );

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let jsonl = fs::read_to_string(&issues_path).expect("read issues jsonl");
    fs::write(&issues_path, jsonl.replace(&original_id, &mismatched_id)).expect("rewrite jsonl");

    let alt_db = workspace.root.join(".beads").join("auto-rebuilt-alt.db");
    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--force",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_missing_db_rename_prefix_force",
    );
    assert!(
        result.status.success(),
        "rename-prefix import should succeed after deferring open-time recovery: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse import json");
    assert_eq!(json["created"].as_u64(), Some(1));

    let alt_storage = SqliteStorage::open(&alt_db).expect("open rebuilt alternate db");
    assert_eq!(
        alt_storage.count_all_issues().expect("count issues"),
        1,
        "alternate DB should be populated by the explicit rename-prefix import"
    );
    let imported_ids = alt_storage.get_all_ids().expect("all ids");
    assert_eq!(imported_ids.len(), 1);
    assert!(
        imported_ids[0].starts_with("target-"),
        "renamed import should use the configured prefix: {:?}",
        imported_ids
    );
    assert_ne!(
        imported_ids[0], mismatched_id,
        "rename-prefix import should rewrite mismatched IDs"
    );
}

#[test]
fn e2e_sync_rename_prefix_applies_after_missing_db_recovery_without_force() {
    let _log =
        common::test_log("e2e_sync_rename_prefix_applies_after_missing_db_recovery_without_force");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let create = run_br(&workspace, ["create", "Seed issue"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let original_id = parse_created_id(&create.stdout);
    let mismatched_id = format!(
        "other-{}",
        original_id
            .split_once('-')
            .map(|(_, remainder)| remainder)
            .expect("created issue id should include a prefix")
    );

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let jsonl = fs::read_to_string(&issues_path).expect("read issues jsonl");
    fs::write(&issues_path, jsonl.replace(&original_id, &mismatched_id)).expect("rewrite jsonl");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("auto-rebuilt-plain-alt.db");
    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_missing_db_plain_rename_prefix",
    );
    assert!(
        result.status.success(),
        "plain rename-prefix import should succeed after deferring open-time recovery: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse import json");
    assert_eq!(json["created"].as_u64(), Some(1));

    let alt_storage = SqliteStorage::open(&alt_db).expect("open rebuilt alternate db");
    assert_eq!(
        alt_storage.count_all_issues().expect("count issues"),
        1,
        "alternate DB should be populated by the explicit rename-prefix import"
    );
    let imported_ids = alt_storage.get_all_ids().expect("all ids");
    assert_eq!(imported_ids.len(), 1);
    assert!(
        imported_ids[0].starts_with("target-"),
        "renamed import should use the configured prefix: {:?}",
        imported_ids
    );
    assert_ne!(
        imported_ids[0], mismatched_id,
        "rename-prefix import should rewrite mismatched IDs"
    );
}

#[test]
fn e2e_auto_flush_skips_silently_overwriting_conflict_markered_jsonl() {
    // Regression: post-command auto-flush used to unconditionally call
    // `export_to_jsonl_with_policy`, which overwrote any existing JSONL —
    // including unresolved `<<<<<<<` / `=======` / `>>>>>>>` regions from
    // a botched `git merge`. Auto-import's conflict-markers check catches
    // most of these before the mutation runs, but commands invoked with
    // `--no-auto-import` skip that guard entirely, leaving auto-flush as
    // the last line of defense. The fix teaches `auto_flush` itself to
    // skip when it sees merge markers, so the mutation still lands in the
    // DB but the JSONL on disk keeps its unresolved state for the
    // operator to fix.
    let _log =
        common::test_log("e2e_auto_flush_skips_silently_overwriting_conflict_markered_jsonl");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Seed"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let issue_id = parse_created_id(&create.stdout);

    let seed_flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush_seed");
    assert!(
        seed_flush.status.success(),
        "initial flush failed: {}",
        seed_flush.stderr
    );

    // Drop the JSONL into a half-resolved merge-conflict state.
    let jsonl_path = workspace.root.join(".beads").join("issues.jsonl");
    let clean = fs::read_to_string(&jsonl_path).expect("read jsonl");
    let conflicted = format!("<<<<<<< HEAD\n{clean}=======\n{clean}>>>>>>> branch\n");
    fs::write(&jsonl_path, &conflicted).expect("write conflicted jsonl");
    let before_bytes = fs::read(&jsonl_path).expect("read conflicted jsonl");

    // Run a mutating command with `--no-auto-import` so the first line of
    // defense (auto-import's conflict-markers scan) is bypassed. The
    // mutation should still succeed against the DB, but auto-flush must
    // NOT overwrite the conflict-markered JSONL.
    let update = run_br(
        &workspace,
        ["--no-auto-import", "update", &issue_id, "--priority", "1"],
        "update_no_auto_import",
    );
    assert!(
        update.status.success(),
        "mutation should still succeed even though auto-flush is skipped: {}",
        update.stderr
    );

    // On-disk JSONL must still hold the conflict markers byte-for-byte.
    let after_bytes = fs::read(&jsonl_path).expect("reread jsonl");
    assert_eq!(
        before_bytes, after_bytes,
        "auto-flush must not rewrite a JSONL that contains unresolved merge-conflict markers"
    );
}

#[test]
fn e2e_auto_flush_failure_is_visible_in_json_mode() {
    let _log = common::test_log("e2e_auto_flush_failure_is_visible_in_json_mode");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Visible flush debt"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let issue_id = parse_created_id(&create.stdout);

    let bad_jsonl = workspace
        .root
        .join(".beads")
        .join("beads.db")
        .join("issues.jsonl");
    let bad_jsonl = bad_jsonl.to_string_lossy().to_string();

    let update = run_br_with_env(
        &workspace,
        [
            "--json",
            "--no-auto-import",
            "update",
            &issue_id,
            "--priority",
            "1",
        ],
        [("BEADS_JSONL", bad_jsonl.as_str())],
        "update_bad_auto_flush_jsonl",
    );
    assert!(
        update.status.success(),
        "mutation should still succeed while surfacing auto-flush debt: {}",
        update.stderr
    );

    let warning_payload = extract_json_payload(&update.stderr);
    let warning: Value =
        serde_json::from_str(&warning_payload).expect("auto-flush warning should be JSON");
    assert_eq!(
        warning["warning"]["code"].as_str(),
        Some("AUTO_FLUSH_FAILED")
    );
    assert!(
        warning["warning"]["message"]
            .as_str()
            .is_some_and(|message| message.contains("Mutation succeeded")),
        "warning should make the committed mutation explicit: {}",
        update.stderr
    );
    assert!(
        warning["warning"]["recovery"]
            .as_str()
            .is_some_and(|recovery| recovery.contains("br sync --flush-only")),
        "warning should tell operators how to repair export debt: {}",
        update.stderr
    );
    assert!(
        update.stdout.contains(&issue_id),
        "JSON stdout should still contain command output: {}",
        update.stdout
    );
}

#[test]
fn e2e_sync_flush_checks_conflict_markers_before_noop_short_circuit() {
    // Regression: `br sync --flush-only` can return early when the DB has
    // nothing dirty. That early return must not hide unresolved JSONL merge
    // markers, because a user running sync for safety should still be told
    // the working tree contains an unresolved beads data conflict.
    let _log = common::test_log("e2e_sync_flush_checks_conflict_markers_before_noop_short_circuit");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Seed"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let _ = parse_created_id(&create.stdout);

    let first_flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush_initial");
    assert!(
        first_flush.status.success(),
        "initial flush should succeed: {}",
        first_flush.stderr
    );

    // Simulate a merge conflict by wrapping the clean JSONL in conflict
    // markers, as if `git merge` left the file in a half-resolved state.
    let jsonl_path = workspace.root.join(".beads").join("issues.jsonl");
    let clean = fs::read_to_string(&jsonl_path).expect("read jsonl");
    let conflicted = format!("<<<<<<< HEAD\n{clean}=======\n{clean}>>>>>>> branch\n");
    fs::write(&jsonl_path, &conflicted).expect("write conflicted jsonl");
    let before_size = fs::metadata(&jsonl_path).expect("stat jsonl").len();

    // A subsequent no-op flush must refuse with a conflict-markers error
    // before taking the "nothing to do" short-circuit.
    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        !flush.status.success(),
        "flush should fail when JSONL contains conflict markers: stdout={} stderr={}",
        flush.stdout,
        flush.stderr
    );
    // Error goes to stderr, not stdout, so check the human-readable text
    // rather than trying to parse JSON from stdout.
    let lower = flush.stderr.to_lowercase();
    assert!(
        lower.contains("conflict") || lower.contains("marker"),
        "flush error should mention conflict markers, got stderr: {}",
        flush.stderr
    );

    // The JSONL on disk must still contain the conflict markers: if the
    // flush had overwritten it, the markers would be gone.
    let after = fs::read_to_string(&jsonl_path).expect("reread jsonl");
    assert!(
        after.contains("<<<<<<<"),
        "conflict markers must still be on disk after refused flush"
    );
    assert_eq!(
        fs::metadata(&jsonl_path).expect("stat jsonl").len(),
        before_size,
        "JSONL size must not change when flush refuses due to conflict markers"
    );
}

#[test]
#[allow(clippy::too_many_lines)]
fn e2e_sync_rebuild_preserves_unflushed_tombstones_across_delegation() {
    // Regression: `br sync --import-only --rebuild` on an existing DB used
    // to lose tombstones that had not yet been flushed to JSONL. The
    // in-place path preserves them via `snapshot_tombstones` +
    // `restore_tombstones` across `reset_data_tables`, but the new
    // delegation path to `recover_database_from_jsonl` opens a fresh DB and
    // imports only what's in the JSONL. Unflushed tombstones therefore
    // vanished silently, taking their deletion-retention state with them.
    // The fix snapshots tombstones before delegation and restores them
    // after.
    let _log =
        common::test_log("e2e_sync_rebuild_preserves_unflushed_tombstones_across_delegation");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    // Create two issues so the rebuild has content to preserve.
    let keep = run_br(&workspace, ["create", "Keep"], "create_keep");
    assert!(keep.status.success(), "create keep failed: {}", keep.stderr);
    let keep_id = parse_created_id(&keep.stdout);

    let delete = run_br(&workspace, ["create", "Delete"], "create_delete");
    assert!(
        delete.status.success(),
        "create delete failed: {}",
        delete.stderr
    );
    let delete_id = parse_created_id(&delete.stdout);

    // Flush both as open so the JSONL reflects the pre-deletion state.
    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    // Delete one issue WITHOUT flushing: the tombstone only lives in the
    // DB, the JSONL still shows `delete_id` as open.
    let delete_cmd = run_br(
        &workspace,
        ["delete", &delete_id, "--force", "--no-auto-flush"],
        "delete_no_flush",
    );
    assert!(
        delete_cmd.status.success(),
        "delete failed: {}",
        delete_cmd.stderr
    );

    // Run --rebuild. The delegation path fires because the DB exists, no
    // rename was requested, and the JSONL is available.
    let rebuild = run_br(
        &workspace,
        ["sync", "--import-only", "--rebuild", "--json"],
        "sync_rebuild",
    );
    assert!(
        rebuild.status.success(),
        "rebuild failed: {}",
        rebuild.stderr
    );

    // The surviving tombstone must still be queryable via `br show`. If the
    // delegation had silently wiped it, `show` would either report
    // "Issue not found" or return the resurrected-as-open version from the
    // JSONL.
    let show = run_br(&workspace, ["show", &delete_id, "--json"], "show_tombstone");
    assert!(
        show.status.success(),
        "tombstone lookup failed after --rebuild: {}",
        show.stderr
    );
    let payload = extract_json_payload(&show.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse show json");
    let record = if json.is_array() {
        json.as_array().and_then(|a| a.first()).cloned()
    } else {
        Some(json.clone())
    }
    .expect("show should return at least one record");
    assert_eq!(
        record["status"].as_str(),
        Some("tombstone"),
        "tombstone status was lost across --rebuild: {record}"
    );

    // The kept issue must still be open.
    let show_keep = run_br(&workspace, ["show", &keep_id, "--json"], "show_keep");
    assert!(
        show_keep.status.success(),
        "keep lookup failed: {}",
        show_keep.stderr
    );
    let payload = extract_json_payload(&show_keep.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse show keep json");
    let record = if json.is_array() {
        json.as_array().and_then(|a| a.first()).cloned()
    } else {
        Some(json.clone())
    }
    .expect("show should return at least one record");
    assert_eq!(record["status"].as_str(), Some("open"));

    // The preserved tombstone must remain dirty so a later flush writes the
    // deletion back to JSONL instead of incorrectly reporting "Nothing to
    // export". Without this, the rebuilt DB and JSONL silently diverge until
    // a future import/rebuild cycle resurrects the supposedly deleted issue.
    let status = run_br(
        &workspace,
        ["sync", "--status", "--json"],
        "status_after_rebuild",
    );
    assert!(
        status.status.success(),
        "status failed after rebuild: {}",
        status.stderr
    );
    let payload = extract_json_payload(&status.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse status json");
    assert_eq!(
        json["dirty_count"].as_u64(),
        Some(1),
        "the preserved tombstone should stay dirty until it is flushed"
    );

    let flush_after_rebuild = run_br(
        &workspace,
        ["sync", "--flush-only", "--json"],
        "flush_after_rebuild",
    );
    assert!(
        flush_after_rebuild.status.success(),
        "flush after rebuild failed: {}",
        flush_after_rebuild.stderr
    );
    let payload = extract_json_payload(&flush_after_rebuild.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse flush json");
    assert_eq!(
        json["cleared_dirty"].as_u64(),
        Some(1),
        "flush should report the single preserved tombstone dirty flag it cleared"
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let jsonl = fs::read_to_string(&issues_path).expect("read rebuilt issues jsonl");
    let exported_issue_states: Vec<(String, String)> = jsonl
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| {
            let value: Value = serde_json::from_str(line).expect("parse exported issue line");
            (
                value["id"].as_str().expect("exported issue id").to_string(),
                value["status"]
                    .as_str()
                    .expect("exported issue status")
                    .to_string(),
            )
        })
        .collect();
    assert!(
        exported_issue_states
            .iter()
            .any(|(id, status)| id == &delete_id && status == "tombstone"),
        "flush after rebuild should export the preserved tombstone: {:?}",
        exported_issue_states
    );
    assert!(
        exported_issue_states
            .iter()
            .any(|(id, status)| id == &keep_id && status == "open"),
        "flush after rebuild should keep the surviving issue open: {:?}",
        exported_issue_states
    );

    let status_after_flush = run_br(
        &workspace,
        ["sync", "--status", "--json"],
        "status_after_flush",
    );
    assert!(
        status_after_flush.status.success(),
        "status failed after flush: {}",
        status_after_flush.stderr
    );
    let payload = extract_json_payload(&status_after_flush.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse post-flush status json");
    assert_eq!(
        json["dirty_count"].as_u64(),
        Some(0),
        "flush should clear the preserved tombstone's dirty flag"
    );
}

#[test]
fn e2e_sync_rebuild_with_rename_prefix_keeps_renamed_issues() {
    // Regression: `--rebuild --rename-prefix` used to wipe the DB. The
    // rebuild's orphan-cleanup pass compares the *raw* JSONL IDs (pre-rename)
    // against `storage.get_all_ids()` (post-rename). Every renamed issue
    // therefore looked like a "DB entry not present in JSONL" and got
    // deleted. The fix is to skip the orphan pass when `--rename-prefix`
    // rewrote the IDs the import just inserted, since the set-difference
    // comparison is no longer semantically meaningful.
    let _log = common::test_log("e2e_sync_rebuild_with_rename_prefix_keeps_renamed_issues");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let create = run_br(&workspace, ["create", "Seed issue"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let original_id = parse_created_id(&create.stdout);
    let mismatched_id = format!(
        "other-{}",
        original_id
            .split_once('-')
            .map(|(_, remainder)| remainder)
            .expect("created issue id should include a prefix")
    );

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let jsonl = fs::read_to_string(&issues_path).expect("read issues jsonl");
    fs::write(&issues_path, jsonl.replace(&original_id, &mismatched_id)).expect("rewrite jsonl");

    let result = run_br(
        &workspace,
        [
            "sync",
            "--import-only",
            "--rebuild",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_rebuild_rename_prefix",
    );
    assert!(
        result.status.success(),
        "--rebuild --rename-prefix should succeed: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse import json");
    assert_eq!(
        json["created"].as_u64(),
        Some(1),
        "expected the renamed issue to be inserted"
    );
    assert_eq!(
        json["orphans_removed"].as_u64(),
        Some(0),
        "orphan cleanup must not run when --rename-prefix rewrote IDs; otherwise every renamed issue is wiped"
    );

    let db_path = workspace.root.join(".beads").join("beads.db");
    let storage = SqliteStorage::open(&db_path).expect("open rebuilt db");
    assert_eq!(
        storage.count_all_issues().expect("count issues"),
        1,
        "DB must retain the renamed issue after --rebuild + --rename-prefix"
    );
    let ids = storage.get_all_ids().expect("all ids");
    assert_eq!(ids.len(), 1);
    assert!(
        ids[0].starts_with("target-"),
        "issue should carry the renamed prefix, got {:?}",
        ids
    );
    assert_ne!(
        ids[0], mismatched_id,
        "the renamed ID must differ from the pre-rename JSONL ID"
    );
}

#[test]
fn e2e_sync_auto_rebuild_plain_import_reports_recovery_result() {
    let _log = common::test_log("e2e_sync_auto_rebuild_plain_import_reports_recovery_result");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Seed issue"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let alt_db = workspace
        .root
        .join(".beads")
        .join("auto-rebuilt-report-alt.db");
    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_auto_rebuild_plain_import",
    );
    assert!(
        result.status.success(),
        "plain import should succeed after open-time auto-rebuild: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("parse import json");
    assert_eq!(json["created"].as_u64(), Some(1));
    assert_eq!(json["updated"].as_u64(), Some(0));
    assert_eq!(json["blocked_cache_rebuilt"].as_bool(), Some(true));

    let alt_storage = SqliteStorage::open(&alt_db).expect("open rebuilt alternate db");
    assert_eq!(
        alt_storage.count_all_issues().expect("count issues"),
        1,
        "alternate DB should be populated by automatic recovery"
    );
}

#[test]
#[allow(clippy::too_many_lines)]
fn e2e_sync_rename_prefix_clears_duplicate_external_ref_after_missing_db_recovery() {
    let _log = common::test_log(
        "e2e_sync_rename_prefix_clears_duplicate_external_ref_after_missing_db_recovery",
    );
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let first = run_br(
        &workspace,
        ["create", "First issue", "--external-ref", "EXT-DUP"],
        "create_first",
    );
    assert!(
        first.status.success(),
        "create first failed: {}",
        first.stderr
    );
    let first_id = parse_created_id(&first.stdout);

    let second = run_br(&workspace, ["create", "Second issue"], "create_second");
    assert!(
        second.status.success(),
        "create second failed: {}",
        second.stderr
    );
    let second_id = parse_created_id(&second.stdout);

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let updated = fs::read_to_string(&issues_path)
        .expect("read issues jsonl")
        .lines()
        .map(|line| {
            let mut value: Value = serde_json::from_str(line).expect("issue json");
            if value["id"].as_str() == Some(&second_id) {
                value["external_ref"] = Value::String("EXT-DUP".to_string());
            }
            serde_json::to_string(&value).expect("serialize issue json")
        })
        .collect::<Vec<_>>()
        .join("\n");
    fs::write(&issues_path, format!("{updated}\n")).expect("rewrite jsonl");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("auto-rebuilt-duplicate-extref-alt.db");
    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_missing_db_duplicate_external_ref_cleanup",
    );
    assert!(
        result.status.success(),
        "rename-prefix duplicate external_ref cleanup should succeed after deferring open-time recovery: {}",
        result.stderr
    );

    let alt_storage = SqliteStorage::open(&alt_db).expect("open rebuilt alternate db");
    assert_eq!(
        alt_storage.count_all_issues().expect("count issues"),
        2,
        "alternate DB should be populated by the explicit import"
    );
    let retained = [&first_id, &second_id]
        .into_iter()
        .filter(|id| {
            alt_storage
                .get_issue(id)
                .expect("query imported issue")
                .and_then(|issue| issue.external_ref)
                .as_deref()
                == Some("EXT-DUP")
        })
        .count();
    let cleared = [&first_id, &second_id]
        .into_iter()
        .filter(|id| {
            alt_storage
                .get_issue(id)
                .expect("query imported issue")
                .and_then(|issue| issue.external_ref)
                .is_none()
        })
        .count();
    assert_eq!(
        retained, 1,
        "exactly one duplicate external_ref should be preserved"
    );
    assert_eq!(
        cleared, 1,
        "exactly one duplicate external_ref should be cleared"
    );
}

#[test]
fn e2e_sync_rename_prefix_failed_import_restores_original_corrupt_db_family() {
    let _log = common::test_log(
        "e2e_sync_rename_prefix_failed_import_restores_original_corrupt_db_family",
    );
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    fs::write(&issues_path, "{\"id\":\"broken\"\n").expect("write malformed jsonl");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("deferred-recovery-restore-alt.db");
    let original_bytes = b"not a sqlite database but should be restored".to_vec();
    fs::write(&alt_db, &original_bytes).expect("write corrupt alt db");

    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_failed_deferred_recovery_restore",
    );
    assert!(
        !result.status.success(),
        "malformed JSONL should fail explicit import after deferred recovery"
    );
    assert!(
        result.stderr.contains("Invalid JSON"),
        "unexpected stderr: {}",
        result.stderr
    );

    let restored_bytes = fs::read(&alt_db).expect("read restored alt db");
    assert_eq!(
        restored_bytes, original_bytes,
        "failed deferred import should restore the original corrupt db bytes"
    );
}

#[test]
fn e2e_sync_rename_prefix_validation_failure_restores_original_corrupt_db_family() {
    let _log = common::test_log(
        "e2e_sync_rename_prefix_validation_failure_restores_original_corrupt_db_family",
    );
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let external_dir = workspace.root.join("external-jsonl");
    fs::create_dir_all(&external_dir).expect("create external dir");
    let external_jsonl = external_dir.join("metadata.jsonl");
    fs::write(
        &external_jsonl,
        "{\"id\":\"legacy-1\",\"title\":\"External metadata JSONL\",\"status\":\"open\",\"priority\":2,\"issue_type\":\"task\",\"created_at\":\"2026-01-01T00:00:00Z\",\"updated_at\":\"2026-01-01T00:00:00Z\"}\n",
    )
    .expect("write external jsonl");

    let metadata_path = workspace.root.join(".beads").join("metadata.json");
    let metadata_json = format!(
        r#"{{"database":"beads.db","jsonl_export":"{}"}}"#,
        external_jsonl.display()
    );
    fs::write(&metadata_path, metadata_json).expect("write metadata");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("deferred-recovery-validation-restore-alt.db");
    let original_bytes = b"not a sqlite database but should survive validation failure".to_vec();
    fs::write(&alt_db, &original_bytes).expect("write corrupt alt db");

    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_failed_deferred_recovery_validation_restore",
    );
    assert!(
        !result.status.success(),
        "external metadata JSONL without allow flag should fail validation"
    );
    let combined = format!("{}{}", result.stdout, result.stderr);
    assert!(
        combined.contains("external")
            || combined.contains("allow-external-jsonl")
            || combined.contains("outside"),
        "unexpected validation failure output: {combined}"
    );

    let restored_bytes = fs::read(&alt_db).expect("read restored alt db");
    assert_eq!(
        restored_bytes, original_bytes,
        "validation failure after deferred recovery should restore the original corrupt db bytes"
    );
}

#[test]
fn e2e_sync_rename_prefix_validation_failure_does_not_create_missing_db() {
    let _log =
        common::test_log("e2e_sync_rename_prefix_validation_failure_does_not_create_missing_db");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let external_dir = workspace.root.join("external-jsonl");
    fs::create_dir_all(&external_dir).expect("create external dir");
    let external_jsonl = external_dir.join("metadata.jsonl");
    fs::write(
        &external_jsonl,
        "{\"id\":\"legacy-1\",\"title\":\"External metadata JSONL\",\"status\":\"open\",\"priority\":2,\"issue_type\":\"task\",\"created_at\":\"2026-01-01T00:00:00Z\",\"updated_at\":\"2026-01-01T00:00:00Z\"}\n",
    )
    .expect("write external jsonl");

    let metadata_path = workspace.root.join(".beads").join("metadata.json");
    let metadata_json = format!(
        r#"{{"database":"beads.db","jsonl_export":"{}"}}"#,
        external_jsonl.display()
    );
    fs::write(&metadata_path, metadata_json).expect("write metadata");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("deferred-recovery-validation-missing-alt.db");
    assert!(
        !alt_db.exists(),
        "precondition: alternate db should start missing"
    );

    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_failed_deferred_recovery_validation_missing_db",
    );
    assert!(
        !result.status.success(),
        "external metadata JSONL without allow flag should fail validation"
    );
    let combined = format!("{}{}", result.stdout, result.stderr);
    assert!(
        combined.contains("external")
            || combined.contains("allow-external-jsonl")
            || combined.contains("outside"),
        "unexpected validation failure output: {combined}"
    );
    assert!(
        !alt_db.exists(),
        "validation failure should not create a fresh alternate db"
    );
}

#[test]
fn e2e_sync_rename_prefix_import_failure_does_not_leave_missing_db_created() {
    let _log =
        common::test_log("e2e_sync_rename_prefix_import_failure_does_not_leave_missing_db_created");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let set_prefix = run_br(
        &workspace,
        ["config", "set", "issue_prefix=target"],
        "config_set_issue_prefix",
    );
    assert!(
        set_prefix.status.success(),
        "config set failed: {}",
        set_prefix.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    fs::write(&issues_path, "{\"id\":\"broken\"\n").expect("write malformed jsonl");

    let alt_db = workspace
        .root
        .join(".beads")
        .join("deferred-recovery-import-missing-alt.db");
    assert!(
        !alt_db.exists(),
        "precondition: alternate db should start missing"
    );

    let result = run_br(
        &workspace,
        [
            "--db",
            alt_db.to_str().expect("alt db path"),
            "sync",
            "--import-only",
            "--rename-prefix",
            "--json",
            "--no-auto-import",
            "--no-auto-flush",
        ],
        "sync_failed_deferred_recovery_import_missing_db",
    );
    assert!(
        !result.status.success(),
        "malformed JSONL should fail explicit import after deferred recovery"
    );
    assert!(
        result.stderr.contains("Invalid JSON"),
        "unexpected stderr: {}",
        result.stderr
    );
    assert!(
        !alt_db.exists(),
        "failed deferred import should not leave a fresh alternate db behind when none existed before"
    );
}

#[test]
fn e2e_sync_export_guards() {
    let _log = common::test_log("e2e_sync_export_guards");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let beads_dir = workspace.root.join(".beads");
    let issues_path = beads_dir.join("issues.jsonl");

    // Empty DB guard: JSONL has content but DB has zero issues.
    fs::write(&issues_path, "{\"id\":\"bd-ghost\"}\n").expect("write jsonl");
    let flush_guard = run_br(&workspace, ["sync", "--flush-only"], "sync_flush_guard");
    assert!(
        !flush_guard.status.success(),
        "expected empty DB guard failure"
    );
    assert!(
        flush_guard
            .stderr
            .contains("Refusing to export empty database"),
        "missing empty DB guard message"
    );
    // Reset JSONL to avoid guard on the seed export.
    fs::write(&issues_path, "").expect("reset jsonl");

    // Stale DB guard: JSONL has an ID missing from DB.
    let create = run_br(&workspace, ["create", "Stale guard issue"], "create_stale");
    assert!(create.status.success(), "create failed: {}", create.stderr);

    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush_seed");
    assert!(
        flush.status.success(),
        "sync flush failed: {}",
        flush.stderr
    );

    let mut contents = fs::read_to_string(&issues_path).expect("read jsonl");
    // Use a complete Issue JSON (not just {"id":"bd-missing"}) to avoid parse errors during auto-import
    contents.push_str("{\"id\":\"bd-missing\",\"title\":\"Ghost issue\",\"status\":\"open\",\"priority\":2,\"issue_type\":\"task\",\"created_at\":\"2026-01-01T00:00:00Z\",\"updated_at\":\"2026-01-01T00:00:00Z\"}\n");
    fs::write(&issues_path, contents).expect("append jsonl");

    // Use --no-auto-import and --allow-stale to prevent bd-missing from being imported into DB
    let create2 = run_br(
        &workspace,
        ["create", "Dirty issue", "--no-auto-import", "--allow-stale"],
        "create_dirty",
    );
    assert!(
        create2.status.success(),
        "create failed: {}",
        create2.stderr
    );

    // The flush should fail because JSONL has bd-missing but DB doesn't
    let flush_stale = run_br(&workspace, ["sync", "--flush-only"], "sync_flush_stale");
    assert!(
        !flush_stale.status.success(),
        "expected stale DB guard failure"
    );
    assert!(
        flush_stale
            .stderr
            .contains("Refusing to export stale database"),
        "missing stale DB guard message"
    );
}

#[test]
fn e2e_ambiguous_id() {
    let _log = common::test_log("e2e_ambiguous_id");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let mut ids: Vec<String> = Vec::new();
    let mut attempt = 0;
    let mut ambiguous_prefix: Option<String> = None;

    while ambiguous_prefix.is_none() && attempt < 30 {
        let title = format!("Ambiguous {attempt}");
        let create = run_br(&workspace, ["create", &title], "create_ambiguous");
        assert!(create.status.success(), "create failed: {}", create.stderr);
        let id = parse_created_id(&create.stdout);
        ids.push(id);

        // Check for first-character collisions (matches how the resolver
        // uses contains() -- a single char matches any hash containing it)
        for i in 0..ids.len() {
            for j in (i + 1)..ids.len() {
                let hash_i = ids[i].split('-').nth(1).unwrap_or("");
                let hash_j = ids[j].split('-').nth(1).unwrap_or("");
                if !hash_i.is_empty()
                    && !hash_j.is_empty()
                    && hash_i.chars().next() == hash_j.chars().next()
                {
                    let common_char = hash_i.chars().next().unwrap();
                    ambiguous_prefix = Some(common_char.to_string());
                    break;
                }
            }
            if ambiguous_prefix.is_some() {
                break;
            }
        }

        attempt += 1;
    }

    let ambiguous_input = ambiguous_prefix.expect("failed to find ambiguous prefix");

    let show = run_br(&workspace, ["show", &ambiguous_input], "show_ambiguous");
    assert!(!show.status.success(), "ambiguous id should fail");
}

#[test]
fn e2e_lint_before_init_fails() {
    let _log = common::test_log("e2e_lint_before_init_fails");
    let workspace = BrWorkspace::new();
    let lint = run_br(&workspace, ["lint"], "lint_before_init");
    assert!(!lint.status.success());
}

#[test]
fn e2e_lint_clean_output_when_no_warnings() {
    let _log = common::test_log("e2e_lint_clean_output_when_no_warnings");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_clean_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let description = "## Acceptance Criteria\n- done";
    create_issue_with_description(
        &workspace,
        "Task with criteria",
        Some("task"),
        Some(description),
        "lint_clean_create",
    );

    let lint = run_br(&workspace, ["lint"], "lint_clean_run");
    assert!(
        lint.status.success(),
        "lint should succeed: {}",
        lint.stderr
    );
    assert!(lint.stdout.contains("No template warnings found"));
}

#[test]
fn e2e_lint_bug_missing_sections_json() {
    let _log = common::test_log("e2e_lint_bug_missing_sections_json");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_bug_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    create_issue_with_description(
        &workspace,
        "Bug with missing sections",
        Some("bug"),
        Some("Bug report"),
        "lint_bug_create",
    );

    let json = run_lint_json(&workspace, vec!["lint".to_string()], "lint_bug_json");
    assert_eq!(json["total"].as_u64(), Some(2));
    assert_eq!(json["issues"].as_u64(), Some(1));
    let missing = json["results"][0]["missing"]
        .as_array()
        .expect("missing array");
    let missing_text: Vec<String> = missing
        .iter()
        .filter_map(|value| value.as_str().map(str::to_string))
        .collect();
    assert!(missing_text.contains(&"## Steps to Reproduce".to_string()));
    assert!(missing_text.contains(&"## Acceptance Criteria".to_string()));
}

#[test]
fn e2e_lint_multiple_issues_aggregate_warnings() {
    let _log = common::test_log("e2e_lint_multiple_issues_aggregate_warnings");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_multi_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    create_issue_with_description(
        &workspace,
        "Bug missing sections",
        Some("bug"),
        Some("Bug report"),
        "lint_multi_bug",
    );
    create_issue_with_description(
        &workspace,
        "Task missing criteria",
        Some("task"),
        Some("Task description"),
        "lint_multi_task",
    );

    let json = run_lint_json(&workspace, vec!["lint".to_string()], "lint_multi_json");
    assert_eq!(json["issues"].as_u64(), Some(2));
    assert_eq!(json["total"].as_u64(), Some(3));
}

#[test]
fn e2e_lint_text_output_exit_code() {
    let _log = common::test_log("e2e_lint_text_output_exit_code");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_text_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    create_issue_with_description(
        &workspace,
        "Bug missing sections",
        Some("bug"),
        Some("Bug report"),
        "lint_text_bug",
    );

    let lint = run_br(&workspace, ["lint"], "lint_text_run");
    assert!(!lint.status.success());
    assert!(lint.stdout.contains("Template warnings"));
}

#[test]
fn e2e_lint_status_all_includes_closed() {
    let _log = common::test_log("e2e_lint_status_all_includes_closed");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_closed_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let id = create_issue_with_description(
        &workspace,
        "Closed bug",
        Some("bug"),
        Some("Bug report"),
        "lint_closed_bug",
    );

    let close = run_br(
        &workspace,
        ["close", &id, "--reason", "done"],
        "lint_closed_close",
    );
    assert!(close.status.success(), "close failed: {}", close.stderr);

    let json = run_lint_json(
        &workspace,
        vec![
            "lint".to_string(),
            "--status".to_string(),
            "all".to_string(),
        ],
        "lint_closed_json",
    );
    assert_eq!(json["issues"].as_u64(), Some(1));
}

#[test]
fn e2e_lint_type_filter_limits_results() {
    let _log = common::test_log("e2e_lint_type_filter_limits_results");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_type_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    create_issue_with_description(
        &workspace,
        "Bug missing sections",
        Some("bug"),
        Some("Bug report"),
        "lint_type_bug",
    );
    create_issue_with_description(
        &workspace,
        "Task with criteria",
        Some("task"),
        Some("## Acceptance Criteria\n- done"),
        "lint_type_task",
    );

    let json = run_lint_json(
        &workspace,
        vec!["lint".to_string(), "--type".to_string(), "bug".to_string()],
        "lint_type_json",
    );
    assert_eq!(json["issues"].as_u64(), Some(1));
    assert_eq!(json["results"][0]["type"].as_str(), Some("bug"));
}

#[test]
fn e2e_lint_ids_only_lints_selected() {
    let _log = common::test_log("e2e_lint_ids_only_lints_selected");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_ids_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let bug_id = create_issue_with_description(
        &workspace,
        "Bug missing sections",
        Some("bug"),
        Some("Bug report"),
        "lint_ids_bug",
    );
    create_issue_with_description(
        &workspace,
        "Task missing criteria",
        Some("task"),
        Some("Task description"),
        "lint_ids_task",
    );

    let json = run_lint_json(
        &workspace,
        vec!["lint".to_string(), bug_id.clone()],
        "lint_ids_json",
    );
    assert_eq!(json["issues"].as_u64(), Some(1));
    assert_eq!(json["results"][0]["id"].as_str(), Some(bug_id.as_str()));
}

#[test]
fn e2e_lint_skips_types_without_required_sections() {
    let _log = common::test_log("e2e_lint_skips_types_without_required_sections");
    let workspace = BrWorkspace::new();
    let init = run_br(&workspace, ["init"], "lint_skip_init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    create_issue_with_description(
        &workspace,
        "Chore without requirements",
        Some("chore"),
        Some("No requirements"),
        "lint_skip_chore",
    );

    let json = run_lint_json(&workspace, vec!["lint".to_string()], "lint_skip_json");
    assert_eq!(json["issues"].as_u64(), Some(0));
    assert_eq!(json["total"].as_u64(), Some(0));
}

// === Structured JSON Error Output Tests ===

/// Parse structured error JSON from stderr.
/// This handles the case where log lines may precede the JSON output.
fn parse_error_json(stderr: &str) -> Option<Value> {
    // First try parsing the whole stderr as JSON
    if let Ok(json) = serde_json::from_str(stderr) {
        return Some(json);
    }

    // If that fails, look for a JSON object starting with '{'
    // This handles cases where log lines precede the JSON output
    if let Some(start) = stderr.find('{') {
        let json_part = &stderr[start..];
        if let Ok(json) = serde_json::from_str(json_part) {
            return Some(json);
        }
    }

    None
}

/// Verify error JSON has required fields.
fn verify_error_structure(json: &Value) -> bool {
    let error = json.get("error");
    if error.is_none() {
        return false;
    }
    let error = error.unwrap();

    // Required fields
    error.get("code").is_some()
        && error.get("message").is_some()
        && error.get("retryable").is_some()
}

#[test]
fn e2e_structured_error_not_initialized() {
    let _log = common::test_log("e2e_structured_error_not_initialized");
    let workspace = BrWorkspace::new();

    // Don't init - test NOT_INITIALIZED error
    let result = run_br(&workspace, ["list", "--json"], "list_not_init_json");
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(2), "exit code should be 2");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "NOT_INITIALIZED");
    assert!(!error["retryable"].as_bool().unwrap());
    assert!(error["hint"].as_str().unwrap().contains("br init"));
}

#[test]
fn e2e_structured_error_issue_not_found() {
    let _log = common::test_log("e2e_structured_error_issue_not_found");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let result = run_br(
        &workspace,
        ["show", "bd-nonexistent", "--json"],
        "show_missing_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(3), "exit code should be 3");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "ISSUE_NOT_FOUND");
    assert!(!error["retryable"].as_bool().unwrap());
    assert!(error["context"]["searched_id"].is_string());
    assert!(error["hint"].as_str().unwrap().contains("br list"));
}

#[test]
fn e2e_structured_error_cycle_detected() {
    let _log = common::test_log("e2e_structured_error_cycle_detected");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    // A depends on B
    let dep_add = run_br(&workspace, ["dep", "add", &id_a, &id_b], "dep_add");
    assert!(dep_add.status.success());

    // B depends on A - would create cycle
    let result = run_br(
        &workspace,
        ["dep", "add", &id_b, &id_a, "--json"],
        "dep_cycle_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(5), "exit code should be 5");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "CYCLE_DETECTED");
    assert!(!error["retryable"].as_bool().unwrap());
    assert!(error["context"]["cycle_path"].is_string());
}

#[test]
fn e2e_structured_error_self_dependency() {
    let _log = common::test_log("e2e_structured_error_self_dependency");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Self dep issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    let result = run_br(
        &workspace,
        ["dep", "add", &id, &id, "--json"],
        "dep_self_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(5), "exit code should be 5");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "SELF_DEPENDENCY");
    assert!(!error["retryable"].as_bool().unwrap());
}

#[test]
fn e2e_structured_error_ambiguous_id() {
    let _log = common::test_log("e2e_structured_error_ambiguous_id");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let mut ids: Vec<String> = Vec::new();
    let mut attempt = 0;
    let mut ambiguous_prefix: Option<String> = None;

    // Create issues until we have ambiguous IDs
    while ambiguous_prefix.is_none() && attempt < 30 {
        let title = format!("Structured test {attempt}");
        let create = run_br(&workspace, ["create", &title], &format!("create_{attempt}"));
        assert!(create.status.success());
        let id = parse_created_id(&create.stdout);
        ids.push(id);

        // Check for prefix collisions
        for i in 0..ids.len() {
            for j in (i + 1)..ids.len() {
                let hash_i = ids[i].split('-').nth(1).unwrap_or("");
                let hash_j = ids[j].split('-').nth(1).unwrap_or("");
                if !hash_i.is_empty()
                    && !hash_j.is_empty()
                    && hash_i.chars().next() == hash_j.chars().next()
                {
                    let common_char = hash_i.chars().next().unwrap();
                    ambiguous_prefix = Some(common_char.to_string());
                    break;
                }
            }
            if ambiguous_prefix.is_some() {
                break;
            }
        }
        attempt += 1;
    }

    let prefix = ambiguous_prefix.expect("failed to create ambiguous IDs");

    let result = run_br(
        &workspace,
        ["show", &prefix, "--json"],
        "show_ambiguous_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(3), "exit code should be 3");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "AMBIGUOUS_ID");
    assert!(error["retryable"].as_bool().unwrap());
    assert!(error["context"]["matches"].is_array());
}

#[test]
fn e2e_structured_error_jsonl_parse() {
    let _log = common::test_log("e2e_structured_error_jsonl_parse");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Create malformed JSONL
    let beads_dir = workspace.root.join(".beads");
    let issues_path = beads_dir.join("issues.jsonl");
    fs::write(&issues_path, "{ not valid json\n").expect("write bad jsonl");

    let result = run_br(
        &workspace,
        ["sync", "--import-only", "--json"],
        "import_bad_json",
    );
    assert!(!result.status.success());
    // JSONL parse errors should be exit code 6 (sync errors) or 7 (config)
    let exit_code = result.status.code().unwrap_or(0);
    assert!(
        exit_code == 6 || exit_code == 7,
        "unexpected exit code: {exit_code}"
    );

    // The error output should be valid JSON
    let json = parse_error_json(&result.stderr);
    if let Some(json) = json {
        assert!(verify_error_structure(&json), "missing required fields");
    }
    // Note: Some errors may not produce structured JSON yet - that's OK
}

#[test]
fn e2e_structured_error_conflict_markers() {
    let _log = common::test_log("e2e_structured_error_conflict_markers");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Create JSONL with conflict markers
    let beads_dir = workspace.root.join(".beads");
    let issues_path = beads_dir.join("issues.jsonl");
    fs::write(
        &issues_path,
        "<<<<<<< HEAD\n{\"id\":\"bd-abc\"}\n=======\n{\"id\":\"bd-def\"}\n>>>>>>> branch\n",
    )
    .expect("write conflict jsonl");

    let result = run_br(
        &workspace,
        ["sync", "--import-only", "--json"],
        "import_conflict_json",
    );
    assert!(!result.status.success());

    // Should detect conflict markers
    assert!(
        result.stderr.contains("conflict") || result.stderr.contains("CONFLICT"),
        "should detect conflict markers"
    );
}

#[test]
fn e2e_sync_flush_refuses_to_overwrite_conflict_markers() {
    let _log = common::test_log("e2e_sync_flush_refuses_to_overwrite_conflict_markers");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(
        &workspace,
        ["create", "Flush conflict seed", "--no-auto-flush"],
        "create_seed",
    );
    assert!(create.status.success(), "create failed: {}", create.stderr);
    let id = parse_created_id(&create.stdout);

    let first_flush = run_br(&workspace, ["sync", "--flush-only"], "first_flush");
    assert!(
        first_flush.status.success(),
        "initial flush failed: {}",
        first_flush.stderr
    );

    let issues_path = workspace.root.join(".beads").join("issues.jsonl");
    let original_jsonl = fs::read_to_string(&issues_path).expect("read initial jsonl");
    assert!(
        original_jsonl.contains("Flush conflict seed"),
        "initial flush should export the seed issue"
    );

    let update = run_br(
        &workspace,
        [
            "update",
            &id,
            "--title",
            "Dirty title that must not be flushed over conflict markers",
            "--no-auto-flush",
        ],
        "dirty_update",
    );
    assert!(update.status.success(), "update failed: {}", update.stderr);

    let conflicted_jsonl = format!(
        "<<<<<<< HEAD\n{}=======\n{}>>>>>>> feature-branch\n",
        original_jsonl, original_jsonl
    );
    fs::write(&issues_path, &conflicted_jsonl).expect("write conflicted jsonl");

    let refused_flush = run_br(
        &workspace,
        ["sync", "--flush-only", "--json"],
        "refused_flush",
    );
    assert!(
        !refused_flush.status.success(),
        "flush should fail while issues.jsonl contains merge conflict markers"
    );
    let exit_code = refused_flush.status.code().unwrap_or(0);
    assert!(
        exit_code == 6 || exit_code == 7,
        "conflict-marker flush refusal should be a sync/config error, got {exit_code}"
    );
    assert!(
        refused_flush.stderr.contains("conflict") || refused_flush.stderr.contains("CONFLICT"),
        "flush error should explain the unresolved conflict markers: {}",
        refused_flush.stderr
    );

    let after_refusal = fs::read_to_string(&issues_path).expect("read refused jsonl");
    assert_eq!(
        after_refusal, conflicted_jsonl,
        "flush refusal must leave the conflicted JSONL byte-for-byte untouched"
    );
    assert!(
        !after_refusal.contains("Dirty title that must not be flushed over conflict markers"),
        "dirty DB title must not be exported over unresolved JSONL conflict markers"
    );
}

#[test]
fn e2e_custom_type_accepted() {
    let _log = common::test_log("e2e_custom_type_accepted");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Custom types are accepted (not rejected as invalid)
    let result = run_br(
        &workspace,
        ["create", "Test issue", "--type", "custom_type", "--json"],
        "create_custom_type_json",
    );
    assert!(
        result.status.success(),
        "custom types should be accepted: {}",
        result.stderr
    );

    // Verify the custom type is stored correctly
    let json: serde_json::Value =
        serde_json::from_str(&result.stdout).expect("should be valid JSON");
    assert_eq!(
        json["issue_type"], "custom_type",
        "custom type should be preserved"
    );
}

#[test]
fn e2e_structured_error_invalid_priority() {
    let _log = common::test_log("e2e_structured_error_invalid_priority");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Test invalid priority (out of 0-4 range)
    let result = run_br(
        &workspace,
        ["create", "Test issue", "--priority", "10", "--json"],
        "create_invalid_priority_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(4), "exit code should be 4");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "INVALID_PRIORITY");
    assert!(error["retryable"].as_bool().unwrap());
    let hint = error["hint"].as_str().unwrap();
    assert!(
        hint.contains('0') && hint.contains('4') || hint.contains("between"),
        "hint should mention valid priority range, got: {hint}"
    );
}

// === --no-color mode tests for stable snapshots ===

#[test]
fn e2e_error_text_mode_no_color() {
    let _log = common::test_log("e2e_error_text_mode_no_color");
    let workspace = BrWorkspace::new();

    // Test NOT_INITIALIZED error in no-color mode
    let result = run_br(&workspace, ["list", "--no-color"], "list_not_init_no_color");
    assert!(!result.status.success());

    // Output should not contain ANSI escape codes
    assert!(
        !result.stderr.contains("\x1b["),
        "stderr should not contain ANSI escape codes"
    );
    assert!(
        !result.stdout.contains("\x1b["),
        "stdout should not contain ANSI escape codes"
    );
}

#[test]
fn e2e_error_text_vs_json_parity() {
    let _log = common::test_log("e2e_error_text_vs_json_parity");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Same error in text mode
    let text_result = run_br(
        &workspace,
        ["show", "bd-nonexistent", "--no-color"],
        "show_missing_text",
    );
    assert!(!text_result.status.success());

    // Same error in JSON mode
    let json_result = run_br(
        &workspace,
        ["show", "bd-nonexistent", "--json"],
        "show_missing_json",
    );
    assert!(!json_result.status.success());

    // Both should have same exit code
    assert_eq!(
        text_result.status.code(),
        json_result.status.code(),
        "text and JSON mode should have same exit code"
    );

    // JSON mode should produce valid structured error
    let json = parse_error_json(&json_result.stderr).expect("JSON mode should produce valid JSON");
    assert!(
        verify_error_structure(&json),
        "JSON error should have required fields"
    );

    // Text mode output should contain error message (not JSON)
    assert!(
        text_result.stderr.contains("not found") || text_result.stderr.contains("No issue"),
        "text mode should contain human-readable error"
    );
}

#[test]
fn e2e_error_multiple_errors_same_exit_code() {
    let _log = common::test_log("e2e_error_multiple_errors_same_exit_code");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let _id = parse_created_id(&create.stdout);

    // Validation errors should return exit code 4
    // Note: invalid type is NOT tested here because custom types are allowed
    let invalid_priority = run_br(
        &workspace,
        ["create", "Test", "--priority", "99", "--json"],
        "invalid_priority",
    );

    assert_eq!(
        invalid_priority.status.code(),
        Some(4),
        "invalid priority should be exit 4"
    );
}

#[test]
fn e2e_error_exit_code_categories() {
    let _log = common::test_log("e2e_error_exit_code_categories");
    let workspace = BrWorkspace::new();

    // Exit code 2: Database/initialization errors
    let not_init = run_br(&workspace, ["list", "--json"], "not_init");
    assert_eq!(
        not_init.status.code(),
        Some(2),
        "NOT_INITIALIZED should be exit 2"
    );

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    // Exit code 3: Issue errors
    let not_found = run_br(&workspace, ["show", "bd-missing", "--json"], "not_found");
    assert_eq!(
        not_found.status.code(),
        Some(3),
        "ISSUE_NOT_FOUND should be exit 3"
    );

    // Exit code 4: Validation errors (already tested above)

    // Exit code 5: Dependency errors
    let create = run_br(&workspace, ["create", "Self dep"], "create_self");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    let self_dep = run_br(&workspace, ["dep", "add", &id, &id, "--json"], "self_dep");
    assert_eq!(
        self_dep.status.code(),
        Some(5),
        "SELF_DEPENDENCY should be exit 5"
    );
}

// === Additional Validation + Error Parity Tests ===

#[test]
fn e2e_structured_error_label_validation() {
    let _log = common::test_log("e2e_structured_error_label_validation");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Test label with invalid characters (spaces not allowed)
    let result = run_br(
        &workspace,
        ["update", &id, "--add-label", "bad label", "--json"],
        "update_bad_label_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(4), "exit code should be 4");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "VALIDATION_FAILED");
    assert!(error["retryable"].as_bool().unwrap());
    assert!(
        error["message"].as_str().unwrap().contains("label")
            || error["hint"].as_str().unwrap_or("").contains("label"),
        "error should mention label"
    );
}

#[test]
fn e2e_structured_error_label_too_long() {
    let _log = common::test_log("e2e_structured_error_label_too_long");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Create a label that exceeds 50 characters
    let long_label = "a".repeat(60);
    let result = run_br(
        &workspace,
        ["update", &id, "--add-label", &long_label, "--json"],
        "update_long_label_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(4), "exit code should be 4");

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    assert_eq!(error["code"], "VALIDATION_FAILED");
}

#[test]
fn e2e_structured_error_dependency_target_not_found() {
    let _log = common::test_log("e2e_structured_error_dependency_target_not_found");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Try to add dependency on non-existent issue
    // The implementation returns ISSUE_NOT_FOUND for missing dependency targets
    let result = run_br(
        &workspace,
        ["dep", "add", &id, "bd-nonexistent", "--json"],
        "dep_missing_target_json",
    );
    assert!(!result.status.success());
    assert_eq!(
        result.status.code(),
        Some(3),
        "exit code should be 3 (issue not found)"
    );

    let json = parse_error_json(&result.stderr).expect("should be valid JSON");
    assert!(verify_error_structure(&json), "missing required fields");

    let error = &json["error"];
    // Returns ISSUE_NOT_FOUND since the target issue doesn't exist
    assert_eq!(error["code"], "ISSUE_NOT_FOUND");
    assert!(!error["retryable"].as_bool().unwrap());
    assert!(
        error["context"]["searched_id"]
            .as_str()
            .unwrap()
            .contains("nonexistent")
    );
}

#[test]
fn e2e_dependency_idempotent_duplicate() {
    let _log = common::test_log("e2e_dependency_idempotent_duplicate");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    // Add dependency first time - should succeed
    let dep_add = run_br(&workspace, ["dep", "add", &id_a, &id_b], "dep_add_first");
    assert!(dep_add.status.success());

    // Add same dependency again - should succeed (idempotent) with status "exists"
    let result = run_br(
        &workspace,
        ["dep", "add", &id_a, &id_b, "--json"],
        "dep_add_duplicate_json",
    );
    assert!(
        result.status.success(),
        "duplicate dependency should be idempotent"
    );

    // Parse output as success JSON (not error)
    let json: Value = serde_json::from_str(&result.stdout).expect("should be valid JSON");
    assert_eq!(
        json["status"].as_str().unwrap_or(""),
        "exists",
        "status should be 'exists'"
    );
    assert_eq!(
        json["action"].as_str().unwrap_or(""),
        "already_exists",
        "action should be 'already_exists'"
    );
}

#[test]
fn e2e_dependency_metadata_flag_persists_to_jsonl() {
    let _log = common::test_log("e2e_dependency_metadata_flag_persists_to_jsonl");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let dep_add = run_br(
        &workspace,
        [
            "dep",
            "add",
            &id_a,
            &id_b,
            "--metadata",
            r#"{"source":"cli","reason":"gate"}"#,
        ],
        "dep_add_metadata",
    );
    assert!(
        dep_add.status.success(),
        "dep add failed: {}",
        dep_add.stderr
    );

    let sync = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(sync.status.success(), "sync failed: {}", sync.stderr);

    let jsonl_path = workspace.root.join(".beads").join("issues.jsonl");
    let contents = fs::read_to_string(&jsonl_path).expect("read issues jsonl");
    let issue = contents
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| serde_json::from_str::<Value>(line).expect("valid issue json"))
        .find(|value| value["id"] == id_a)
        .expect("issue A exported");

    let deps = issue["dependencies"]
        .as_array()
        .expect("dependencies array");
    assert_eq!(deps.len(), 1);
    assert_eq!(deps[0]["depends_on_id"], id_b);
    assert_eq!(deps[0]["metadata"], r#"{"source":"cli","reason":"gate"}"#);
}

#[test]
fn e2e_dependency_remove_json_reports_removed_type() {
    let _log = common::test_log("e2e_dependency_remove_json_reports_removed_type");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let dep_add = run_br(
        &workspace,
        ["dep", "add", &id_a, &id_b, "--type", "waits-for"],
        "dep_add_waits_for",
    );
    assert!(
        dep_add.status.success(),
        "dep add failed: {}",
        dep_add.stderr
    );

    let result = run_br(
        &workspace,
        ["dep", "remove", &id_a, &id_b, "--json"],
        "dep_remove_json",
    );
    assert!(
        result.status.success(),
        "dep remove failed: {}",
        result.stderr
    );

    let json: Value = serde_json::from_str(&result.stdout).expect("should be valid JSON");
    assert_eq!(json["status"], "ok");
    assert_eq!(json["action"], "removed");
    assert_eq!(json["type"], "waits-for");
}

#[test]
fn e2e_delete_with_dependents_preview() {
    let _log = common::test_log("e2e_delete_with_dependents_preview");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    // B depends on A
    let dep_add = run_br(&workspace, ["dep", "add", &id_b, &id_a], "dep_add");
    assert!(dep_add.status.success());

    // Delete A (which has B as dependent) - shows preview mode warning
    // The command exits 0 (preview mode) but warns about dependents
    let result = run_br(&workspace, ["delete", &id_a], "delete_with_deps");
    assert!(
        result.status.success(),
        "delete with dependents should show preview"
    );
    assert!(
        result.stdout.contains("depend on") || result.stdout.contains("dependents"),
        "should mention dependents in output"
    );
    assert!(
        result.stdout.contains("--force") || result.stdout.contains("--cascade"),
        "should suggest force or cascade options"
    );

    // Issue should still exist after preview
    let show = run_br(&workspace, ["show", &id_a], "show_after_preview");
    assert!(
        show.status.success(),
        "issue should still exist after preview"
    );
}

#[test]
fn e2e_delete_json_sorts_deleted_ids() {
    let _log = common::test_log("e2e_delete_json_sorts_deleted_ids");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Delete A"], "create_delete_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Delete B"], "create_delete_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let result = run_br(
        &workspace,
        ["delete", &id_b, &id_a, "--json"],
        "delete_json_sorted_ids",
    );
    assert!(
        result.status.success(),
        "delete json failed: {}",
        result.stderr
    );

    let json: Value = serde_json::from_str(&result.stdout).expect("should be valid JSON");
    let deleted = json["deleted"].as_array().expect("deleted array");
    let deleted_ids: Vec<&str> = deleted
        .iter()
        .map(|value| value.as_str().expect("deleted id"))
        .collect();

    let mut expected = vec![id_a.as_str(), id_b.as_str()];
    expected.sort_unstable();
    assert_eq!(deleted_ids, expected);
    assert_eq!(json["deleted_count"], 2);
}

#[test]
fn e2e_delete_dry_run_sorts_requested_ids() {
    let _log = common::test_log("e2e_delete_dry_run_sorts_requested_ids");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Dry Run A"], "create_dry_run_a");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Dry Run B"], "create_dry_run_b");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let result = run_br(
        &workspace,
        ["delete", &id_b, &id_a, "--dry-run"],
        "delete_dry_run_sorted_ids",
    );
    assert!(
        result.status.success(),
        "delete dry-run failed: {}",
        result.stderr
    );

    let listed_ids: Vec<&str> = result
        .stdout
        .lines()
        .filter_map(|line| line.strip_prefix("  - "))
        .filter_map(|line| line.split(':').next())
        .take(2)
        .collect();

    let mut expected = vec![id_a.as_str(), id_b.as_str()];
    expected.sort_unstable();
    assert_eq!(listed_ids, expected);
}

#[test]
fn e2e_delete_dry_run_json_returns_structured_preview() {
    let _log = common::test_log("e2e_delete_dry_run_json_returns_structured_preview");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(
        &workspace,
        ["create", "Dry Run JSON A"],
        "create_dry_run_json_a",
    );
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(
        &workspace,
        ["create", "Dry Run JSON B"],
        "create_dry_run_json_b",
    );
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let result = run_br(
        &workspace,
        ["delete", &id_b, &id_a, "--dry-run", "--json"],
        "delete_dry_run_json",
    );
    assert!(
        result.status.success(),
        "delete dry-run --json failed: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("delete dry-run preview json");
    assert_eq!(json["preview"], true);
    let ids = json["would_delete"].as_array().expect("would_delete array");
    let mut expected = vec![id_a.as_str(), id_b.as_str()];
    expected.sort_unstable();
    let actual: Vec<&str> = ids
        .iter()
        .map(|value| value.as_str().expect("preview delete id"))
        .collect();
    assert_eq!(actual, expected);
}

#[test]
fn e2e_delete_with_dependents_json_returns_structured_preview() {
    let _log = common::test_log("e2e_delete_with_dependents_json_returns_structured_preview");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_a = run_br(&workspace, ["create", "Issue A"], "create_a_json_preview");
    assert!(create_a.status.success());
    let id_a = parse_created_id(&create_a.stdout);

    let create_b = run_br(&workspace, ["create", "Issue B"], "create_b_json_preview");
    assert!(create_b.status.success());
    let id_b = parse_created_id(&create_b.stdout);

    let dep_add = run_br(
        &workspace,
        ["dep", "add", &id_b, &id_a],
        "dep_add_json_preview",
    );
    assert!(dep_add.status.success());

    let result = run_br(
        &workspace,
        ["delete", &id_a, "--json"],
        "delete_with_dependents_json_preview",
    );
    assert!(
        result.status.success(),
        "delete with dependents --json should return preview: {}",
        result.stderr
    );

    let payload = extract_json_payload(&result.stdout);
    let json: Value = serde_json::from_str(&payload).expect("delete dependent preview json");
    assert_eq!(json["preview"], true);
    assert_eq!(json["would_delete"][0], id_a);
    let blocked = json["blocked_dependents"]
        .as_array()
        .expect("blocked_dependents array");
    assert_eq!(blocked.len(), 1);
    assert_eq!(blocked[0], id_b);
}

#[test]
fn e2e_delete_ignores_non_blocking_related_dependencies() {
    let _log = common::test_log("e2e_delete_ignores_non_blocking_related_dependencies");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_anchor = run_br(&workspace, ["create", "Anchor"], "create_anchor");
    assert!(create_anchor.status.success());
    let anchor_id = parse_created_id(&create_anchor.stdout);

    let create_related = run_br(&workspace, ["create", "Related"], "create_related");
    assert!(create_related.status.success());
    let related_id = parse_created_id(&create_related.stdout);

    let dep_add = run_br(
        &workspace,
        ["dep", "add", &related_id, &anchor_id, "--type", "related"],
        "dep_add_related",
    );
    assert!(
        dep_add.status.success(),
        "dep add failed: {}",
        dep_add.stderr
    );

    let delete = run_br(
        &workspace,
        ["delete", &anchor_id, "--json"],
        "delete_related_edge_json",
    );
    assert!(delete.status.success(), "delete failed: {}", delete.stderr);

    let payload = extract_json_payload(&delete.stdout);
    let json: Value = serde_json::from_str(&payload).expect("delete json");
    assert_eq!(json["deleted_count"], 1);
    assert_eq!(json["deleted"][0], anchor_id);
    assert!(
        json.get("preview").is_none(),
        "non-blocking related edges should not trigger preview: {json}"
    );
}

#[test]
fn e2e_delete_child_with_parent_child_dependency_previews_parent() {
    let _log = common::test_log("e2e_delete_child_with_parent_child_dependency_previews_parent");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create_parent = run_br(&workspace, ["create", "Parent"], "create_parent");
    assert!(create_parent.status.success());
    let parent_id = parse_created_id(&create_parent.stdout);

    let create_child = run_br(&workspace, ["create", "Child"], "create_child");
    assert!(create_child.status.success());
    let child_id = parse_created_id(&create_child.stdout);

    let dep_add = run_br(
        &workspace,
        [
            "dep",
            "add",
            &child_id,
            &parent_id,
            "--type",
            "parent-child",
        ],
        "dep_add_parent_child",
    );
    assert!(
        dep_add.status.success(),
        "dep add failed: {}",
        dep_add.stderr
    );

    let delete = run_br(
        &workspace,
        ["delete", &child_id, "--json"],
        "delete_child_parent_child_json",
    );
    assert!(
        delete.status.success(),
        "delete should return preview json: {}",
        delete.stderr
    );

    let payload = extract_json_payload(&delete.stdout);
    let json: Value = serde_json::from_str(&payload).expect("delete preview json");
    assert_eq!(json["preview"], true);
    assert_eq!(json["would_delete"][0], child_id);
    let blocked = json["blocked_dependents"]
        .as_array()
        .expect("blocked_dependents array");
    assert_eq!(blocked.len(), 1);
    assert_eq!(blocked[0], parent_id);
}

#[test]
fn e2e_delete_hard_json_reports_removed_labels_and_events() {
    let _log = common::test_log("e2e_delete_hard_json_reports_removed_labels_and_events");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(
        &workspace,
        ["create", "Delete counters issue"],
        "create_delete_counters",
    );
    assert!(create.status.success());
    let issue_id = parse_created_id(&create.stdout);

    let label_add = run_br(
        &workspace,
        ["label", "add", &issue_id, "triage"],
        "label_add_delete_counters",
    );
    assert!(
        label_add.status.success(),
        "label add failed: {}",
        label_add.stderr
    );

    let delete = run_br(
        &workspace,
        ["delete", &issue_id, "--hard", "--json"],
        "delete_hard_counters_json",
    );
    assert!(delete.status.success(), "delete failed: {}", delete.stderr);

    let payload = extract_json_payload(&delete.stdout);
    let json: Value = serde_json::from_str(&payload).expect("delete hard json");
    assert_eq!(json["labels_removed"], 1);
    assert!(
        json["events_removed"].as_u64().unwrap_or(0) >= 2,
        "hard delete should report removed audit events: {json}"
    );
}

#[test]
fn e2e_validation_error_empty_label() {
    let _log = common::test_log("e2e_validation_error_empty_label");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Empty label should fail validation
    let result = run_br(
        &workspace,
        ["update", &id, "--add-label", "", "--json"],
        "update_empty_label_json",
    );
    assert!(!result.status.success());
    assert_eq!(result.status.code(), Some(4), "exit code should be 4");
}

#[test]
fn e2e_validation_special_characters_in_label() {
    let _log = common::test_log("e2e_validation_special_characters_in_label");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Valid labels (alphanumeric, hyphen, underscore, colon)
    let valid_labels = ["bug", "feat-1", "scope:subsystem", "test_case"];
    for label in valid_labels {
        let result = run_br(
            &workspace,
            ["update", &id, "--add-label", label],
            &format!("add_label_{}", label.replace(':', "_")),
        );
        assert!(
            result.status.success(),
            "label '{}' should be valid: {}",
            label,
            result.stderr
        );
    }

    // Create a new issue for testing invalid labels (to avoid label conflict)
    let create2 = run_br(&workspace, ["create", "Test issue 2"], "create2");
    assert!(create2.status.success());
    let id2 = parse_created_id(&create2.stdout);

    // Invalid labels (special characters not allowed)
    let invalid_labels = ["@mention", "has/slash", "with.dot", "emoji🎉"];
    for label in invalid_labels {
        let result = run_br(
            &workspace,
            ["update", &id2, "--add-label", label, "--json"],
            &format!("add_invalid_label_{}", label.len()),
        );
        assert!(
            !result.status.success(),
            "label '{}' should be invalid",
            label
        );
    }
}

#[test]
fn e2e_error_text_json_parity_validation() {
    let _log = common::test_log("e2e_error_text_json_parity_validation");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success());

    let create = run_br(&workspace, ["create", "Test issue"], "create");
    assert!(create.status.success());
    let id = parse_created_id(&create.stdout);

    // Same validation error in text mode
    let text_result = run_br(
        &workspace,
        ["update", &id, "--add-label", "bad label", "--no-color"],
        "label_error_text",
    );
    assert!(!text_result.status.success());

    // Same validation error in JSON mode
    let json_result = run_br(
        &workspace,
        ["update", &id, "--add-label", "bad label", "--json"],
        "label_error_json",
    );
    assert!(!json_result.status.success());

    // Both should have same exit code
    assert_eq!(
        text_result.status.code(),
        json_result.status.code(),
        "text and JSON mode should have same exit code for validation errors"
    );

    // JSON mode should produce valid structured error
    let json = parse_error_json(&json_result.stderr).expect("JSON mode should produce valid JSON");
    assert!(
        verify_error_structure(&json),
        "JSON error should have required fields"
    );
}

#[test]
fn e2e_sync_merge_detects_conflict_markers_in_base_snapshot() {
    // Regression: `execute_merge` loads `beads.base.jsonl` via
    // `load_base_snapshot` *before* scanning the main JSONL for conflict
    // markers. If the base snapshot itself contained unresolved
    // `<<<<<<<` / `=======` / `>>>>>>>` regions (a rare but possible state
    // when a user commits the base snapshot against the default gitignore
    // and then hits a botched `git merge`), the merge would fail with a
    // cryptic "Invalid JSON in base snapshot at line 1" instead of the
    // helpful "merge conflict markers detected" diagnostic. The fix
    // scans the base snapshot for markers before attempting to parse.
    let _log = common::test_log("e2e_sync_merge_detects_conflict_markers_in_base_snapshot");
    let workspace = BrWorkspace::new();

    let init = run_br(&workspace, ["init"], "init");
    assert!(init.status.success(), "init failed: {}", init.stderr);

    let create = run_br(&workspace, ["create", "Seed"], "create");
    assert!(create.status.success(), "create failed: {}", create.stderr);

    // First flush so the JSONL is valid and the main sync path won't
    // short-circuit before the merge code runs.
    let flush = run_br(&workspace, ["sync", "--flush-only"], "sync_flush");
    assert!(flush.status.success(), "flush failed: {}", flush.stderr);

    // Build a base snapshot that contains merge-conflict markers as if a
    // user committed `beads.base.jsonl` and then hit a botched `git merge`.
    let jsonl_path = workspace.root.join(".beads").join("issues.jsonl");
    let clean = fs::read_to_string(&jsonl_path).expect("read jsonl");
    let base_path = workspace.root.join(".beads").join("beads.base.jsonl");
    let conflicted = format!("<<<<<<< HEAD\n{clean}=======\n{clean}>>>>>>> branch\n");
    fs::write(&base_path, &conflicted).expect("write conflicted base snapshot");

    // Merge must refuse with a conflict-markers diagnostic instead of a
    // generic "Invalid JSON in base snapshot" parse error.
    let merge = run_br(&workspace, ["sync", "--merge"], "sync_merge");
    assert!(
        !merge.status.success(),
        "merge should fail when base snapshot contains conflict markers: stdout={} stderr={}",
        merge.stdout,
        merge.stderr
    );
    let lower = merge.stderr.to_lowercase();
    assert!(
        lower.contains("conflict") || lower.contains("marker"),
        "merge error should mention conflict markers, got stderr: {}",
        merge.stderr
    );
    assert!(
        !lower.contains("invalid json in base snapshot"),
        "merge error should surface the conflict-markers diagnostic rather than the generic JSON parse failure, got stderr: {}",
        merge.stderr
    );
}