beads_rust 0.5.3

Agent-first issue tracker (SQLite + JSONL)
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
//! E2E tests for `SQLite` lock handling and concurrency semantics.
//!
//! Validates:
//! - Lock contention with overlapping write operations
//! - --lock-timeout behavior and proper error codes
//! - Concurrent read-only operations succeed
//!
//! Related: beads_rust-uahy

mod common;

use assert_cmd::Command;
use beads_rust::franken_sync::Connection;
use common::dataset_registry::{DatasetRegistry, IsolatedDataset, KnownDataset};
use fsqlite_types::SqliteValue;
use std::ffi::OsStr;
use std::fs::{self, OpenOptions};
use std::path::Path;
use std::path::PathBuf;
use std::process::{Command as StdCommand, Stdio};
use std::sync::{Arc, Barrier};
use std::thread;
use std::time::{Duration, Instant};
use tempfile::TempDir;

#[cfg(target_os = "linux")]
const WRITE_LOCK_WAIT_OBSERVATION_TIMEOUT: Duration = Duration::from_secs(5);
#[cfg(target_os = "linux")]
const WRITE_LOCK_WAIT_POLL_INTERVAL: Duration = Duration::from_millis(25);
const CONTENTION_SUCCESS_LOCK_TIMEOUT_MS: &str = "1000";

/// Result of running a br command.
#[derive(Debug)]
struct BrResult {
    stdout: String,
    stderr: String,
    success: bool,
    exit_code: Option<i32>,
    _duration: Duration,
}

fn should_clear_inherited_br_env(key: &OsStr) -> bool {
    let key = key.to_string_lossy();
    key.starts_with("BD_")
        || key.starts_with("BEADS_")
        || matches!(
            key.as_ref(),
            "BR_OUTPUT_FORMAT" | "TOON_DEFAULT_FORMAT" | "TOON_STATS"
        )
}

fn clear_inherited_br_env(cmd: &mut Command) {
    for (key, _) in std::env::vars_os() {
        if should_clear_inherited_br_env(&key) {
            cmd.env_remove(&key);
        }
    }
}

fn clear_inherited_br_env_std(cmd: &mut StdCommand) {
    for (key, _) in std::env::vars_os() {
        if should_clear_inherited_br_env(&key) {
            cmd.env_remove(&key);
        }
    }
}

fn isolated_temp_dir(label: &str) -> TempDir {
    TempDir::new_in(common::cli::isolated_temp_root())
        .unwrap_or_else(|error| panic!("create {label}: {error}"))
}

fn spawn_br_child_in_dir<I, S>(root: &Path, args: I) -> std::process::Child
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    let mut cmd = StdCommand::new(assert_cmd::cargo::cargo_bin!("br"));
    cmd.current_dir(root);
    cmd.args(args);
    clear_inherited_br_env_std(&mut cmd);
    cmd.env("NO_COLOR", "1");
    cmd.env("RUST_LOG", "error");
    cmd.env("RUST_BACKTRACE", "1");
    cmd.env("HOME", root);
    // Hermetic $PATH: dual `br` installs otherwise trip the br_path_dupes
    // doctor warning inside spawned doctor runs (beads_rust-ozdh class).
    cmd.env("PATH", common::cli::deduplicated_br_path());
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    cmd.spawn().expect("spawn br child")
}

#[cfg(target_os = "linux")]
fn read_child_wait_channel(pid: u32) -> Option<String> {
    fs::read_to_string(format!("/proc/{pid}/wchan"))
        .ok()
        .map(|channel| channel.trim().to_string())
}

#[cfg(target_os = "linux")]
fn is_write_lock_wait_channel(channel: &str) -> bool {
    let channel = channel.to_ascii_lowercase();
    channel.contains("lock")
        || channel.contains("flock")
        // blocking_write_lock_with_timeout uses bounded try_lock polling.
        // While contended, Linux commonly reports the waiter in the sleep
        // between polls rather than inside flock/lock_file_wait.
        || channel.contains("nanosleep")
        || channel.contains("hrtimer")
}

fn wait_for_child_to_block_on_write_lock(child: &mut std::process::Child, label: &str) {
    #[cfg(target_os = "linux")]
    {
        let deadline = Instant::now() + WRITE_LOCK_WAIT_OBSERVATION_TIMEOUT;

        loop {
            let status = child.try_wait().expect("poll child while waiting for lock");
            assert!(
                status.is_none(),
                "{label} exited before reaching .write.lock contention: {status:?}"
            );

            let wait_channel = read_child_wait_channel(child.id());
            if wait_channel
                .as_deref()
                .is_some_and(is_write_lock_wait_channel)
            {
                return;
            }

            assert!(
                Instant::now() < deadline,
                "{label} stayed alive but was never observed blocked on .write.lock; last wait channel: {wait_channel:?}"
            );
            thread::sleep(WRITE_LOCK_WAIT_POLL_INTERVAL);
        }
    }

    #[cfg(not(target_os = "linux"))]
    {
        thread::sleep(Duration::from_millis(250));
        let status = child.try_wait().expect("poll child while waiting for lock");
        assert!(
            status.is_none(),
            "{label} should still be waiting on .write.lock; status={status:?}"
        );
    }
}

/// Run br command in a specific directory.
fn run_br_in_dir<I, S>(root: &PathBuf, args: I) -> BrResult
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
{
    run_br_in_dir_with_env(root, args, std::iter::empty::<(String, String)>())
}

/// Run br command in a specific directory with environment overrides.
fn run_br_in_dir_with_env<I, S, E, K, V>(root: &PathBuf, args: I, env_vars: E) -> BrResult
where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
    E: IntoIterator<Item = (K, V)>,
    K: AsRef<OsStr>,
    V: AsRef<OsStr>,
{
    let start = Instant::now();
    let mut cmd = Command::cargo_bin("br").expect("find br binary");
    cmd.current_dir(root);
    cmd.args(args);
    clear_inherited_br_env(&mut cmd);
    // Hermetic defaults; explicit env_vars below may override RUST_LOG.
    cmd.env("RUST_LOG", "error");
    cmd.env("PATH", common::cli::deduplicated_br_path());
    cmd.envs(env_vars);
    cmd.env("NO_COLOR", "1");
    cmd.env("RUST_BACKTRACE", "1");
    cmd.env("HOME", root);

    let output = cmd.output().expect("run br");
    let duration = start.elapsed();

    BrResult {
        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
        success: output.status.success(),
        exit_code: output.status.code(),
        _duration: duration,
    }
}

/// Helper to parse created issue ID from stdout.
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);
    normalized
        .strip_prefix("Created ")
        .and_then(|rest| rest.split(':').next())
        .unwrap_or("")
        .trim()
        .to_string()
}

fn is_expected_contention_failure(result: &BrResult) -> bool {
    let combined = format!("{} {}", result.stdout, result.stderr).to_lowercase();
    !result.success
        && (combined.contains("busy")
            || combined.contains("locked")
            || combined.contains("lock timeout")
            || combined.contains("timed out")
            || combined.contains("sync conflict")
            || combined.contains("jsonl is newer")
            || combined.contains("schema has changed"))
        && !combined.contains("malformed")
        && !combined.contains("corrupt")
        && !combined.contains("constraint")
        && !combined.contains("unexpected token")
        && !combined.contains("panic")
}

fn has_integrity_failure_signal(result: &BrResult) -> bool {
    if contains_integrity_failure_signal(&result.stderr) {
        return true;
    }

    !result.success && contains_integrity_failure_signal(&result.stdout)
}

fn contains_integrity_failure_signal(output: &str) -> bool {
    let output = output.to_lowercase();
    output.contains("unique constraint failed: blocked_issues_cache.issue_id")
        || output.contains("constraint failed")
        || output.contains("constraint")
        || output.contains("corrupt")
        || output.contains("malformed")
        || output.contains("unexpected token")
        || output.contains("panic")
}

fn assert_no_integrity_failure_signals(role: &str, results: &[BrResult]) {
    let mut integrity_failures = Vec::new();

    for (index, result) in results.iter().enumerate() {
        if has_integrity_failure_signal(result) {
            integrity_failures.push(format!(
                "{role}[{index}] stdout={} stderr={}",
                result.stdout, result.stderr
            ));
        }
    }

    assert!(
        integrity_failures.is_empty(),
        "integrity failure signals detected in {role}: {}",
        integrity_failures.join(" | ")
    );
}

fn assert_only_success_or_contention(role: &str, results: &[BrResult]) -> usize {
    let mut success_count = 0;
    let mut unexpected_failures = Vec::new();

    for (index, result) in results.iter().enumerate() {
        if result.success {
            success_count += 1;
        } else if !is_expected_contention_failure(result) {
            unexpected_failures.push(format!(
                "{role}[{index}] stdout={} stderr={}",
                result.stdout, result.stderr
            ));
        }
    }

    assert!(
        unexpected_failures.is_empty(),
        "unexpected {role} failures: {}",
        unexpected_failures.join(" | ")
    );

    success_count
}

fn issue_title_count(root: &Path, title: &str) -> i64 {
    let db_path = root.join(".beads").join("beads.db");
    let conn = Connection::open(db_path.to_string_lossy().into_owned()).expect("open beads db");
    let rows = conn
        .query_with_params(
            "SELECT COUNT(*) FROM issues WHERE title = ?",
            &[SqliteValue::from(title)],
        )
        .expect("count issue title");

    rows.first()
        .and_then(|row| row.get(0))
        .and_then(SqliteValue::as_integer)
        .unwrap_or(0)
}

/// Extract JSON payload from stdout (skip non-JSON preamble).
fn extract_json_payload(stdout: &str) -> String {
    for (idx, line) in stdout.lines().enumerate() {
        let trimmed = line.trim_start();
        if trimmed.starts_with('[') || trimmed.starts_with('{') {
            return stdout
                .lines()
                .skip(idx)
                .collect::<Vec<_>>()
                .join("\n")
                .trim()
                .to_string();
        }
    }
    stdout.trim().to_string()
}

/// Parse issues list from `br list --json` stdout, handling both the legacy
/// plain-array format and the current paginated envelope format:
/// `{"issues": [...], "total": N, "limit": N, "offset": 0, "has_more": false}`.
fn extract_issues_array(stdout: &str) -> Vec<serde_json::Value> {
    let payload = extract_json_payload(stdout);
    // Try plain array first (legacy / future-proof).
    if let Ok(arr) = serde_json::from_str::<Vec<serde_json::Value>>(&payload) {
        return arr;
    }
    // Try paginated envelope.
    if let Ok(obj) = serde_json::from_str::<serde_json::Value>(&payload)
        && let Some(issues) = obj.get("issues").and_then(|v| v.as_array())
    {
        return issues.clone();
    }
    Vec::new()
}

/// Assert that `br doctor` reports the workspace as healthy.
///
/// If the initial check fails with only recoverable fsqlite-layer issues
/// (WAL-without-SHM, minor page accounting gaps after concurrent load), this
/// runs `doctor --repair` which checkpoints the WAL and reconciles page
/// accounting. `doctor --repair` exits non-zero only when post-repair
/// verification still fails, so a successful repair exit code means the
/// workspace is clean. Unrecoverable failures surface the original report.
fn assert_doctor_healthy(root: &PathBuf) {
    let doctor = run_br_in_dir(root, ["doctor", "--json"]);
    if doctor.success {
        return;
    }
    // Attempt auto-repair (checkpoint WAL, quarantine anomalous sidecars).
    let repair = run_br_in_dir(root, ["doctor", "--repair", "--json"]);
    assert!(
        repair.success,
        "doctor failed after contention and --repair could not recover it:\n\
         initial: stdout={} stderr={}\n\
         repair:  stdout={} stderr={}",
        doctor.stdout, doctor.stderr, repair.stdout, repair.stderr
    );
}

fn assert_doctor_has_no_page_anomalies(root: &PathBuf, label: &str) {
    let doctor = run_br_in_dir(root, ["doctor", "--json"]);
    assert!(
        doctor.success,
        "{label}: doctor failed: stdout={} stderr={}",
        doctor.stdout, doctor.stderr
    );

    let payload = extract_json_payload(&doctor.stdout);
    let report: serde_json::Value =
        serde_json::from_str(&payload).expect("doctor output should be valid json");
    let checks = report
        .get("checks")
        .and_then(serde_json::Value::as_array)
        .expect("doctor report should include checks array");

    let page_anomalies: Vec<String> = checks
        .iter()
        .filter_map(|check| {
            let name = check
                .get("name")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            if name != "sqlite.integrity_check" && name != "sqlite3.integrity_check" {
                return None;
            }

            let message = check
                .get("message")
                .and_then(serde_json::Value::as_str)
                .unwrap_or_default();
            let lower = message.to_ascii_lowercase();
            (lower.contains("never used")
                || lower.contains("free space corruption")
                || lower.contains("malformed")
                || lower.contains("disk image"))
            .then(|| format!("{name}: {message}"))
        })
        .collect();

    assert!(
        page_anomalies.is_empty(),
        "{label}: doctor reported page anomalies: {page_anomalies:?}\nstdout={}\nstderr={}",
        doctor.stdout,
        doctor.stderr
    );
}

fn assert_upstream_sqlite_integrity_ok(root: &Path, label: &str) {
    let db_path = root.join(".beads").join("beads.db");
    let output = StdCommand::new("sqlite3")
        .arg(&db_path)
        .arg("PRAGMA integrity_check;")
        .output();

    let output = match output {
        Ok(output) => output,
        Err(err) => {
            eprintln!("{label}: sqlite3 unavailable, skipping upstream integrity check: {err}");
            return;
        }
    };

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success() && stdout.trim() == "ok",
        "{label}: upstream sqlite3 integrity_check failed for {}: status={:?} stdout={stdout} stderr={stderr}",
        db_path.display(),
        output.status.code()
    );
}

fn create_routes_file(root: &Path, entries: &[(&str, &Path)]) {
    let routes_path = root.join(".beads").join("routes.jsonl");
    let content = entries
        .iter()
        .map(|(prefix, path)| {
            format!(
                r#"{{"prefix":"{prefix}","path":"{}"}}"#,
                path.to_string_lossy()
            )
        })
        .collect::<Vec<_>>()
        .join("\n");
    fs::write(routes_path, content).expect("write routes.jsonl");
}

fn configure_external_route(main_root: &Path, external_root: &Path) {
    fs::write(
        external_root.join(".beads").join("config.yaml"),
        "issue_prefix: ext\n",
    )
    .expect("write external config");
    create_routes_file(main_root, &[("ext-", external_root)]);
}

/// A writer process killed while waiting for `.write.lock` must not leave a
/// ghost mutation or poison the advisory lock for subsequent writers.
#[test]
#[allow(clippy::incompatible_msrv)]
fn e2e_killed_writer_waiting_on_write_lock_does_not_poison_workspace() {
    let _log =
        common::test_log("e2e_killed_writer_waiting_on_write_lock_does_not_poison_workspace");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let seed = run_br_in_dir(&root, ["create", "Seed before killed writer"]);
    assert!(seed.success, "seed create failed: {}", seed.stderr);

    let lock_path = root.join(".beads").join(".write.lock");
    let write_lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(lock_path)
        .expect("open .write.lock");
    write_lock.lock().expect("hold .write.lock");

    let mut blocked_writer = spawn_br_child_in_dir(
        &root,
        ["create", "Killed while waiting for write lock", "--json"],
    );
    wait_for_child_to_block_on_write_lock(&mut blocked_writer, "writer create");

    blocked_writer.kill().expect("kill blocked writer");
    let killed = blocked_writer
        .wait_with_output()
        .expect("collect killed writer");
    assert!(
        !killed.status.success(),
        "killed writer must not report success"
    );
    drop(write_lock);

    let after = run_br_in_dir(&root, ["create", "After killed writer", "--json"]);
    assert!(
        after.success,
        "post-kill writer failed: stdout={} stderr={}",
        after.stdout, after.stderr
    );

    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(
        list.success,
        "list after killed writer failed: {}",
        list.stderr
    );
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues
            .iter()
            .any(|issue| issue["title"].as_str() == Some("Seed before killed writer")),
        "seed issue should remain visible: {}",
        list.stdout
    );
    assert!(
        issues
            .iter()
            .any(|issue| issue["title"].as_str() == Some("After killed writer")),
        "post-kill issue should be visible: {}",
        list.stdout
    );
    assert!(
        issues.iter().all(|issue| {
            issue["title"].as_str() != Some("Killed while waiting for write lock")
        }),
        "killed waiter must not create a ghost issue: {}",
        list.stdout
    );

    assert_doctor_healthy(&root);
}

/// A broken `.write.lock` path must fail closed. Mutating commands must not
/// bypass cross-process serialization just because the advisory lock cannot be
/// opened.
#[test]
#[cfg(unix)]
fn e2e_mutating_command_fails_when_write_lock_path_unusable() {
    let _log = common::test_log("e2e_mutating_command_fails_when_write_lock_path_unusable");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let lock_path = root.join(".beads").join(".write.lock");
    fs::create_dir_all(&lock_path).expect("replace write lock path with directory");

    let create = run_br_in_dir(
        &root,
        ["create", "Should not bypass broken write lock", "--json"],
    );
    assert!(
        !create.success,
        "mutating command should fail when .write.lock is unusable; stdout={} stderr={}",
        create.stdout, create.stderr
    );
    let combined = format!("{}{}", create.stdout, create.stderr);
    assert!(
        (combined.contains("Refusing unsafe workspace write lock path")
            || combined.contains("Failed to open write lock"))
            && combined.contains(".write.lock"),
        "error should explain the unusable write lock path: {combined}"
    );

    assert_eq!(
        issue_title_count(&root, "Should not bypass broken write lock"),
        0,
        "failed lock acquisition must not create an issue"
    );
}

/// A held `.write.lock` must fail with the configured timeout instead of
/// parking the mutating command indefinitely.
#[test]
#[cfg(unix)]
#[allow(clippy::incompatible_msrv)]
fn e2e_write_lock_contention_respects_lock_timeout() {
    let _log = common::test_log("e2e_write_lock_contention_respects_lock_timeout");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let lock_path = root.join(".beads").join(".write.lock");
    let write_lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(lock_path)
        .expect("open .write.lock");
    write_lock.lock().expect("hold .write.lock");

    let start = Instant::now();
    let create = run_br_in_dir(
        &root,
        [
            "--lock-timeout",
            "75",
            "--json",
            "create",
            "Blocked by held write lock",
        ],
    );
    let elapsed = start.elapsed();

    assert!(
        !create.success,
        "mutating command should time out while write lock is held; stdout={} stderr={}",
        create.stdout, create.stderr
    );
    assert!(
        elapsed < Duration::from_secs(3),
        "write lock timeout should not block indefinitely; elapsed={elapsed:?}"
    );
    let combined = format!("{}{}", create.stdout, create.stderr);
    assert!(
        combined.contains("Timed out after 75ms")
            && combined.contains("write lock")
            && combined.contains(".write.lock"),
        "error should include bounded write-lock diagnostics: {combined}"
    );

    drop(write_lock);
    let after = run_br_in_dir(&root, ["create", "After write lock timeout", "--json"]);
    assert!(
        after.success,
        "workspace should accept writes after lock release: stdout={} stderr={}",
        after.stdout, after.stderr
    );
}

/// Flat doctor surfaces must classify a genuinely held advisory lock before
/// live inspection, without using inode age or recommending inode replacement.
#[test]
#[cfg(unix)]
#[allow(clippy::incompatible_msrv)]
#[allow(clippy::too_many_lines)]
fn e2e_doctor_reports_live_write_lock_without_mutating_workspace() {
    use std::os::unix::fs::MetadataExt;

    let _log = common::test_log("e2e_doctor_reports_live_write_lock_without_mutating_workspace");
    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);
    let seed = run_br_in_dir(&root, ["create", "Lock evidence seed", "--json"]);
    assert!(seed.success, "seed failed: {}", seed.stderr);

    let lock_path = root.join(".beads/.write.lock");
    let db_path = root.join(".beads/beads.db");
    let jsonl_path = root.join(".beads/issues.jsonl");
    let db_before = fs::read(&db_path).expect("read database before contention");
    let jsonl_before = fs::read(&jsonl_path).expect("read JSONL before contention");
    let inode_before = fs::metadata(&lock_path).expect("stat lock").ino();

    let write_lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
        .expect("open .write.lock");
    write_lock.lock().expect("hold .write.lock");

    for (args, robot_triage) in [
        (vec!["--lock-timeout", "0", "doctor", "--json"], false),
        (
            vec!["--lock-timeout", "0", "doctor", "--robot-triage"],
            true,
        ),
        (
            vec![
                "--lock-timeout",
                "0",
                "doctor",
                "--robot-triage",
                "--repair",
            ],
            true,
        ),
        (
            vec![
                "--lock-timeout",
                "0",
                "doctor",
                "--robot-triage",
                "--repair-indexes",
            ],
            true,
        ),
    ] {
        let doctor = run_br_in_dir(&root, args);
        assert!(
            !doctor.success,
            "doctor must not inspect through a live owner: stdout={} stderr={}",
            doctor.stdout, doctor.stderr
        );
        assert_eq!(
            doctor.exit_code,
            Some(5),
            "process status must agree with the typed payload: stdout={} stderr={}",
            doctor.stdout,
            doctor.stderr
        );
        let payload: serde_json::Value =
            serde_json::from_str(&doctor.stdout).expect("typed doctor startup JSON");
        assert_eq!(payload["exit_code"], 5, "{payload}");
        assert_eq!(payload["code"], "concurrency_lost", "{payload}");
        assert_eq!(payload["inspection_state"], "not_started", "{payload}");
        assert!(
            payload.get("workspace_health").is_none(),
            "uninspected workspace must not receive a health value: {payload}"
        );
        if robot_triage {
            assert_eq!(
                payload["schema_version"], "br.doctor.triage.v1",
                "{payload}"
            );
            for key in [
                "summary",
                "findings",
                "actions_planned",
                "recommended_command",
                "capabilities_url",
                "robot_docs_command",
                "quick_ref",
            ] {
                assert!(
                    payload.get(key).is_some(),
                    "robot triage contract is missing {key}: {payload}"
                );
            }
            assert_eq!(payload["quick_ref"]["healthy"], 0, "{payload}");
            assert_eq!(payload["quick_ref"]["warn"], 1, "{payload}");
            assert_eq!(payload["quick_ref"]["error"], 0, "{payload}");
            assert_eq!(
                payload["findings"][0]["id"], "fm-concurrency_primitives-orphaned-write-lock",
                "{payload}"
            );
            assert_eq!(payload["reason"], "live_owner", "{payload}");
        } else {
            assert_eq!(payload["checks"][0]["name"], "write_lock", "{payload}");
            assert_eq!(
                payload["checks"][0]["details"]["reason"], "live_owner",
                "{payload}"
            );
            assert_eq!(
                payload["checks"][0]["details"]["finding_id"],
                "fm-concurrency_primitives-orphaned-write-lock",
                "{payload}"
            );
            assert!(
                payload["checks"][0]["details"]["remediation"]
                    .as_str()
                    .is_some_and(|message| message.contains("do not move or delete")),
                "{payload}"
            );
        }
        assert_eq!(
            fs::metadata(&lock_path)
                .expect("stat lock after doctor")
                .ino(),
            inode_before,
            "doctor must not replace the lock inode"
        );
        assert_eq!(
            fs::read(&db_path).expect("read database after contention"),
            db_before,
            "doctor must not inspect or mutate the database after lock refusal"
        );
        assert_eq!(
            fs::read(&jsonl_path).expect("read JSONL after contention"),
            jsonl_before,
            "doctor must not mutate JSONL after lock refusal"
        );
    }

    drop(write_lock);
    let recovery = run_br_in_dir(&root, ["doctor", "--json"]);
    assert!(
        matches!(recovery.exit_code, Some(0 | 1)),
        "doctor should resume inspection after owner release without a hard failure: \
         exit={:?} stdout={} stderr={}",
        recovery.exit_code,
        recovery.stdout,
        recovery.stderr
    );
    let payload: serde_json::Value =
        serde_json::from_str(&recovery.stdout).expect("recovery doctor JSON");
    let lock_check = payload["checks"]
        .as_array()
        .and_then(|checks| checks.iter().find(|check| check["name"] == "write_lock"))
        .expect("write_lock check after recovery");
    assert_eq!(lock_check["status"], "ok", "{lock_check}");
    assert_eq!(
        lock_check["details"]["reason"], "persistent_advisory_inode",
        "{lock_check}"
    );
}

/// Auto-import runs before nominally read-only commands, but the import itself
/// mutates SQLite. It must therefore serialize through `.write.lock` just like
/// explicit write commands.
#[test]
#[cfg(unix)]
#[allow(clippy::incompatible_msrv)]
fn e2e_read_command_auto_import_waits_for_write_lock() {
    let _log = common::test_log("e2e_read_command_auto_import_waits_for_write_lock");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let seed = run_br_in_dir(&root, ["create", "Seed before auto-import"]);
    assert!(seed.success, "seed create failed: {}", seed.stderr);

    let flush = run_br_in_dir(&root, ["sync", "--flush-only"]);
    assert!(flush.success, "flush failed: {}", flush.stderr);

    let beads_dir = root.join(".beads");
    let jsonl_path = beads_dir.join("issues.jsonl");
    let jsonl = fs::read_to_string(&jsonl_path).expect("read issues jsonl");
    let mut issue: serde_json::Value = serde_json::from_str(jsonl.trim()).expect("parse issue");
    issue["title"] = serde_json::Value::String("Imported while waiting for write lock".to_string());
    issue["updated_at"] = serde_json::Value::String("2999-01-01T00:00:00Z".to_string());
    fs::write(
        &jsonl_path,
        format!(
            "{}\n",
            serde_json::to_string(&issue).expect("serialize modified issue")
        ),
    )
    .expect("write stale jsonl");

    let lock_path = beads_dir.join(".write.lock");
    let write_lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(lock_path)
        .expect("open .write.lock");
    write_lock.lock().expect("hold .write.lock");

    let mut blocked_list = spawn_br_child_in_dir(&root, ["list", "--json"]);
    wait_for_child_to_block_on_write_lock(&mut blocked_list, "auto-import list");

    blocked_list.kill().expect("kill blocked list");
    let killed = blocked_list
        .wait_with_output()
        .expect("collect killed list");
    assert!(
        !killed.status.success(),
        "killed auto-import waiter must not report success"
    );
    drop(write_lock);

    let list = run_br_in_dir(&root, ["list", "--json"]);
    assert!(
        list.success,
        "list after releasing write lock failed: {}",
        list.stderr
    );
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.iter().any(|issue| {
            issue["title"].as_str() == Some("Imported while waiting for write lock")
        }),
        "later list should import the preserved JSONL update: {}",
        list.stdout
    );
}

/// Refreshing a stale JSONL witness is a SQLite metadata write even when the
/// JSONL itself is not newer. Read commands must serialize that path too.
#[test]
#[cfg(unix)]
#[allow(clippy::incompatible_msrv)]
fn e2e_read_command_witness_refresh_waits_for_write_lock() {
    let _log = common::test_log("e2e_read_command_witness_refresh_waits_for_write_lock");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let seed = run_br_in_dir(&root, ["create", "Seed before witness refresh"]);
    assert!(seed.success, "seed create failed: {}", seed.stderr);

    let flush = run_br_in_dir(&root, ["sync", "--flush-only"]);
    assert!(flush.success, "flush failed: {}", flush.stderr);

    let beads_dir = root.join(".beads");
    let db_path = beads_dir.join("beads.db");
    let conn = Connection::open(db_path.to_string_lossy().into_owned()).expect("open beads db");
    conn.execute("DELETE FROM metadata WHERE key = 'jsonl_size'")
        .expect("delete jsonl_size witness");
    conn.execute("INSERT INTO metadata (key, value) VALUES ('jsonl_size', '0')")
        .expect("write stale jsonl_size witness");
    // beads_rust-mjmk: also corrupt jsonl_content_hash so the staleness probe
    // actually concludes the JSONL is newer. compute_jsonl_newer_impl falls
    // back to hash comparison when size mismatches; if the hash still matches
    // the actual JSONL, the probe returns "not newer" and the read command
    // never tries to refresh witnesses, making this test a no-op.
    conn.execute("DELETE FROM metadata WHERE key = 'jsonl_content_hash'")
        .expect("delete jsonl_content_hash witness");
    conn.execute(
        "INSERT INTO metadata (key, value) VALUES ('jsonl_content_hash', 'stale_witness_hash_mjmk')",
    )
    .expect("write stale jsonl_content_hash witness");
    drop(conn);

    let lock_path = beads_dir.join(".write.lock");
    let write_lock = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(lock_path)
        .expect("open .write.lock");
    write_lock.lock().expect("hold .write.lock");

    let mut blocked_search = spawn_br_child_in_dir(&root, ["search", "Seed", "--json"]);
    wait_for_child_to_block_on_write_lock(&mut blocked_search, "witness-refresh search");

    drop(write_lock);
    let completed = blocked_search
        .wait_with_output()
        .expect("collect search after lock release");
    assert!(
        completed.status.success(),
        "search after witness refresh failed: stdout={} stderr={}",
        String::from_utf8_lossy(&completed.stdout),
        String::from_utf8_lossy(&completed.stderr)
    );
}

/// Test that concurrent write operations respect `SQLite` locking.
///
/// This test:
/// 1. Starts two threads that attempt to create issues simultaneously
/// 2. Uses a barrier to synchronize the start of both operations
/// 3. Verifies that both eventually succeed (due to default busy timeout)
#[test]
fn e2e_concurrent_writes_succeed_with_retry() {
    let _log = common::test_log("e2e_concurrent_writes_succeed_with_retry");

    // Create workspace
    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize workspace
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    // Create a barrier to synchronize thread start
    let barrier = Arc::new(Barrier::new(2));
    let root1 = Arc::new(root.clone());
    let root2 = Arc::new(root.clone());

    let barrier1 = Arc::clone(&barrier);
    let barrier2 = Arc::clone(&barrier);
    let root1_clone = Arc::clone(&root1);
    let root2_clone = Arc::clone(&root2);

    // Spawn two threads that will try to create issues concurrently.
    // Use an explicit timeout here so the retry behavior is stable under
    // remote worker load instead of depending on the ambient default.
    let handle1 = thread::spawn(move || {
        barrier1.wait();
        run_br_in_dir(
            &root1_clone,
            ["--lock-timeout", "1000", "create", "Issue from thread 1"],
        )
    });

    let handle2 = thread::spawn(move || {
        barrier2.wait();
        run_br_in_dir(
            &root2_clone,
            ["--lock-timeout", "1000", "create", "Issue from thread 2"],
        )
    });

    let result1 = handle1.join().expect("thread 1 panicked");
    let result2 = handle2.join().expect("thread 2 panicked");

    let mut success_count = 0;
    let mut successful_titles = Vec::new();
    let mut unexpected_failures = Vec::new();
    for (index, result, title) in [
        (1, &result1, "Issue from thread 1"),
        (2, &result2, "Issue from thread 2"),
    ] {
        if result.success {
            success_count += 1;
            successful_titles.push(title);
        } else if !is_expected_contention_failure(result) {
            unexpected_failures.push(format!(
                "thread {index} stdout={} stderr={}",
                result.stdout, result.stderr
            ));
        }
    }
    assert!(
        unexpected_failures.is_empty(),
        "unexpected concurrent write failures: {}",
        unexpected_failures.join(" | ")
    );
    assert!(
        success_count > 0,
        "expected at least one concurrent writer to succeed"
    );

    // Verify successful issues were created. Use --no-auto-import to avoid
    // SYNC_CONFLICT when JSONL is newer than the DB after concurrent flushes.
    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(list.success, "list failed: {}", list.stderr);
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.len() >= success_count,
        "expected at least {success_count} concurrent issues, got {}",
        issues.len()
    );
    for title in successful_titles {
        assert!(list.stdout.contains(title), "missing issue title {title}");
    }

    // Keep temp_dir alive until end
    drop(temp_dir);
}

/// Test that --lock-timeout=1 causes quick failure on lock contention.
///
/// This test:
/// 1. Holds a write lock via rapid updates
/// 2. Attempts a second write with --lock-timeout=1
/// 3. Measures timing to verify timeout behavior
#[test]
fn e2e_lock_timeout_behavior() {
    let _log = common::test_log("e2e_lock_timeout_behavior");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize workspace
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    // Create an issue first
    let create = run_br_in_dir(&root, ["create", "Seed issue"]);
    assert!(create.success, "create seed failed: {}", create.stderr);
    let seed_id = parse_created_id(&create.stdout);

    // Use a synchronization primitive
    let barrier = Arc::new(Barrier::new(2));
    let root_shared = Arc::new(root);
    let seed_id_arc = Arc::new(seed_id);

    let barrier1 = Arc::clone(&barrier);
    let barrier2 = Arc::clone(&barrier);
    let root1_clone = Arc::clone(&root_shared);
    let root2_clone = Arc::clone(&root_shared);
    let seed_id_clone = Arc::clone(&seed_id_arc);

    // Thread 1: Do multiple rapid updates to keep the DB busy
    let handle1 = thread::spawn(move || {
        barrier1.wait();
        for i in 0..10 {
            let title = format!("Update {i}");
            run_br_in_dir(&root1_clone, ["update", &seed_id_clone, "--title", &title]);
            thread::sleep(Duration::from_millis(50));
        }
    });

    // Thread 2: Try to create with low timeout
    let handle2 = thread::spawn(move || {
        barrier2.wait();
        // Small delay to let the first thread start
        thread::sleep(Duration::from_millis(25));
        let start = Instant::now();
        let result = run_br_in_dir(
            &root2_clone,
            ["--lock-timeout", "1", "create", "Low timeout issue"],
        );
        let elapsed = start.elapsed();
        (result, elapsed)
    });

    handle1.join().expect("thread 1 panicked");
    let (result2, elapsed2) = handle2.join().expect("thread 2 panicked");

    // Log timing for diagnostics
    eprintln!(
        "Low timeout operation: success={}, elapsed={elapsed2:?}",
        result2.success
    );

    // Either outcome is valid depending on timing:
    // - Success if no contention was hit
    // - Failure with lock/busy error if contention occurred
    if !result2.success {
        let combined = format!("{} {}", result2.stderr, result2.stdout).to_lowercase();
        // Check for any database-related error (busy, lock, or general database error)
        assert!(
            combined.contains("busy")
                || combined.contains("lock")
                || combined.contains("database")
                || combined.contains("error"),
            "expected lock-related error, got: stdout={}, stderr={}",
            result2.stdout,
            result2.stderr
        );
    }

    drop(temp_dir);
}

/// Test that read-only operations succeed concurrently without blocking.
///
/// This test:
/// 1. Creates several issues
/// 2. Runs multiple concurrent read operations (list, show, stats)
/// 3. Verifies all complete successfully
#[test]
fn e2e_concurrent_reads_succeed() {
    let _log = common::test_log("e2e_concurrent_reads_succeed");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize and create some issues
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    let mut ids = Vec::new();
    for i in 0..5 {
        let create = run_br_in_dir(&root, ["create", &format!("Issue {i}")]);
        assert!(create.success, "create {i} failed: {}", create.stderr);
        ids.push(parse_created_id(&create.stdout));
    }

    // Spawn multiple threads doing read operations
    let barrier = Arc::new(Barrier::new(5));
    let mut handles = Vec::new();

    let root_arc = Arc::new(root);
    for (i, issue_id) in ids.iter().cloned().enumerate() {
        let root_clone = Arc::clone(&root_arc);
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            barrier_clone.wait();
            let start = Instant::now();

            // Mix of read operations
            let list = run_br_in_dir(&root_clone, ["list", "--json"]);
            let show = run_br_in_dir(&root_clone, ["show", &issue_id, "--json"]);
            let stats = run_br_in_dir(&root_clone, ["stats", "--json"]);

            let elapsed = start.elapsed();
            (i, list, show, stats, elapsed)
        });

        handles.push(handle);
    }

    // Collect results
    let results: Vec<_> = handles
        .into_iter()
        .map(|h| h.join().expect("thread panicked"))
        .collect();

    // All read operations should succeed
    for (i, list, show, stats, elapsed) in &results {
        assert!(list.success, "thread {i} list failed: {}", list.stderr);
        assert!(show.success, "thread {i} show failed: {}", show.stderr);
        assert!(stats.success, "thread {i} stats failed: {}", stats.stderr);
        eprintln!("Thread {i} completed reads in {elapsed:?}");
    }

    drop(temp_dir);
}

/// Test that parallel read-only commands serialize without teardown errors.
///
/// Read-only DB-family commands intentionally pass through `.write.lock` because
/// storage open/recovery can touch shared DB state before the command body runs.
/// This guards against the failure mode we actually care about: hidden
/// write-like teardown work surfacing as `database is busy` or corrupting the
/// workspace under concurrent read traffic.
#[test]
fn e2e_parallel_read_only_commands_serialize_without_busy_on_drop() {
    let _log = common::test_log("e2e_parallel_read_only_commands_serialize_without_busy_on_drop");

    let registry = DatasetRegistry::new();
    if !registry.is_available(KnownDataset::BeadsRust) {
        eprintln!("skipping: beads_rust dataset is unavailable in this environment");
        return;
    }

    let isolated =
        IsolatedDataset::from_dataset(KnownDataset::BeadsRust).expect("copy beads_rust dataset");
    isolated
        .migrate_to_current_schema()
        .expect("migrate isolated beads_rust dataset");
    let root = isolated.root.clone();

    let create = run_br_in_dir(
        &root,
        [
            "--no-auto-import",
            "--no-auto-flush",
            "create",
            "Concurrency seed issue",
        ],
    );
    assert!(create.success, "seed create failed: {}", create.stderr);
    let issue_id = parse_created_id(&create.stdout);

    let root_arc = Arc::new(root);
    let barrier = Arc::new(Barrier::new(6));
    let mut handles = Vec::new();

    for worker in 0..6 {
        let root_clone = Arc::clone(&root_arc);
        let barrier_clone = Arc::clone(&barrier);
        let issue_id_clone = issue_id.clone();

        handles.push(thread::spawn(move || {
            barrier_clone.wait();

            let mut failures = Vec::new();
            for iteration in 0..6 {
                let result = if worker % 2 == 0 {
                    run_br_in_dir(
                        &root_clone,
                        [
                            "--lock-timeout",
                            "1000",
                            "--no-auto-import",
                            "--no-auto-flush",
                            "ready",
                            "--json",
                        ],
                    )
                } else {
                    run_br_in_dir(
                        &root_clone,
                        [
                            "--lock-timeout",
                            "1000",
                            "--no-auto-import",
                            "--no-auto-flush",
                            "show",
                            &issue_id_clone,
                            "--json",
                        ],
                    )
                };

                if !result.success {
                    failures.push(format!(
                        "iteration={iteration} stdout={} stderr={}",
                        result.stdout, result.stderr
                    ));
                    break;
                }
            }

            (worker, failures)
        }));
    }

    for handle in handles {
        let (worker, failures) = handle.join().expect("thread panicked");
        assert!(
            failures.is_empty(),
            "worker {worker} hit read-only contention: {}",
            failures.join(" | ")
        );
    }

    drop(isolated);
}

/// Test that lock timeout is properly respected with specific timing.
///
/// This test:
/// 1. Sets a specific lock timeout
/// 2. Verifies the operation completes within expected time (no contention)
#[test]
fn e2e_lock_timeout_timing() {
    let _log = common::test_log("e2e_lock_timeout_timing");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize workspace
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    // Create a seed issue
    let create = run_br_in_dir(&root, ["create", "Seed"]);
    assert!(create.success, "create failed: {}", create.stderr);

    // Test with a 500ms timeout (should complete quickly without contention)
    let timeout_ms = 500;
    let start = Instant::now();
    let result = run_br_in_dir(
        &root,
        ["--lock-timeout", &timeout_ms.to_string(), "list", "--json"],
    );
    let elapsed = start.elapsed();

    // Without contention, should complete very quickly
    assert!(result.success, "list failed: {}", result.stderr);
    let timeout_ms_u64 = u64::try_from(timeout_ms).unwrap_or(0);
    assert!(
        elapsed < Duration::from_millis(timeout_ms_u64 + 500),
        "operation took too long without contention: {elapsed:?}"
    );

    eprintln!("Lock timeout timing test: elapsed={elapsed:?} (timeout={timeout_ms}ms)");

    drop(temp_dir);
}

/// Test that writes serialize properly and eventually complete.
///
/// This test verifies the proper serialization of write operations.
#[test]
fn e2e_write_serialization() {
    let _log = common::test_log("e2e_write_serialization");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    let start = Instant::now();
    let mut handles = Vec::new();
    let barrier = Arc::new(Barrier::new(3));

    // Spawn 3 threads doing writes
    for i in 0..3 {
        let root_clone = Arc::new(root.clone());
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            barrier_clone.wait();
            let thread_start = Instant::now();
            let result = run_br_in_dir(
                &root_clone,
                [
                    "--lock-timeout",
                    "1000",
                    "create",
                    &format!("Serialized issue {i}"),
                ],
            );
            let thread_elapsed = thread_start.elapsed();
            (i, result, thread_elapsed)
        });

        handles.push(handle);
    }

    let results: Vec<_> = handles
        .into_iter()
        .map(|h| h.join().expect("thread panicked"))
        .collect();
    let total_elapsed = start.elapsed();

    let mut success_count = 0;
    let mut successful_indices = Vec::new();
    let mut unexpected_failures = Vec::new();

    for (i, result, elapsed) in &results {
        if result.success {
            success_count += 1;
            successful_indices.push(*i);
            eprintln!("Thread {i} took {elapsed:?}");
        } else if !is_expected_contention_failure(result) {
            unexpected_failures.push(format!(
                "thread {i} stdout={} stderr={}",
                result.stdout, result.stderr
            ));
        }
    }

    assert!(
        unexpected_failures.is_empty(),
        "unexpected serialized writer failures: {}",
        unexpected_failures.join(" | ")
    );
    assert!(
        success_count > 0,
        "expected at least one serialized write to complete"
    );

    eprintln!("Total time for 3 serialized writes: {total_elapsed:?}");

    // Verify all successful writes persist. Use --no-auto-import to avoid
    // SYNC_CONFLICT when concurrent flushes leave JSONL ahead of DB.
    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(list.success, "final list failed: {}", list.stderr);
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.len() >= success_count,
        "expected at least {success_count} serialized issues, got {}",
        issues.len()
    );
    for i in successful_indices {
        assert!(
            list.stdout.contains(&format!("Serialized issue {i}")),
            "missing serialized issue {i}"
        );
    }

    drop(temp_dir);
}

/// Test mixed read-write concurrency.
///
/// This test:
/// 1. Has some threads doing writes
/// 2. Has other threads doing reads
/// 3. Verifies reads complete and writes eventually complete
#[test]
fn e2e_mixed_read_write_concurrency() {
    let _log = common::test_log("e2e_mixed_read_write_concurrency");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize with some existing data
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    for i in 0..3 {
        let create = run_br_in_dir(&root, ["create", &format!("Existing issue {i}")]);
        assert!(create.success, "create {i} failed");
    }

    let barrier = Arc::new(Barrier::new(6)); // 3 readers + 3 writers
    let mut handles = Vec::new();

    // Spawn readers
    for i in 0..3 {
        let root_clone = Arc::new(root.clone());
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            barrier_clone.wait();
            let start = Instant::now();
            // This reader deliberately opts out of both startup mutations, so
            // it exercises the current-schema read-only connection instead of
            // competing with writers for the workspace authority.
            let result = run_br_in_dir(
                &root_clone,
                [
                    "--no-auto-import",
                    "--no-auto-flush",
                    "--lock-timeout",
                    "500",
                    "list",
                    "--json",
                ],
            );
            let elapsed = start.elapsed();
            ("reader", i, result, elapsed)
        });
        handles.push(handle);
    }

    // Spawn writers
    for i in 0..3 {
        let root_clone = Arc::new(root.clone());
        let barrier_clone = Arc::clone(&barrier);

        let handle = thread::spawn(move || {
            barrier_clone.wait();
            let start = Instant::now();
            let result = run_br_in_dir(&root_clone, ["create", &format!("New issue {i}")]);
            let elapsed = start.elapsed();
            ("writer", i, result, elapsed)
        });
        handles.push(handle);
    }

    let results: Vec<_> = handles
        .into_iter()
        .map(|h| h.join().expect("thread panicked"))
        .collect();

    let mut reader_results = Vec::new();
    let mut writer_results = Vec::new();
    for (role, i, result, elapsed) in results {
        eprintln!("{role} {i} completed in {elapsed:?}");
        if role == "reader" {
            reader_results.push(result);
        } else {
            writer_results.push(result);
        }
    }

    let reader_successes = assert_only_success_or_contention("reader", &reader_results);
    let writer_successes = assert_only_success_or_contention("writer", &writer_results);

    assert_eq!(
        reader_successes,
        reader_results.len(),
        "read-only fast-open readers must all bypass mixed writer contention"
    );
    assert!(
        writer_successes > 0,
        "expected at least one successful writer under mixed contention"
    );

    // Verify final state. Use --no-auto-import to avoid SYNC_CONFLICT when
    // JSONL is newer than the DB after concurrent flushes.
    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(list.success, "final list failed: {}", list.stderr);

    // All successful writers should persist; explicit contention failures are acceptable.
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.len() >= 3 + writer_successes,
        "expected at least {} issues, got {}",
        3 + writer_successes,
        issues.len()
    );

    drop(temp_dir);
}

/// Test that mixed mutating command families either succeed or fail explicitly
/// under contention, while the workspace remains readable afterward.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_interleaved_command_families_remain_bounded() {
    let _log = common::test_log("e2e_interleaved_command_families_remain_bounded");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let create = run_br_in_dir(&root, ["create", "Interleaved seed issue"]);
    assert!(create.success, "create seed failed: {}", create.stderr);
    let seed_id = parse_created_id(&create.stdout);

    let barrier = Arc::new(Barrier::new(4));
    let root_arc = Arc::new(root.clone());
    let seed_id_arc = Arc::new(seed_id);

    let create_handle = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..4 {
                results.push(run_br_in_dir(
                    &root,
                    [
                        "--lock-timeout",
                        "1",
                        "create",
                        &format!("Interleaved issue {idx}"),
                    ],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let update_handle = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        let seed_id = Arc::clone(&seed_id_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..4 {
                let title = format!("Interleaved title {idx}");
                results.push(run_br_in_dir(
                    &root,
                    ["--lock-timeout", "1", "update", &seed_id, "--title", &title],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let label_handle = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        let seed_id = Arc::clone(&seed_id_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..4 {
                let label = format!("lane-{idx}");
                results.push(run_br_in_dir(
                    &root,
                    ["--lock-timeout", "1", "label", "add", &seed_id, &label],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let comments_handle = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        let seed_id = Arc::clone(&seed_id_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..4 {
                let body = format!("bounded comment {idx}");
                results.push(run_br_in_dir(
                    &root,
                    ["--lock-timeout", "1", "comments", "add", &seed_id, &body],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let worker_results = [
        (
            "create",
            create_handle.join().expect("create worker panicked"),
        ),
        (
            "update",
            update_handle.join().expect("update worker panicked"),
        ),
        ("label", label_handle.join().expect("label worker panicked")),
        (
            "comments",
            comments_handle.join().expect("comments worker panicked"),
        ),
    ];

    let total_successes: usize = worker_results
        .iter()
        .map(|(_, results)| results.iter().filter(|result| result.success).count())
        .sum();
    assert!(
        total_successes > 0,
        "expected at least one successful mutation across interleaved workers"
    );

    for (worker, results) in &worker_results {
        let _ = assert_only_success_or_contention(worker, results);
    }

    // Use --no-auto-import for post-contention reads to avoid SYNC_CONFLICT
    // when concurrent flushes leave JSONL ahead of the DB.
    let show = run_br_in_dir(&root, ["--no-auto-import", "show", &seed_id_arc, "--json"]);
    assert!(
        show.success,
        "show after contention failed: {}",
        show.stderr
    );

    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(
        list.success,
        "list after contention failed: {}",
        list.stderr
    );

    let stats = run_br_in_dir(&root, ["--no-auto-import", "stats", "--json"]);
    assert!(
        stats.success,
        "stats after contention failed: {}",
        stats.stderr
    );
}

/// Test that routed access to an external workspace remains available while the
/// invoking workspace is under local mutation.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_routed_external_mutation_succeeds_during_local_updates() {
    let _log = common::test_log("e2e_routed_external_mutation_succeeds_during_local_updates");

    let main_temp = isolated_temp_dir("main temp dir");
    let external_temp = isolated_temp_dir("external temp dir");
    let main_root = main_temp.path().to_path_buf();
    let external_root = external_temp.path().to_path_buf();

    let init_main = run_br_in_dir(&main_root, ["init"]);
    assert!(init_main.success, "init main failed: {}", init_main.stderr);
    let init_external = run_br_in_dir(&external_root, ["init"]);
    assert!(
        init_external.success,
        "init external failed: {}",
        init_external.stderr
    );

    configure_external_route(&main_root, &external_root);

    let create_local = run_br_in_dir(&main_root, ["create", "Local issue under mutation"]);
    assert!(
        create_local.success,
        "create local failed: {}",
        create_local.stderr
    );
    let local_id = parse_created_id(&create_local.stdout);

    let create_external = run_br_in_dir(&external_root, ["create", "External routed issue"]);
    assert!(
        create_external.success,
        "create external failed: {}",
        create_external.stderr
    );
    let external_id = parse_created_id(&create_external.stdout);
    assert!(
        external_id.starts_with("ext-"),
        "expected external prefix, got {external_id}"
    );

    let barrier = Arc::new(Barrier::new(2));
    let main_root_arc = Arc::new(main_root.clone());
    let local_id_arc = Arc::new(local_id);
    let external_id_arc = Arc::new(external_id);

    let local_updates = {
        let barrier = Arc::clone(&barrier);
        let main_root = Arc::clone(&main_root_arc);
        let local_id = Arc::clone(&local_id_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..8 {
                let title = format!("Local routed contention title {idx}");
                results.push(run_br_in_dir(
                    &main_root,
                    [
                        "--lock-timeout",
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS,
                        "update",
                        &local_id,
                        "--title",
                        &title,
                    ],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let routed_comments = {
        let barrier = Arc::clone(&barrier);
        let main_root = Arc::clone(&main_root_arc);
        let external_id = Arc::clone(&external_id_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..8 {
                let body = format!("routed external comment {idx}");
                results.push(run_br_in_dir(
                    &main_root,
                    [
                        "--lock-timeout",
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS,
                        "comments",
                        "add",
                        &external_id,
                        &body,
                        "--json",
                    ],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let local_update_results = local_updates.join().expect("local updates panicked");
    let routed_comment_results = routed_comments.join().expect("routed comments panicked");

    let local_update_successes =
        assert_only_success_or_contention("local_routed_updates", &local_update_results);
    assert!(
        local_update_successes > 0,
        "local mutation worker never succeeded"
    );

    let routed_comment_successes =
        assert_only_success_or_contention("routed_external_comments", &routed_comment_results);
    assert!(
        routed_comment_successes > 0,
        "expected at least one successful routed external comment"
    );

    let show_external = run_br_in_dir(&main_root, ["show", &external_id_arc, "--json"]);
    assert!(
        show_external.success,
        "routed show after contention failed: {}",
        show_external.stderr
    );
    let payload = extract_json_payload(&show_external.stdout);
    let issues: Vec<serde_json::Value> = serde_json::from_str(&payload).expect("parse show json");
    let comments = issues[0]["comments"].as_array().expect("comments array");
    assert!(
        comments.len() >= routed_comment_successes,
        "expected at least {} routed comments to persist, got {}",
        routed_comment_successes,
        comments.len()
    );

    let show_local = run_br_in_dir(&main_root, ["show", &local_id_arc, "--json"]);
    assert!(
        show_local.success,
        "local show after routed mutation failed: {}",
        show_local.stderr
    );
}

/// Test that background sync-status checks touching `.beads/` remain readable
/// while mutating commands are auto-flushing JSONL.
#[test]
fn e2e_sync_status_observer_stays_available_during_writes() {
    let _log = common::test_log("e2e_sync_status_observer_stays_available_during_writes");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let barrier = Arc::new(Barrier::new(2));
    let root_arc = Arc::new(root.clone());

    let writer = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..6 {
                results.push(run_br_in_dir(
                    &root,
                    ["create", &format!("background observer issue {idx}")],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let observer = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&root_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for _ in 0..6 {
                results.push(run_br_in_dir(
                    &root,
                    [
                        "--lock-timeout",
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS,
                        "sync",
                        "--status",
                        "--json",
                    ],
                ));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let writer_results = writer.join().expect("writer panicked");
    let observer_results = observer.join().expect("observer panicked");

    for (idx, result) in writer_results.iter().enumerate() {
        assert!(
            result.success,
            "writer iteration {idx} failed: {}",
            result.stderr
        );
    }

    let observer_successes = assert_only_success_or_contention("sync_status", &observer_results);
    assert!(
        observer_successes > 0,
        "expected at least one successful sync --status observation"
    );

    let list = run_br_in_dir(&root, ["list", "--json"]);
    assert!(list.success, "final list failed: {}", list.stderr);
    let issues = extract_issues_array(&list.stdout);
    assert_eq!(issues.len(), 6, "expected all writer issues to persist");
}

/// Test that database locked errors are properly reported.
///
/// This test verifies that when a lock cannot be acquired within the timeout,
/// an appropriate error message is returned.
#[test]
fn e2e_lock_error_reporting() {
    let _log = common::test_log("e2e_lock_error_reporting");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

    // Initialize
    let init = run_br_in_dir(&root, ["init"]);
    assert!(init.success, "init failed: {}", init.stderr);

    // Create a seed issue
    let create = run_br_in_dir(&root, ["create", "Lock test issue"]);
    assert!(create.success, "create failed: {}", create.stderr);

    // Normal operation should report no lock issues
    let list = run_br_in_dir(&root, ["list", "--json"]);
    assert!(list.success, "list failed: {}", list.stderr);
    assert!(
        !list.stderr.to_lowercase().contains("lock"),
        "unexpected lock message in normal operation"
    );

    drop(temp_dir);
}

#[test]
#[allow(clippy::too_many_lines)]
fn e2e_interleaved_command_families_preserve_workspace_integrity() {
    let _log = common::test_log("e2e_interleaved_command_families_preserve_workspace_integrity");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let seed = run_br_in_dir(&root, ["create", "Concurrency seed issue"]);
    assert!(seed.success, "seed create failed: {}", seed.stderr);
    let issue_id = parse_created_id(&seed.stdout);
    assert!(!issue_id.is_empty(), "missing seed issue id");

    let barrier = Arc::new(Barrier::new(4));
    let shared_root = Arc::new(root.clone());
    let shared_issue_id = Arc::new(issue_id.clone());

    let create_root = Arc::clone(&shared_root);
    let create_barrier = Arc::clone(&barrier);
    let creator = thread::spawn(move || {
        create_barrier.wait();
        let mut results = Vec::new();
        for i in 0..6 {
            let args = vec![
                "--lock-timeout".to_string(),
                CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                "create".to_string(),
                format!("Agent-created issue {i}"),
            ];
            results.push(run_br_in_dir(&create_root, args));
            thread::sleep(Duration::from_millis(10));
        }
        results
    });

    let comment_root = Arc::clone(&shared_root);
    let comment_issue_id = Arc::clone(&shared_issue_id);
    let comment_barrier = Arc::clone(&barrier);
    let commenter = thread::spawn(move || {
        comment_barrier.wait();
        let mut results = Vec::new();
        for i in 0..6 {
            // Use --no-auto-import to avoid SYNC_CONFLICT when concurrent creates
            // have updated the JSONL but left dirty flags in the DB. Comments add
            // does not need to sync from JSONL before appending a comment.
            let args = vec![
                "--no-auto-import".to_string(),
                "--lock-timeout".to_string(),
                CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                "comments".to_string(),
                "add".to_string(),
                comment_issue_id.as_ref().clone(),
                format!("agent-note-{i}"),
            ];
            results.push(run_br_in_dir(&comment_root, args));
            thread::sleep(Duration::from_millis(10));
        }
        results
    });

    let label_root = Arc::clone(&shared_root);
    let label_issue_id = Arc::clone(&shared_issue_id);
    let label_barrier = Arc::clone(&barrier);
    let labeler = thread::spawn(move || {
        label_barrier.wait();
        let mut results = Vec::new();
        for i in 0..6 {
            // Use --no-auto-import to avoid SYNC_CONFLICT during concurrent creates.
            let args = vec![
                "--no-auto-import".to_string(),
                "--lock-timeout".to_string(),
                CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                "label".to_string(),
                "add".to_string(),
                label_issue_id.as_ref().clone(),
                format!("contended-{i}"),
            ];
            results.push(run_br_in_dir(&label_root, args));
            thread::sleep(Duration::from_millis(10));
        }
        results
    });

    let reader_root = Arc::clone(&shared_root);
    let reader_issue_id = Arc::clone(&shared_issue_id);
    let reader_barrier = Arc::clone(&barrier);
    let reader = thread::spawn(move || {
        reader_barrier.wait();
        let mut results = Vec::new();
        for i in 0..12 {
            let args = match i % 3 {
                0 => vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "list".to_string(),
                    "--json".to_string(),
                ],
                1 => vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "show".to_string(),
                    reader_issue_id.as_ref().clone(),
                    "--json".to_string(),
                ],
                _ => vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "ready".to_string(),
                    "--json".to_string(),
                ],
            };
            results.push(run_br_in_dir(&reader_root, args));
            thread::sleep(Duration::from_millis(5));
        }
        results
    });

    let create_results = creator.join().expect("creator panicked");
    let comment_results = commenter.join().expect("commenter panicked");
    let label_results = labeler.join().expect("labeler panicked");
    let reader_results = reader.join().expect("reader panicked");

    let create_successes = assert_only_success_or_contention("create", &create_results);
    let comment_successes = assert_only_success_or_contention("comments", &comment_results);
    let label_successes = assert_only_success_or_contention("labels", &label_results);
    let reader_successes = assert_only_success_or_contention("reader", &reader_results);

    assert!(
        create_successes > 0,
        "expected at least one successful create"
    );
    assert!(
        comment_successes > 0,
        "expected at least one successful comment add"
    );
    assert!(
        label_successes > 0,
        "expected at least one successful label add"
    );
    assert!(
        reader_successes > 0,
        "expected at least one successful reader command"
    );

    assert_doctor_healthy(&root);

    // Use --no-auto-import to avoid SYNC_CONFLICT from concurrent flushes.
    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(
        list.success,
        "list failed after contention: {}",
        list.stderr
    );
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.len() > create_successes,
        "expected at least {} issues after concurrent creates, got {}",
        1 + create_successes,
        issues.len()
    );

    let comments = run_br_in_dir(
        &root,
        ["--no-auto-import", "comments", "list", &issue_id, "--json"],
    );
    assert!(
        comments.success,
        "comments list failed after contention: {}",
        comments.stderr
    );
    let comment_json: Vec<serde_json::Value> =
        serde_json::from_str(&extract_json_payload(&comments.stdout))
            .expect("parse comments list json");
    assert!(
        comment_json.len() >= comment_successes,
        "expected at least {} comments, got {}",
        comment_successes,
        comment_json.len()
    );

    let labels = run_br_in_dir(
        &root,
        ["--no-auto-import", "label", "list", &issue_id, "--json"],
    );
    assert!(
        labels.success,
        "label list failed after contention: {}",
        labels.stderr
    );
    let label_json: Vec<String> =
        serde_json::from_str(&extract_json_payload(&labels.stdout)).expect("parse label list");
    assert!(
        label_json.len() >= label_successes,
        "expected at least {} labels, got {}",
        label_successes,
        label_json.len()
    );

    let show = run_br_in_dir(&root, ["--no-auto-import", "show", &issue_id, "--json"]);
    assert!(
        show.success,
        "show failed after contention: {}",
        show.stderr
    );

    drop(temp_dir);
}

#[test]
#[allow(clippy::too_many_lines)]
fn e2e_external_access_and_background_status_are_bounded_during_mutation() {
    let _log =
        common::test_log("e2e_external_access_and_background_status_are_bounded_during_mutation");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let seed = run_br_in_dir(&root, ["create", "External access seed issue"]);
    assert!(seed.success, "seed create failed: {}", seed.stderr);
    let issue_id = parse_created_id(&seed.stdout);
    assert!(!issue_id.is_empty(), "missing seed issue id");

    let beads_dir = Arc::new(root.join(".beads").display().to_string());
    let external_temp_dir = isolated_temp_dir("external temp dir");
    let external_root = Arc::new(external_temp_dir.path().to_path_buf());

    let barrier = Arc::new(Barrier::new(3));
    let shared_root = Arc::new(root.clone());
    let shared_issue_id = Arc::new(issue_id);

    let writer_root = Arc::clone(&shared_root);
    let writer_barrier = Arc::clone(&barrier);
    let local_writer = thread::spawn(move || {
        writer_barrier.wait();
        let mut results = Vec::new();
        for i in 0..8 {
            let args = vec![
                "--lock-timeout".to_string(),
                CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                "create".to_string(),
                format!("local-mutation-{i}"),
            ];
            results.push(run_br_in_dir(&writer_root, args));
            thread::sleep(Duration::from_millis(8));
        }
        results
    });

    let read_root = Arc::clone(&external_root);
    let read_beads_dir = Arc::clone(&beads_dir);
    let read_issue_id = Arc::clone(&shared_issue_id);
    let read_barrier = Arc::clone(&barrier);
    let external_reader = thread::spawn(move || {
        read_barrier.wait();
        let mut results = Vec::new();
        for i in 0..10 {
            let args = if i % 2 == 0 {
                vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "list".to_string(),
                    "--json".to_string(),
                ]
            } else {
                vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "show".to_string(),
                    read_issue_id.as_ref().clone(),
                    "--json".to_string(),
                ]
            };
            results.push(run_br_in_dir_with_env(
                &read_root,
                args,
                [("BEADS_DIR", read_beads_dir.as_str())],
            ));
            thread::sleep(Duration::from_millis(6));
        }
        results
    });

    let status_root = Arc::clone(&external_root);
    let status_beads_dir = Arc::clone(&beads_dir);
    let status_barrier = Arc::clone(&barrier);
    let background_status = thread::spawn(move || {
        status_barrier.wait();
        let mut results = Vec::new();
        for _ in 0..10 {
            let args = vec![
                "--lock-timeout".to_string(),
                CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                "sync".to_string(),
                "--status".to_string(),
                "--json".to_string(),
            ];
            results.push(run_br_in_dir_with_env(
                &status_root,
                args,
                [("BEADS_DIR", status_beads_dir.as_str())],
            ));
            thread::sleep(Duration::from_millis(6));
        }
        results
    });

    let writer_results = local_writer.join().expect("local writer panicked");
    let reader_results = external_reader.join().expect("external reader panicked");
    let status_results = background_status
        .join()
        .expect("background status panicked");

    let writer_successes = assert_only_success_or_contention("writer", &writer_results);
    let reader_successes = assert_only_success_or_contention("external_reader", &reader_results);
    let status_successes = assert_only_success_or_contention("background_status", &status_results);

    assert!(
        writer_successes > 0,
        "expected at least one successful local write"
    );
    assert!(
        reader_successes > 0,
        "expected at least one successful external BEADS_DIR access"
    );
    assert!(
        status_successes > 0,
        "expected at least one successful background status command"
    );

    assert_doctor_healthy(&root);

    let status = run_br_in_dir(&root, ["sync", "--status", "--json"]);
    assert!(
        status.success,
        "sync --status failed after contention: stdout={} stderr={}",
        status.stdout, status.stderr
    );

    // Use --no-auto-import to avoid SYNC_CONFLICT from concurrent flushes.
    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(
        list.success,
        "list failed after contention: {}",
        list.stderr
    );
    let issues = extract_issues_array(&list.stdout);
    assert!(
        issues.len() > writer_successes,
        "expected at least {} issues after local mutation, got {}",
        1 + writer_successes,
        issues.len()
    );

    drop(external_temp_dir);
    drop(temp_dir);
}

/// Test that actor-aware command families like claim and defer can interleave
/// with other mutating commands while leaving the workspace readable.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_actor_oriented_command_families_preserve_workspace_integrity() {
    let _log = common::test_log("e2e_actor_oriented_command_families_preserve_workspace_integrity");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let claim_issue = run_br_in_dir(&root, ["create", "Claim target"]);
    assert!(claim_issue.success, "create claim target failed");
    let claim_id = parse_created_id(&claim_issue.stdout);

    let defer_issue = run_br_in_dir(&root, ["create", "Deferred target"]);
    assert!(defer_issue.success, "create defer target failed");
    let defer_id = parse_created_id(&defer_issue.stdout);

    let comment_issue = run_br_in_dir(&root, ["create", "Comment target"]);
    assert!(comment_issue.success, "create comment target failed");
    let comment_id = parse_created_id(&comment_issue.stdout);

    let label_issue = run_br_in_dir(&root, ["create", "Label target"]);
    assert!(label_issue.success, "create label target failed");
    let label_id = parse_created_id(&label_issue.stdout);

    let barrier = Arc::new(Barrier::new(5));
    let shared_root = Arc::new(root.clone());

    let claimer = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let claim_id = claim_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for _ in 0..8 {
                // Use --no-auto-import to avoid SYNC_CONFLICT when other concurrent
                // threads update the JSONL but leave dirty flags in the DB.
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "--actor".to_string(),
                    "alice".to_string(),
                    "update".to_string(),
                    claim_id.clone(),
                    "--claim".to_string(),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let deferrer = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let defer_id = defer_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for _ in 0..8 {
                // Use --no-auto-import to avoid SYNC_CONFLICT during concurrent writes.
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "--actor".to_string(),
                    "dave".to_string(),
                    "defer".to_string(),
                    defer_id.clone(),
                    "--until".to_string(),
                    "2026-12-01T00:00:00Z".to_string(),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let commenter = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let comment_id = comment_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..8 {
                // Use --no-auto-import to avoid SYNC_CONFLICT when concurrent
                // claimer/deferrer threads update the JSONL but leave dirty flags
                // in the DB. Comment add does not need to sync from JSONL first.
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "--actor".to_string(),
                    "carol".to_string(),
                    "comments".to_string(),
                    "add".to_string(),
                    comment_id.clone(),
                    format!("actor-note-{i}"),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let labeler = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let label_id = label_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..8 {
                // Use --no-auto-import to avoid SYNC_CONFLICT during concurrent writes.
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "--actor".to_string(),
                    "bob".to_string(),
                    "label".to_string(),
                    "add".to_string(),
                    label_id.clone(),
                    format!("actor-lane-{i}"),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let reader = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let claim_id = claim_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..12 {
                let args = match i % 3 {
                    0 => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "show".to_string(),
                        claim_id.clone(),
                        "--json".to_string(),
                    ],
                    1 => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "ready".to_string(),
                        "--json".to_string(),
                    ],
                    _ => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "stats".to_string(),
                        "--json".to_string(),
                    ],
                };
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let claim_results = claimer.join().expect("claimer panicked");
    let defer_results = deferrer.join().expect("deferrer panicked");
    let comment_results = commenter.join().expect("commenter panicked");
    let label_results = labeler.join().expect("labeler panicked");
    let reader_results = reader.join().expect("reader panicked");

    let claim_successes = assert_only_success_or_contention("claim", &claim_results);
    let defer_successes = assert_only_success_or_contention("defer", &defer_results);
    let comment_successes = assert_only_success_or_contention("comments", &comment_results);
    let label_successes = assert_only_success_or_contention("labels", &label_results);
    let reader_successes = assert_only_success_or_contention("reader", &reader_results);

    assert!(
        claim_successes > 0,
        "expected at least one successful claim"
    );
    assert!(
        defer_successes > 0,
        "expected at least one successful defer"
    );
    assert!(
        comment_successes > 0,
        "expected at least one successful comment add"
    );
    assert!(
        label_successes > 0,
        "expected at least one successful label add"
    );
    assert!(
        reader_successes > 0,
        "expected at least one successful reader command"
    );

    assert_doctor_healthy(&root);

    let claim_show = run_br_in_dir(&root, ["--no-auto-import", "show", &claim_id, "--json"]);
    assert!(
        claim_show.success,
        "show claim target failed: {}",
        claim_show.stderr
    );
    let claim_json: Vec<serde_json::Value> =
        serde_json::from_str(&extract_json_payload(&claim_show.stdout)).expect("claim show json");
    assert_eq!(claim_json[0]["status"].as_str(), Some("in_progress"));
    assert_eq!(claim_json[0]["assignee"].as_str(), Some("alice"));

    // Use --no-auto-import for post-contention reads to avoid SYNC_CONFLICT.
    let defer_show = run_br_in_dir(&root, ["--no-auto-import", "show", &defer_id, "--json"]);
    assert!(
        defer_show.success,
        "show defer target failed: {}",
        defer_show.stderr
    );
    let defer_json: Vec<serde_json::Value> =
        serde_json::from_str(&extract_json_payload(&defer_show.stdout)).expect("defer show json");
    assert_eq!(defer_json[0]["status"].as_str(), Some("deferred"));
    let defer_until = defer_json[0]["defer_until"]
        .as_str()
        .expect("defer_until should be present");
    assert!(
        defer_until.starts_with("2026-12-01"),
        "unexpected defer_until value: {defer_until}"
    );

    let comments = run_br_in_dir(
        &root,
        [
            "--no-auto-import",
            "comments",
            "list",
            &comment_id,
            "--json",
        ],
    );
    assert!(
        comments.success,
        "comments list failed after actor contention: {}",
        comments.stderr
    );
    let comment_json: Vec<serde_json::Value> =
        serde_json::from_str(&extract_json_payload(&comments.stdout))
            .expect("parse comments list json");
    assert!(
        comment_json.len() >= comment_successes,
        "expected at least {} comments, got {}",
        comment_successes,
        comment_json.len()
    );
    assert!(
        comment_json
            .iter()
            .all(|comment| comment["author"].as_str() == Some("carol")),
        "expected all comment authors to be carol: {}",
        comments.stdout
    );

    let labels = run_br_in_dir(
        &root,
        ["--no-auto-import", "label", "list", &label_id, "--json"],
    );
    assert!(
        labels.success,
        "label list failed after actor contention: {}",
        labels.stderr
    );
    let label_json: Vec<String> =
        serde_json::from_str(&extract_json_payload(&labels.stdout)).expect("parse label list");
    assert!(
        label_json.len() >= label_successes,
        "expected at least {} labels, got {}",
        label_successes,
        label_json.len()
    );

    let list = run_br_in_dir(&root, ["--no-auto-import", "list", "--json"]);
    assert!(
        list.success,
        "list failed after actor contention: {}",
        list.stderr
    );
}

/// Regression for direct close/update cache-refresh integrity under contention.
///
/// The failure mode we are guarding is not ordinary lock contention; that is
/// already allowed by the test harness. What must never reappear is a
/// blocked-cache UNIQUE constraint or other corruption signal while close-style
/// status mutations interleave with update/reopen traffic.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_close_update_reopen_preserve_blocked_cache_integrity() {
    let _log = common::test_log("e2e_close_update_reopen_preserve_blocked_cache_integrity");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let mut close_ids = Vec::new();
    for idx in 0..6 {
        let created = run_br_in_dir(&root, ["create", &format!("Close target {idx}")]);
        assert!(created.success, "create close target {idx} failed");
        close_ids.push(parse_created_id(&created.stdout));
    }

    let mut reopen_ids = Vec::new();
    for idx in 0..3 {
        let created = run_br_in_dir(&root, ["create", &format!("Reopen target {idx}")]);
        assert!(created.success, "create reopen target {idx} failed");
        let issue_id = parse_created_id(&created.stdout);
        let closed = run_br_in_dir(&root, ["close", &issue_id, "--reason", "seed closed"]);
        assert!(closed.success, "seed close {idx} failed: {}", closed.stderr);
        reopen_ids.push(issue_id);
    }

    let update_issue = run_br_in_dir(&root, ["create", "Update target"]);
    assert!(update_issue.success, "create update target failed");
    let update_id = parse_created_id(&update_issue.stdout);

    let barrier = Arc::new(Barrier::new(4));
    let shared_root = Arc::new(root.clone());

    let closer = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let close_ids = close_ids.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for issue_id in close_ids {
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "close".to_string(),
                    issue_id,
                    "--reason".to_string(),
                    "cache regression stress".to_string(),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let updater = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let update_id = update_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..10 {
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "update".to_string(),
                    update_id.clone(),
                    "--title".to_string(),
                    format!("Update target {idx}"),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let reopener = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let reopen_ids = reopen_ids.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..9 {
                let issue_id = reopen_ids[idx % reopen_ids.len()].clone();
                let args = vec![
                    "--no-auto-import".to_string(),
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "reopen".to_string(),
                    issue_id,
                    "--reason".to_string(),
                    format!("reopen round {idx}"),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(10));
            }
            results
        })
    };

    let reader = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let update_id = update_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..12 {
                let args = match idx % 3 {
                    0 => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "show".to_string(),
                        update_id.clone(),
                        "--json".to_string(),
                    ],
                    1 => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "ready".to_string(),
                        "--json".to_string(),
                    ],
                    _ => vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "stats".to_string(),
                        "--json".to_string(),
                    ],
                };
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let close_results = closer.join().expect("closer panicked");
    let update_results = updater.join().expect("updater panicked");
    let reopen_results = reopener.join().expect("reopener panicked");
    let reader_results = reader.join().expect("reader panicked");

    assert_no_integrity_failure_signals("close", &close_results);
    assert_no_integrity_failure_signals("update", &update_results);
    assert_no_integrity_failure_signals("reopen", &reopen_results);
    assert_no_integrity_failure_signals("reader", &reader_results);

    let close_successes = assert_only_success_or_contention("close", &close_results);
    let update_successes = assert_only_success_or_contention("update", &update_results);
    let reopen_successes = assert_only_success_or_contention("reopen", &reopen_results);
    let reader_successes = assert_only_success_or_contention("reader", &reader_results);

    assert!(
        close_successes > 0,
        "expected at least one successful close under contention"
    );
    assert!(
        update_successes > 0,
        "expected at least one successful update under contention"
    );
    assert!(
        reopen_successes > 0,
        "expected at least one successful reopen under contention"
    );
    assert!(
        reader_successes > 0,
        "expected at least one successful reader command"
    );

    assert_doctor_healthy(&root);

    let update_show = run_br_in_dir(&root, ["--no-auto-import", "show", &update_id, "--json"]);
    assert!(
        update_show.success,
        "show update target failed: {}",
        update_show.stderr
    );

    for issue_id in close_ids.iter().take(2) {
        let show = run_br_in_dir(&root, ["--no-auto-import", "show", issue_id, "--json"]);
        assert!(show.success, "show close target failed: {}", show.stderr);
    }

    for issue_id in &reopen_ids {
        let show = run_br_in_dir(&root, ["--no-auto-import", "show", issue_id, "--json"]);
        assert!(show.success, "show reopen target failed: {}", show.stderr);
    }
}

/// Regression for the ts2 report: mixed DB-backed commands in parallel must
/// serialize cleanly and leave no upstream `sqlite3` page-integrity residue.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_parallel_mixed_db_commands_preserve_sqlite_integrity() {
    let _log = common::test_log("e2e_parallel_mixed_db_commands_preserve_sqlite_integrity");

    let temp_dir = isolated_temp_dir("temp dir");
    let root = temp_dir.path().to_path_buf();

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

    let mut issue_ids = Vec::new();
    for idx in 0..14 {
        let created = run_br_in_dir(&root, ["create", &format!("ts2 mixed issue {idx}")]);
        assert!(
            created.success,
            "seed create {idx} failed: stdout={} stderr={}",
            created.stdout, created.stderr
        );
        issue_ids.push(parse_created_id(&created.stdout));
    }

    let barrier = Arc::new(Barrier::new(4));
    let shared_root = Arc::new(root.clone());

    let updater = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let issue_ids = issue_ids.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for (idx, issue_id) in issue_ids.iter().take(10).enumerate() {
                let args = vec![
                    "--lock-timeout".to_string(),
                    "15000".to_string(),
                    "update".to_string(),
                    issue_id.clone(),
                    "--title".to_string(),
                    format!("ts2 mixed updated {idx}"),
                    "--priority".to_string(),
                    (idx % 5).to_string(),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let depper = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let issue_ids = issue_ids.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 1..issue_ids.len() {
                let args = vec![
                    "--lock-timeout".to_string(),
                    "15000".to_string(),
                    "dep".to_string(),
                    "add".to_string(),
                    issue_ids[idx].clone(),
                    issue_ids[idx - 1].clone(),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let creator = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..8 {
                let args = vec![
                    "--lock-timeout".to_string(),
                    "15000".to_string(),
                    "create".to_string(),
                    format!("ts2 mixed concurrent create {idx}"),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let reader = {
        let barrier = Arc::clone(&barrier);
        let root = Arc::clone(&shared_root);
        let issue_ids = issue_ids.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for idx in 0..12 {
                let args = match idx % 4 {
                    0 => vec![
                        "--lock-timeout".to_string(),
                        "15000".to_string(),
                        "show".to_string(),
                        issue_ids[idx % issue_ids.len()].clone(),
                        "--json".to_string(),
                    ],
                    1 => vec![
                        "--lock-timeout".to_string(),
                        "15000".to_string(),
                        "status".to_string(),
                        "--no-activity".to_string(),
                        "--json".to_string(),
                    ],
                    2 => vec![
                        "--lock-timeout".to_string(),
                        "15000".to_string(),
                        "ready".to_string(),
                        "--json".to_string(),
                    ],
                    _ => vec![
                        "--lock-timeout".to_string(),
                        "15000".to_string(),
                        "doctor".to_string(),
                        "--json".to_string(),
                    ],
                };
                results.push(run_br_in_dir(&root, args));
                thread::sleep(Duration::from_millis(5));
            }
            results
        })
    };

    let update_results = updater.join().expect("updater panicked");
    let dep_results = depper.join().expect("depper panicked");
    let create_results = creator.join().expect("creator panicked");
    let read_results = reader.join().expect("reader panicked");

    for (role, results) in [
        ("update", &update_results),
        ("dep add", &dep_results),
        ("create", &create_results),
        ("read/status/doctor", &read_results),
    ] {
        assert_no_integrity_failure_signals(role, results);
        let successes = assert_only_success_or_contention(role, results);
        assert!(successes > 0, "{role} had no successful operations");
    }

    assert_doctor_has_no_page_anomalies(&root, "after mixed parallel DB load");
    assert_upstream_sqlite_integrity_ok(&root, "after mixed parallel DB load");

    for round in 0..4 {
        let status = run_br_in_dir(&root, ["status", "--no-activity", "--json"]);
        assert!(
            status.success,
            "post-load status round {round} failed: stdout={} stderr={}",
            status.stdout, status.stderr
        );

        let doctor = run_br_in_dir(&root, ["doctor", "--json"]);
        assert!(
            doctor.success,
            "post-load doctor round {round} failed: stdout={} stderr={}",
            doctor.stdout, doctor.stderr
        );
    }

    assert_doctor_has_no_page_anomalies(&root, "after repeated status/doctor reads");
    assert_upstream_sqlite_integrity_ok(&root, "after repeated status/doctor reads");
}

/// Test that routed access remains bounded even while the routed workspace
/// itself is mutating, not just the invoking workspace.
#[test]
#[allow(clippy::too_many_lines)]
fn e2e_routed_access_remains_bounded_while_remote_workspace_mutates() {
    let _log = common::test_log("e2e_routed_access_remains_bounded_while_remote_workspace_mutates");

    let main_temp_dir = isolated_temp_dir("main temp dir");
    let external_temp_dir = isolated_temp_dir("external temp dir");
    let main_root = main_temp_dir.path().to_path_buf();
    let external_root = external_temp_dir.path().to_path_buf();

    let init_main = run_br_in_dir(&main_root, ["init"]);
    assert!(init_main.success, "main init failed: {}", init_main.stderr);
    let init_external = run_br_in_dir(&external_root, ["init"]);
    assert!(
        init_external.success,
        "external init failed: {}",
        init_external.stderr
    );

    configure_external_route(&main_root, &external_root);

    let local_issue = run_br_in_dir(&main_root, ["create", "Local routed contention target"]);
    assert!(local_issue.success, "create local issue failed");
    let local_id = parse_created_id(&local_issue.stdout);

    let external_issue = run_br_in_dir(
        &external_root,
        ["create", "External routed contention target"],
    );
    assert!(external_issue.success, "create external issue failed");
    let external_id = parse_created_id(&external_issue.stdout);

    let barrier = Arc::new(Barrier::new(3));
    let main_root_arc = Arc::new(main_root.clone());
    let external_root_arc = Arc::new(external_root.clone());

    let local_writer = {
        let barrier = Arc::clone(&barrier);
        let main_root = Arc::clone(&main_root_arc);
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..8 {
                let args = vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "create".to_string(),
                    format!("local-route-write-{i}"),
                ];
                results.push(run_br_in_dir(&main_root, args));
                thread::sleep(Duration::from_millis(8));
            }
            results
        })
    };

    let external_writer = {
        let barrier = Arc::clone(&barrier);
        let external_root = Arc::clone(&external_root_arc);
        let external_id = external_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..8 {
                let args = vec![
                    "--lock-timeout".to_string(),
                    CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                    "--actor".to_string(),
                    "bob".to_string(),
                    "update".to_string(),
                    external_id.clone(),
                    "--title".to_string(),
                    format!("remote-mutation-{i}"),
                    "--json".to_string(),
                ];
                results.push(run_br_in_dir(&external_root, args));
                thread::sleep(Duration::from_millis(8));
            }
            results
        })
    };

    let routed_worker = {
        let barrier = Arc::clone(&barrier);
        let main_root = Arc::clone(&main_root_arc);
        let external_id = external_id.clone();
        thread::spawn(move || {
            barrier.wait();
            let mut results = Vec::new();
            for i in 0..10 {
                let args = if i % 2 == 0 {
                    vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "show".to_string(),
                        external_id.clone(),
                        "--json".to_string(),
                    ]
                } else {
                    vec![
                        "--lock-timeout".to_string(),
                        CONTENTION_SUCCESS_LOCK_TIMEOUT_MS.to_string(),
                        "--actor".to_string(),
                        "carol".to_string(),
                        "label".to_string(),
                        "add".to_string(),
                        external_id.clone(),
                        "remote-route".to_string(),
                    ]
                };
                results.push(run_br_in_dir(&main_root, args));
                thread::sleep(Duration::from_millis(6));
            }
            results
        })
    };

    let local_results = local_writer.join().expect("local writer panicked");
    let external_results = external_writer.join().expect("external writer panicked");
    let routed_results = routed_worker.join().expect("routed worker panicked");

    let local_successes = assert_only_success_or_contention("local_writer", &local_results);
    let external_successes =
        assert_only_success_or_contention("external_writer", &external_results);
    assert_only_success_or_contention("routed_worker", &routed_results);
    let routed_label_successes = routed_results
        .iter()
        .enumerate()
        .filter(|(idx, result)| *idx % 2 == 1 && result.success)
        .count();

    assert!(
        local_successes > 0,
        "expected at least one successful local write"
    );
    assert!(
        external_successes > 0,
        "expected at least one successful remote mutation"
    );
    assert_doctor_healthy(&main_root);

    // Use --no-auto-import for post-contention reads to avoid SYNC_CONFLICT.
    let routed_show = run_br_in_dir(
        &main_root,
        ["--no-auto-import", "show", &external_id, "--json"],
    );
    assert!(
        routed_show.success,
        "show routed issue failed: {}",
        routed_show.stderr
    );
    let routed_json: Vec<serde_json::Value> =
        serde_json::from_str(&extract_json_payload(&routed_show.stdout))
            .expect("parse routed show json");
    let routed_title = routed_json[0]["title"]
        .as_str()
        .expect("routed title should be present");
    assert!(
        routed_title.starts_with("remote-mutation-"),
        "expected remote title mutation, got: {routed_title}"
    );

    let external_labels = run_br_in_dir(
        &external_root,
        ["--no-auto-import", "label", "list", &external_id, "--json"],
    );
    assert!(
        external_labels.success,
        "label list on external workspace failed: {}",
        external_labels.stderr
    );
    if routed_label_successes > 0 {
        let label_json: Vec<String> =
            serde_json::from_str(&extract_json_payload(&external_labels.stdout))
                .expect("parse external label list");
        assert!(
            label_json.iter().any(|label| label == "remote-route"),
            "expected remote-route label in external workspace: {}",
            external_labels.stdout
        );
    }

    let local_show = run_br_in_dir(
        &main_root,
        ["--no-auto-import", "show", &local_id, "--json"],
    );
    assert!(
        local_show.success,
        "show local issue failed after routed contention: {}",
        local_show.stderr
    );

    let main_status = run_br_in_dir(&main_root, ["sync", "--status", "--json"]);
    assert!(
        main_status.success,
        "sync --status failed after routed contention: stdout={} stderr={}",
        main_status.stdout, main_status.stderr
    );
}