crosslink 0.8.0

A synced issue tracker CLI for multi-agent AI development
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
use crate::issue_file::{
    read_counters, read_issue_file, write_counters, write_issue_file, IssueFile,
};
use crate::models::{IssueStatus, Priority};
use crate::shared_writer::core::{
    PushOutcome, SharedWriter, LOCK_CONFIRM_TIMEOUT_SECS, MAX_RETRIES,
};
use crate::shared_writer::locks::LockClaimResult;
use crate::shared_writer::mutations::DescriptionUpdate;
use crate::shared_writer::offline::{replace_local_refs, RewriteStats};
use anyhow::{bail, Result};
use chrono::Utc;
use std::path::Path;
use tempfile::tempdir;
use uuid::Uuid;

fn make_issue(display_id: i64, title: &str) -> IssueFile {
    IssueFile {
        uuid: Uuid::new_v4(),
        display_id: Some(display_id),
        title: title.to_string(),
        description: None,
        status: IssueStatus::Open,
        priority: Priority::Medium,
        parent_uuid: None,
        created_by: "test-agent".to_string(),
        created_at: Utc::now(),
        updated_at: Utc::now(),
        closed_at: None,
        labels: vec![],
        comments: vec![],
        blockers: vec![],
        related: vec![],
        milestone_uuid: None,
        time_entries: vec![],
    }
}

#[test]
fn test_new_returns_none_without_agent_config() {
    let dir = tempdir().unwrap();
    let crosslink_dir = dir.path().join(".crosslink");
    std::fs::create_dir_all(&crosslink_dir).unwrap();

    let writer = SharedWriter::new(&crosslink_dir).unwrap();
    assert!(writer.is_none());
}

#[test]
fn test_claim_display_id() {
    // Test the counter logic directly using file I/O
    let dir = tempdir().unwrap();
    let meta_dir = dir.path().join("meta");
    std::fs::create_dir_all(&meta_dir).unwrap();

    let counters_path = meta_dir.join("counters.json");

    // Start from defaults
    let counters = read_counters(&counters_path).unwrap();
    assert_eq!(counters.next_display_id, 1);

    // Claim 1 ID
    let first = counters.next_display_id;
    let mut updated = counters;
    updated.next_display_id += 1;
    write_counters(&counters_path, &updated).unwrap();

    assert_eq!(first, 1);

    // Claim another
    let counters = read_counters(&counters_path).unwrap();
    assert_eq!(counters.next_display_id, 2);
}

#[test]
fn test_load_issue_by_display_id() {
    let dir = tempdir().unwrap();
    let issues_dir = dir.path().join("issues");
    std::fs::create_dir_all(&issues_dir).unwrap();

    let issue1 = make_issue(1, "First");
    let issue2 = make_issue(2, "Second");
    write_issue_file(&issues_dir.join(format!("{}.json", issue1.uuid)), &issue1).unwrap();
    write_issue_file(&issues_dir.join(format!("{}.json", issue2.uuid)), &issue2).unwrap();

    // Simulate the scan logic
    let found = scan_for_display_id(&issues_dir, 2).unwrap();
    assert_eq!(found.title, "Second");
    assert_eq!(found.uuid, issue2.uuid);
}

#[test]
fn test_load_issue_by_display_id_not_found() {
    let dir = tempdir().unwrap();
    let issues_dir = dir.path().join("issues");
    std::fs::create_dir_all(&issues_dir).unwrap();

    let result = scan_for_display_id(&issues_dir, 99);
    assert!(result.is_err());
}

#[test]
fn test_resolve_uuid_from_files() {
    let dir = tempdir().unwrap();
    let issues_dir = dir.path().join("issues");
    std::fs::create_dir_all(&issues_dir).unwrap();

    let issue = make_issue(42, "Target");
    write_issue_file(&issues_dir.join(format!("{}.json", issue.uuid)), &issue).unwrap();

    let found = scan_for_display_id(&issues_dir, 42).unwrap();
    assert_eq!(found.uuid, issue.uuid);
}

#[test]
fn test_counters_sequential_claim() {
    let dir = tempdir().unwrap();
    let meta_dir = dir.path().join("meta");
    std::fs::create_dir_all(&meta_dir).unwrap();
    let path = meta_dir.join("counters.json");

    // Claim 3 sequential IDs
    let mut counters = read_counters(&path).unwrap();
    let ids: Vec<i64> = (0..3)
        .map(|_| {
            let id = counters.next_display_id;
            counters.next_display_id += 1;
            id
        })
        .collect();

    write_counters(&path, &counters).unwrap();

    assert_eq!(ids, vec![1, 2, 3]);
    let reloaded = read_counters(&path).unwrap();
    assert_eq!(reloaded.next_display_id, 4);
}

#[test]
fn test_replace_local_refs_basic() {
    let replacements = vec![
        ("L1".to_string(), "#5".to_string()),
        ("L2".to_string(), "#6".to_string()),
    ];
    let result = replace_local_refs("See L1 and L2 for details", &replacements);
    assert_eq!(result, Some("See #5 and #6 for details".to_string()));
}

#[test]
fn test_replace_local_refs_no_match() {
    let replacements = vec![("L1".to_string(), "#5".to_string())];
    let result = replace_local_refs("No local refs here", &replacements);
    assert!(result.is_none());
}

#[test]
fn test_replace_local_refs_non_matching_id() {
    let replacements = vec![("L1".to_string(), "#5".to_string())];
    let result = replace_local_refs("See L99 for info", &replacements);
    assert!(result.is_none());
}

#[test]
fn test_replace_local_refs_word_boundary() {
    let replacements = vec![("L1".to_string(), "#5".to_string())];
    // "FILE1" should NOT be rewritten (L1 is preceded by alphanumeric)
    let result = replace_local_refs("Check FILE1 now", &replacements);
    assert!(result.is_none());

    // "L1." should be rewritten (punctuation after is ok)
    let result = replace_local_refs("Fixed L1.", &replacements);
    assert_eq!(result, Some("Fixed #5.".to_string()));

    // "L1," in a list
    let result = replace_local_refs(
        "L1, L2 are done",
        &[
            ("L1".to_string(), "#5".to_string()),
            ("L2".to_string(), "#6".to_string()),
        ],
    );
    assert_eq!(result, Some("#5, #6 are done".to_string()));
}

#[test]
fn test_replace_local_refs_start_end() {
    let replacements = vec![("L1".to_string(), "#5".to_string())];
    // At start of string
    let result = replace_local_refs("L1 is done", &replacements);
    assert_eq!(result, Some("#5 is done".to_string()));

    // At end of string
    let result = replace_local_refs("Working on L1", &replacements);
    assert_eq!(result, Some("Working on #5".to_string()));

    // Entire string
    let result = replace_local_refs("L1", &replacements);
    assert_eq!(result, Some("#5".to_string()));
}

/// Helper for tests: scan issues dir for a `display_id` (mirrors `SharedWriter` logic).
fn scan_for_display_id(issues_dir: &Path, display_id: i64) -> Result<IssueFile> {
    for entry in std::fs::read_dir(issues_dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        if let Ok(issue) = read_issue_file(&path) {
            if issue.display_id == Some(display_id) {
                return Ok(issue);
            }
        }
    }
    bail!("Issue #{display_id} not found")
}

#[test]
fn test_v1_issue_path_format() {
    let uuid = Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-ef1234567890").unwrap();
    let path = format!("issues/{uuid}.json");
    assert_eq!(path, "issues/a1b2c3d4-e5f6-7890-abcd-ef1234567890.json");
}

#[test]
fn test_v2_issue_path_format() {
    let uuid = Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-ef1234567890").unwrap();
    let path = format!("issues/{uuid}/issue.json");
    assert_eq!(
        path,
        "issues/a1b2c3d4-e5f6-7890-abcd-ef1234567890/issue.json"
    );
}

#[test]
fn test_v2_comment_path_format() {
    let issue_uuid = Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-ef1234567890").unwrap();
    let comment_uuid = Uuid::parse_str("11111111-2222-3333-4444-555555555555").unwrap();
    let path = format!("issues/{issue_uuid}/comments/{comment_uuid}.json");
    assert_eq!(
        path,
        "issues/a1b2c3d4-e5f6-7890-abcd-ef1234567890/comments/11111111-2222-3333-4444-555555555555.json"
    );
}

#[test]
fn test_v2_scan_finds_issue_in_subdirectory() {
    let dir = tempdir().unwrap();
    let issues_dir = dir.path().join("issues");

    // Create a v2-style issue directory
    let issue = make_issue(7, "V2 Issue");
    let issue_subdir = issues_dir.join(issue.uuid.to_string());
    std::fs::create_dir_all(issue_subdir.join("comments")).unwrap();
    write_issue_file(&issue_subdir.join("issue.json"), &issue).unwrap();

    // The v2 scan should find it
    let mut found = false;
    for entry in std::fs::read_dir(&issues_dir).unwrap() {
        let entry = entry.unwrap();
        let path = entry.path();
        if path.is_dir() {
            let issue_file = path.join("issue.json");
            if issue_file.exists() {
                if let Ok(loaded) = read_issue_file(&issue_file) {
                    if loaded.display_id == Some(7) {
                        assert_eq!(loaded.title, "V2 Issue");
                        found = true;
                    }
                }
            }
        }
    }
    assert!(found, "v2 issue not found in subdirectory scan");
}

#[test]
fn test_v2_comment_file_construction() {
    use crate::issue_file::CommentFile;

    let issue_uuid = Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-ef1234567890").unwrap();
    let comment_uuid = Uuid::new_v4();
    let comment = CommentFile {
        uuid: comment_uuid,
        issue_uuid,
        author: "test-agent".to_string(),
        content: "A standalone comment".to_string(),
        created_at: Utc::now(),
        kind: "note".to_string(),
        trigger_type: None,
        intervention_context: None,
        driver_key_fingerprint: None,
        signed_by: None,
        signature: None,
    };

    let json = serde_json::to_string_pretty(&comment).unwrap();
    let parsed: CommentFile = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.uuid, comment_uuid);
    assert_eq!(parsed.issue_uuid, issue_uuid);
    assert_eq!(parsed.content, "A standalone comment");
    assert_eq!(parsed.kind, "note");
}

#[test]
fn test_v2_intervention_comment_file_construction() {
    use crate::issue_file::CommentFile;

    let issue_uuid = Uuid::parse_str("a1b2c3d4-e5f6-7890-abcd-ef1234567890").unwrap();
    let comment_uuid = Uuid::new_v4();
    let comment = CommentFile {
        uuid: comment_uuid,
        issue_uuid,
        author: "test-agent".to_string(),
        content: "Driver intervention".to_string(),
        created_at: Utc::now(),
        kind: "intervention".to_string(),
        trigger_type: Some("redirect".to_string()),
        intervention_context: Some("User redirected task".to_string()),
        driver_key_fingerprint: Some("SHA256:abc123".to_string()),
        signed_by: None,
        signature: None,
    };

    let json = serde_json::to_string_pretty(&comment).unwrap();
    let parsed: CommentFile = serde_json::from_str(&json).unwrap();
    assert_eq!(parsed.kind, "intervention");
    assert_eq!(parsed.trigger_type, Some("redirect".to_string()));
    assert_eq!(
        parsed.intervention_context,
        Some("User redirected task".to_string())
    );
    assert_eq!(
        parsed.driver_key_fingerprint,
        Some("SHA256:abc123".to_string())
    );
}

#[test]
fn test_lock_confirm_timeout_constant() {
    assert_eq!(LOCK_CONFIRM_TIMEOUT_SECS, 30);
}

mod lock_v2_tests {
    use super::*;
    use crate::issue_file::LockFileV2;
    use tempfile::tempdir;

    #[test]
    fn test_lock_claim_result_variants() {
        let claimed = LockClaimResult::Claimed;
        let already = LockClaimResult::AlreadyHeld;
        let contended = LockClaimResult::Contended {
            winner_agent_id: "agent-2".to_string(),
        };
        assert_eq!(claimed, LockClaimResult::Claimed);
        assert_eq!(already, LockClaimResult::AlreadyHeld);
        assert_ne!(claimed, already);
        assert_ne!(claimed, contended);
        assert_eq!(
            contended,
            LockClaimResult::Contended {
                winner_agent_id: "agent-2".to_string(),
            }
        );
        // Verify Debug
        let _ = format!("{claimed:?}");
        let _ = format!("{contended:?}");
    }

    #[test]
    fn test_read_lock_v2_file() {
        let dir = tempdir().unwrap();
        let locks_dir = dir.path().join("locks");
        std::fs::create_dir_all(&locks_dir).unwrap();

        let lock = LockFileV2 {
            issue_id: 42,
            agent_id: "agent-1".to_string(),
            branch: Some("feature/x".to_string()),
            claimed_at: chrono::Utc::now(),
            signed_by: Some("SHA256:abc".to_string()),
        };
        let json = serde_json::to_string_pretty(&lock).unwrap();
        std::fs::write(locks_dir.join("42.json"), &json).unwrap();

        // Read it back
        let content = std::fs::read_to_string(locks_dir.join("42.json")).unwrap();
        let parsed: LockFileV2 = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed.issue_id, 42);
        assert_eq!(parsed.agent_id, "agent-1");
        assert_eq!(parsed.branch, Some("feature/x".to_string()));
    }

    #[test]
    fn test_read_lock_v2_missing() {
        let dir = tempdir().unwrap();
        let lock_path = dir.path().join("locks").join("99.json");
        assert!(!lock_path.exists());
    }

    #[test]
    fn test_lock_v2_file_roundtrip() {
        let dir = tempdir().unwrap();
        let locks_dir = dir.path().join("locks");
        std::fs::create_dir_all(&locks_dir).unwrap();

        let lock = LockFileV2 {
            issue_id: 5,
            agent_id: "worker-1".to_string(),
            branch: None,
            claimed_at: chrono::Utc::now(),
            signed_by: None,
        };
        let json = serde_json::to_string_pretty(&lock).unwrap();
        let path = locks_dir.join("5.json");
        std::fs::write(&path, &json).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: LockFileV2 = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed.issue_id, lock.issue_id);
        assert_eq!(parsed.agent_id, lock.agent_id);
        assert!(parsed.branch.is_none());
        assert!(parsed.signed_by.is_none());
    }

    #[test]
    fn test_lock_contention_deterministic_winner() {
        // Verify that compaction's first-claim-wins rule works
        use crate::checkpoint::{read_checkpoint, write_checkpoint, CheckpointState};
        use crate::events::{append_event, Event, EventEnvelope};
        use chrono::Utc;

        let dir = tempdir().unwrap();
        let cache = dir.path();

        // Set up checkpoint
        std::fs::create_dir_all(cache.join("checkpoint")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-a")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-b")).unwrap();
        std::fs::create_dir_all(cache.join("locks")).unwrap();
        std::fs::create_dir_all(cache.join("issues")).unwrap();

        let state = CheckpointState::default();
        write_checkpoint(cache, &state).unwrap();

        let now = Utc::now();

        // Agent A claims first (earlier timestamp)
        let e1 = EventEnvelope {
            agent_id: "agent-a".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(1),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: None,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-a/events.log"), &e1).unwrap();

        // Agent B claims second (later timestamp)
        let e2 = EventEnvelope {
            agent_id: "agent-b".to_string(),
            agent_seq: 1,
            timestamp: now,
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: None,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-b/events.log"), &e2).unwrap();

        // Run compaction
        let result = crate::compaction::compact(cache, "agent-a", true)
            .unwrap()
            .unwrap();
        assert_eq!(result.locks_materialized, 1);

        // Read checkpoint -- agent-a should win (earlier timestamp)
        let state = read_checkpoint(cache).unwrap();
        let lock = state.locks.get(&1).unwrap();
        assert_eq!(lock.agent_id, "agent-a");
    }

    #[test]
    fn test_prune_then_checkpoint_clear() {
        use crate::checkpoint::{write_checkpoint, CheckpointState, LockEntry};
        use crate::events::{append_event, Event, EventEnvelope, OrderingKey};
        use chrono::Utc;

        let dir = tempdir().unwrap();
        let cache = dir.path();

        std::fs::create_dir_all(cache.join("checkpoint")).unwrap();
        std::fs::create_dir_all(cache.join("agents/stale-agent")).unwrap();
        std::fs::create_dir_all(cache.join("locks")).unwrap();
        std::fs::create_dir_all(cache.join("issues")).unwrap();

        let now = Utc::now();

        // Write an event for the stale agent
        let e = EventEnvelope {
            agent_id: "stale-agent".to_string(),
            agent_seq: 1,
            timestamp: now,
            event: Event::LockClaimed {
                issue_display_id: 5,
                branch: None,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/stale-agent/events.log"), &e).unwrap();

        // Write a watermark that covers the event so prune_events will prune it
        let watermark = OrderingKey {
            timestamp: now + chrono::Duration::seconds(1),
            agent_id: "stale-agent".to_string(),
            agent_seq: 1,
        };

        // Compact to materialize (watermark is embedded in checkpoint state)
        let mut state = CheckpointState {
            watermark: Some(watermark),
            ..CheckpointState::default()
        };
        state.locks.insert(
            5,
            LockEntry {
                agent_id: "stale-agent".to_string(),
                branch: None,
                claimed_at: now,
            },
        );
        write_checkpoint(cache, &state).unwrap();

        // Write materialized lock file
        let lock = crate::issue_file::LockFileV2 {
            issue_id: 5,
            agent_id: "stale-agent".to_string(),
            branch: None,
            claimed_at: now,
            signed_by: None,
        };
        std::fs::write(
            cache.join("locks/5.json"),
            serde_json::to_string_pretty(&lock).unwrap(),
        )
        .unwrap();

        // Prune stale agent events
        let pruned = crate::compaction::prune_events(cache, "stale-agent").unwrap();
        assert!(pruned > 0);

        // Clear checkpoint lock
        let mut state = crate::checkpoint::read_checkpoint(cache).unwrap();
        state.locks.remove(&5);
        write_checkpoint(cache, &state).unwrap();

        // Remove lock file
        let lock_path = cache.join("locks/5.json");
        if lock_path.exists() {
            std::fs::remove_file(&lock_path).unwrap();
        }

        // Verify clean state
        let state = crate::checkpoint::read_checkpoint(cache).unwrap();
        assert!(state.locks.is_empty());
        assert!(!cache.join("locks/5.json").exists());
    }

    #[test]
    fn test_lock_file_v2_with_all_fields() {
        let dir = tempdir().unwrap();
        let locks_dir = dir.path().join("locks");
        std::fs::create_dir_all(&locks_dir).unwrap();

        let now = chrono::Utc::now();
        let lock = LockFileV2 {
            issue_id: 100,
            agent_id: "agent-special".to_string(),
            branch: Some("feature/special-branch".to_string()),
            claimed_at: now,
            signed_by: Some("SHA256:xyz789".to_string()),
        };
        let json = serde_json::to_string_pretty(&lock).unwrap();
        let path = locks_dir.join("100.json");
        std::fs::write(&path, &json).unwrap();

        let content = std::fs::read_to_string(&path).unwrap();
        let parsed: LockFileV2 = serde_json::from_str(&content).unwrap();
        assert_eq!(parsed.issue_id, 100);
        assert_eq!(parsed.agent_id, "agent-special");
        assert_eq!(parsed.branch, Some("feature/special-branch".to_string()));
        assert_eq!(parsed.claimed_at, now);
        assert_eq!(parsed.signed_by, Some("SHA256:xyz789".to_string()));
    }

    #[test]
    fn test_lock_claim_result_display_and_equality() {
        // Verify Contended results with different winners are not equal
        let c1 = LockClaimResult::Contended {
            winner_agent_id: "agent-1".to_string(),
        };
        let c2 = LockClaimResult::Contended {
            winner_agent_id: "agent-2".to_string(),
        };
        assert_ne!(c1, c2);

        // Verify same winner is equal
        let c3 = LockClaimResult::Contended {
            winner_agent_id: "agent-1".to_string(),
        };
        assert_eq!(c1, c3);

        // Verify Clone works correctly
        let cloned = c1.clone();
        assert_eq!(c1, cloned);
    }

    #[test]
    fn test_lock_contention_with_three_agents() {
        // Three agents claiming same lock, verify deterministic winner
        use crate::checkpoint::{read_checkpoint, write_checkpoint, CheckpointState};
        use crate::events::{append_event, Event, EventEnvelope};
        use chrono::Utc;

        let dir = tempdir().unwrap();
        let cache = dir.path();

        std::fs::create_dir_all(cache.join("checkpoint")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-a")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-b")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-c")).unwrap();
        std::fs::create_dir_all(cache.join("locks")).unwrap();
        std::fs::create_dir_all(cache.join("issues")).unwrap();

        let state = CheckpointState::default();
        write_checkpoint(cache, &state).unwrap();

        let now = Utc::now();

        // Agent C claims first (earliest)
        let e1 = EventEnvelope {
            agent_id: "agent-c".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(3),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: Some("feature/c".to_string()),
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-c/events.log"), &e1).unwrap();

        // Agent A claims second
        let e2 = EventEnvelope {
            agent_id: "agent-a".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(2),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: Some("feature/a".to_string()),
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-a/events.log"), &e2).unwrap();

        // Agent B claims third
        let e3 = EventEnvelope {
            agent_id: "agent-b".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(1),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: Some("feature/b".to_string()),
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-b/events.log"), &e3).unwrap();

        let result = crate::compaction::compact(cache, "agent-a", true)
            .unwrap()
            .unwrap();
        assert_eq!(result.locks_materialized, 1);

        let state = read_checkpoint(cache).unwrap();
        let lock = state.locks.get(&1).unwrap();
        assert_eq!(lock.agent_id, "agent-c");
        assert_eq!(lock.branch, Some("feature/c".to_string()));
    }

    #[test]
    fn test_lock_contention_then_winner_releases() {
        // Two agents contend. Winner releases. Lock should be empty.
        use crate::checkpoint::{read_checkpoint, write_checkpoint, CheckpointState};
        use crate::events::{append_event, Event, EventEnvelope};
        use chrono::Utc;

        let dir = tempdir().unwrap();
        let cache = dir.path();

        std::fs::create_dir_all(cache.join("checkpoint")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-a")).unwrap();
        std::fs::create_dir_all(cache.join("agents/agent-b")).unwrap();
        std::fs::create_dir_all(cache.join("locks")).unwrap();
        std::fs::create_dir_all(cache.join("issues")).unwrap();

        let state = CheckpointState::default();
        write_checkpoint(cache, &state).unwrap();

        let now = Utc::now();

        // Agent A claims first (wins)
        let e1 = EventEnvelope {
            agent_id: "agent-a".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(3),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: None,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-a/events.log"), &e1).unwrap();

        // Agent B claims second (loses)
        let e2 = EventEnvelope {
            agent_id: "agent-b".to_string(),
            agent_seq: 1,
            timestamp: now - chrono::Duration::seconds(2),
            event: Event::LockClaimed {
                issue_display_id: 1,
                branch: None,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-b/events.log"), &e2).unwrap();

        // Agent A releases
        let e3 = EventEnvelope {
            agent_id: "agent-a".to_string(),
            agent_seq: 2,
            timestamp: now - chrono::Duration::seconds(1),
            event: Event::LockReleased {
                issue_display_id: 1,
            },
            signed_by: None,
            signature: None,
        };
        append_event(&cache.join("agents/agent-a/events.log"), &e3).unwrap();

        crate::compaction::compact(cache, "agent-a", true).unwrap();

        let state = read_checkpoint(cache).unwrap();
        assert!(state.locks.is_empty());
        assert!(!cache.join("locks/1.json").exists());
    }

    #[test]
    fn test_lock_file_v2_missing_optional_fields() {
        // Verify LockFileV2 deserialization works when optional fields are null
        let json = r#"{
            "issue_id": 7,
            "agent_id": "agent-minimal",
            "branch": null,
            "claimed_at": "2026-01-01T00:00:00Z",
            "signed_by": null
        }"#;
        let parsed: LockFileV2 = serde_json::from_str(json).unwrap();
        assert_eq!(parsed.issue_id, 7);
        assert_eq!(parsed.agent_id, "agent-minimal");
        assert!(parsed.branch.is_none());
        assert!(parsed.signed_by.is_none());
    }

    #[test]
    fn test_lock_contention_deterministic_across_compaction_agents() {
        // The same winner should emerge regardless of which agent runs compaction
        use crate::checkpoint::{read_checkpoint, write_checkpoint, CheckpointState};
        use crate::events::{append_event, Event, EventEnvelope};
        use chrono::Utc;

        let now = Utc::now();

        // Set up two identical caches with the same events
        for compactor in &["agent-a", "agent-b"] {
            let dir = tempdir().unwrap();
            let cache = dir.path();

            std::fs::create_dir_all(cache.join("checkpoint")).unwrap();
            std::fs::create_dir_all(cache.join("agents/agent-a")).unwrap();
            std::fs::create_dir_all(cache.join("agents/agent-b")).unwrap();
            std::fs::create_dir_all(cache.join("locks")).unwrap();
            std::fs::create_dir_all(cache.join("issues")).unwrap();

            let state = CheckpointState::default();
            write_checkpoint(cache, &state).unwrap();

            let e1 = EventEnvelope {
                agent_id: "agent-a".to_string(),
                agent_seq: 1,
                timestamp: now - chrono::Duration::seconds(2),
                event: Event::LockClaimed {
                    issue_display_id: 1,
                    branch: None,
                },
                signed_by: None,
                signature: None,
            };
            append_event(&cache.join("agents/agent-a/events.log"), &e1).unwrap();

            let e2 = EventEnvelope {
                agent_id: "agent-b".to_string(),
                agent_seq: 1,
                timestamp: now - chrono::Duration::seconds(1),
                event: Event::LockClaimed {
                    issue_display_id: 1,
                    branch: None,
                },
                signed_by: None,
                signature: None,
            };
            append_event(&cache.join("agents/agent-b/events.log"), &e2).unwrap();

            crate::compaction::compact(cache, compactor, true).unwrap();

            let state = read_checkpoint(cache).unwrap();
            assert_eq!(
                state.locks[&1].agent_id, "agent-a",
                "Winner should be agent-a regardless of who runs compaction (compactor={compactor})"
            );
        }
    }
}

// ---- Integration tests with real git repos ----

mod integration {
    use super::*;
    use crate::db::Database;
    use crate::identity::AgentConfig;
    use std::process::Command;
    use tempfile::TempDir;

    /// Set up a minimal git environment for `SharedWriter` tests.
    ///
    /// Returns (`work_dir`, `remote_dir`). The hub cache (`crosslink/hub` branch)
    /// is initialized directly inside the `work_dir` so `SharedWriter::new()` works.
    fn setup_shared_writer_env() -> (TempDir, TempDir, std::path::PathBuf) {
        let remote_dir = tempfile::tempdir().unwrap();
        let work_dir = tempfile::tempdir().unwrap();

        // Init bare remote
        Command::new("git")
            .current_dir(remote_dir.path())
            .args(["init", "--bare", "-b", "main"])
            .output()
            .unwrap();

        // Init work repo
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["init", "-b", "main"])
            .output()
            .unwrap();

        // Config git identity
        for args in [
            vec!["config", "user.email", "test@test.local"],
            vec!["config", "user.name", "Test"],
            vec![
                "remote",
                "add",
                "origin",
                remote_dir.path().to_str().unwrap(),
            ],
        ] {
            Command::new("git")
                .current_dir(work_dir.path())
                .args(&args)
                .output()
                .unwrap();
        }

        // Initial commit + push
        std::fs::write(work_dir.path().join("README.md"), "# test\n").unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["add", "."])
            .output()
            .unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["commit", "-m", "init", "--no-gpg-sign"])
            .output()
            .unwrap();
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["push", "-u", "origin", "main"])
            .output()
            .unwrap();

        // Create .crosslink dir with hook-config.json
        let crosslink_dir = work_dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        std::fs::write(
            crosslink_dir.join("hook-config.json"),
            r#"{"remote":"origin","layout":"v2"}"#,
        )
        .unwrap();

        // Create agent.json (needed for SharedWriter::new() to get an agent identity)
        let agent_config = AgentConfig {
            agent_id: "test-agent".to_string(),
            machine_id: "test-machine".to_string(),
            description: Some("Integration test agent".to_string()),
            ssh_key_path: None,
            ssh_fingerprint: None,
            ssh_public_key: None,
        };
        let agent_json = serde_json::to_string_pretty(&agent_config).unwrap();
        std::fs::write(crosslink_dir.join("agent.json"), agent_json).unwrap();

        // Initialize the hub cache (crosslink/hub branch) using SyncManager
        let sync = crate::sync::SyncManager::new(&crosslink_dir).unwrap();
        sync.init_cache().unwrap();

        (work_dir, remote_dir, crosslink_dir)
    }

    /// Create an in-memory test database at a temp path.
    fn make_db(dir: &std::path::Path) -> Database {
        Database::open(&dir.join("issues.db")).unwrap()
    }

    // --- SharedWriter::new() ---

    #[test]
    fn test_new_returns_some_with_agent_and_hub() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap();
        assert!(
            writer.is_some(),
            "SharedWriter::new() should return Some when agent.json and hub branch exist"
        );
        drop(work_dir);
    }

    #[test]
    fn test_new_agent_id_matches_config() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        assert_eq!(writer.agent_id(), "test-agent");
        drop(work_dir);
    }

    #[test]
    fn test_new_creates_issues_and_meta_dirs() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let cache_dir = crosslink_dir.join(".hub-cache");
        assert!(
            cache_dir.join("issues").exists(),
            "issues/ dir should exist"
        );
        assert!(
            cache_dir.join("meta").join("milestones").exists(),
            "meta/milestones/ dir should exist"
        );
        drop(work_dir);
    }

    // --- create_issue() ---

    #[test]
    fn test_create_issue_returns_display_id() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Test issue", None, "medium")
            .unwrap();
        assert!(id > 0, "create_issue should return a positive display ID");
        drop(work_dir);
    }

    #[test]
    fn test_create_issue_increments_id() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id1 = writer
            .create_issue(&db, "First issue", None, "low")
            .unwrap();
        let id2 = writer
            .create_issue(&db, "Second issue", None, "low")
            .unwrap();
        assert_eq!(id2, id1 + 1, "IDs should be sequential");
        drop(work_dir);
    }

    #[test]
    fn test_create_issue_with_description() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(
                &db,
                "With description",
                Some("A detailed description"),
                "high",
            )
            .unwrap();
        assert!(id > 0);

        // Verify it's in the database
        let issue = db.get_issue(id).unwrap();
        assert!(
            issue.is_some(),
            "Issue should exist in database after create"
        );
        let issue = issue.unwrap();
        assert_eq!(issue.title, "With description");
        assert_eq!(issue.description.as_deref(), Some("A detailed description"));
        drop(work_dir);
    }

    #[test]
    fn test_create_issue_high_priority() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Critical bug", None, "critical")
            .unwrap();
        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.priority, Priority::Critical);
        drop(work_dir);
    }

    #[test]
    fn test_create_issue_writes_json_to_cache() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        writer
            .create_issue(&db, "Cache test", None, "medium")
            .unwrap();

        // Verify the issue JSON file exists in the hub cache (v2 layout)
        let cache_dir = crosslink_dir.join(".hub-cache").join("issues");
        let entries: Vec<_> = std::fs::read_dir(&cache_dir)
            .unwrap()
            .filter_map(std::result::Result::ok)
            .collect();
        assert!(
            !entries.is_empty(),
            "At least one issue entry should exist in cache"
        );
        drop(work_dir);
    }

    // --- create_subissue() ---

    #[test]
    fn test_create_subissue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let parent_id = writer
            .create_issue(&db, "Parent issue", None, "medium")
            .unwrap();
        let child_id = writer
            .create_subissue(&db, parent_id, "Child issue", None, "low")
            .unwrap();

        assert!(child_id > 0);
        assert_ne!(parent_id, child_id);

        // Verify parent relationship in database
        let child = db.get_issue(child_id).unwrap().unwrap();
        assert_eq!(child.parent_id, Some(parent_id));
        drop(work_dir);
    }

    // --- update_issue() ---

    #[test]
    fn test_update_issue_title() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Old title", None, "medium")
            .unwrap();
        writer
            .update_issue(
                &db,
                id,
                Some("New title"),
                DescriptionUpdate::Unchanged,
                None,
                None,
            )
            .unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.title, "New title");
        drop(work_dir);
    }

    #[test]
    fn test_update_issue_priority() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Priority test", None, "low")
            .unwrap();
        writer
            .update_issue(
                &db,
                id,
                None,
                DescriptionUpdate::Unchanged,
                None,
                Some("high"),
            )
            .unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.priority, Priority::High);
        drop(work_dir);
    }

    #[test]
    fn test_update_issue_description() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer.create_issue(&db, "Desc test", None, "low").unwrap();
        writer
            .update_issue(
                &db,
                id,
                None,
                DescriptionUpdate::Set("Updated desc"),
                None,
                None,
            )
            .unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.description.as_deref(), Some("Updated desc"));
        drop(work_dir);
    }

    #[test]
    fn test_update_issue_clear_description() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Has desc", Some("initial desc"), "low")
            .unwrap();
        writer
            .update_issue(&db, id, None, DescriptionUpdate::Clear, None, None)
            .unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert!(issue.description.is_none(), "Description should be cleared");
        drop(work_dir);
    }

    // --- close_issue() / reopen_issue() ---

    #[test]
    fn test_close_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Close me", None, "medium")
            .unwrap();
        writer.close_issue(&db, id).unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.status, IssueStatus::Closed);
        drop(work_dir);
    }

    #[test]
    fn test_reopen_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Open/close cycle", None, "medium")
            .unwrap();
        writer.close_issue(&db, id).unwrap();
        writer.reopen_issue(&db, id).unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.status, IssueStatus::Open);
        drop(work_dir);
    }

    #[test]
    fn test_closed_issue_has_closed_at() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Closed at test", None, "medium")
            .unwrap();

        // Before closing, closed_at should be None
        // Read from cache to verify
        let cache_dir = crosslink_dir.join(".hub-cache");
        let issue_before = writer.load_issue_by_id(id, &db).unwrap();
        assert!(
            issue_before.closed_at.is_none(),
            "closed_at should be None before closing"
        );

        writer.close_issue(&db, id).unwrap();

        let issue_after = writer.load_issue_by_id(id, &db).unwrap();
        assert!(
            issue_after.closed_at.is_some(),
            "closed_at should be set after closing"
        );
        assert_eq!(issue_after.status, IssueStatus::Closed);
        drop(cache_dir);
        drop(work_dir);
    }

    #[test]
    fn test_reopen_clears_closed_at() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Reopen cleared", None, "medium")
            .unwrap();
        writer.close_issue(&db, id).unwrap();
        writer.reopen_issue(&db, id).unwrap();

        let issue = writer.load_issue_by_id(id, &db).unwrap();
        assert!(
            issue.closed_at.is_none(),
            "closed_at should be cleared after reopen"
        );
        drop(work_dir);
    }

    // --- delete_issue() ---

    #[test]
    fn test_delete_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id1 = writer
            .create_issue(&db, "Delete me", None, "medium")
            .unwrap();
        let id2 = writer.create_issue(&db, "Keep me", None, "medium").unwrap();

        let delete_result = writer.delete_issue(&db, id1);
        // delete may fail on empty commit in test environments; verify at least the DB state
        if delete_result.is_ok() {
            let deleted = db.get_issue(id1).unwrap();
            assert!(deleted.is_none(), "Deleted issue should be gone from DB");
        }

        // Issue 2 should still exist regardless
        let kept = db.get_issue(id2).unwrap();
        assert!(kept.is_some(), "Kept issue should still be in DB");

        drop(work_dir);
    }

    #[test]
    fn test_delete_issue_removes_file_from_disk() {
        // Verify that delete_issue's closure removes the file from disk via issue_path(),
        // which correctly uses V2 layout (issues/{uuid}/issue.json).
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "File remove test", None, "medium")
            .unwrap();

        // Get the UUID so we can check the V2 file path
        let uuid_str = db.get_issue_uuid_by_id(id).unwrap();
        let uuid: Uuid = uuid_str.parse().unwrap();
        let v2_issue_path = crosslink_dir
            .join(".hub-cache")
            .join("issues")
            .join(uuid.to_string())
            .join("issue.json");

        assert!(
            v2_issue_path.exists(),
            "Issue file should exist before delete"
        );

        // delete_issue removes the file from disk in the prepare closure
        // (even if the subsequent git commit step fails due to V2 path mismatch)
        let _ = writer.delete_issue(&db, id);

        assert!(
            !v2_issue_path.exists(),
            "Issue file should be removed from disk by delete_issue's prepare closure"
        );
        drop(work_dir);
    }

    // --- add_comment() / add_intervention_comment() ---

    #[test]
    fn test_add_comment_returns_id() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Comment host", None, "medium")
            .unwrap();
        let comment_id = writer
            .add_comment(&db, issue_id, "A test comment", "note")
            .unwrap();

        assert!(comment_id > 0, "comment ID should be positive");
        drop(work_dir);
    }

    #[test]
    fn test_add_comment_persists_to_db() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Comment persist", None, "medium")
            .unwrap();
        writer
            .add_comment(&db, issue_id, "Persisted comment content", "plan")
            .unwrap();

        let comments = db.get_comments(issue_id).unwrap();
        assert!(!comments.is_empty(), "Comment should be in DB");
        assert_eq!(comments[0].content, "Persisted comment content");
        drop(work_dir);
    }

    #[test]
    fn test_add_comment_multiple_kinds() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Typed comments", None, "medium")
            .unwrap();

        let kinds = ["plan", "decision", "observation", "blocker", "resolution"];
        for kind in &kinds {
            writer
                .add_comment(&db, issue_id, &format!("Comment: {kind}"), kind)
                .unwrap();
        }

        let comments = db.get_comments(issue_id).unwrap();
        assert_eq!(comments.len(), kinds.len());
        drop(work_dir);
    }

    #[test]
    fn test_add_comment_sequential_ids() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Sequential comments", None, "medium")
            .unwrap();
        let c1 = writer
            .add_comment(&db, issue_id, "First comment", "note")
            .unwrap();
        let c2 = writer
            .add_comment(&db, issue_id, "Second comment", "note")
            .unwrap();

        assert_eq!(c2, c1 + 1, "Comment IDs should be sequential");
        drop(work_dir);
    }

    #[test]
    fn test_add_intervention_comment() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Intervention host", None, "medium")
            .unwrap();
        let comment_id = writer
            .add_intervention_comment(
                &db,
                issue_id,
                "Intervention content",
                "manual_redirect",
                Some("context string"),
                None,
            )
            .unwrap();

        assert!(comment_id > 0);
        let comments = db.get_comments(issue_id).unwrap();
        assert!(!comments.is_empty());
        assert_eq!(comments[0].content, "Intervention content");
        drop(work_dir);
    }

    // --- add_label() / remove_label() ---

    #[test]
    fn test_add_label() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Label test", None, "medium")
            .unwrap();
        writer.add_label(&db, id, "bug").unwrap();

        let labels = db.get_labels(id).unwrap();
        assert!(labels.contains(&"bug".to_string()));
        drop(work_dir);
    }

    #[test]
    fn test_add_multiple_labels() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Multi-label", None, "medium")
            .unwrap();
        writer.add_label(&db, id, "bug").unwrap();
        writer.add_label(&db, id, "urgent").unwrap();
        writer.add_label(&db, id, "frontend").unwrap();

        let labels = db.get_labels(id).unwrap();
        assert!(labels.contains(&"bug".to_string()));
        assert!(labels.contains(&"urgent".to_string()));
        assert!(labels.contains(&"frontend".to_string()));
        drop(work_dir);
    }

    #[test]
    fn test_remove_label() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Remove label", None, "medium")
            .unwrap();
        writer.add_label(&db, id, "bug").unwrap();
        writer.add_label(&db, id, "keep").unwrap();
        writer.remove_label(&db, id, "bug").unwrap();

        let labels = db.get_labels(id).unwrap();
        assert!(
            !labels.contains(&"bug".to_string()),
            "bug label should be gone"
        );
        assert!(
            labels.contains(&"keep".to_string()),
            "keep label should remain"
        );
        drop(work_dir);
    }

    #[test]
    fn test_add_label_idempotent() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Idempotent label", None, "medium")
            .unwrap();
        writer.add_label(&db, id, "tag").unwrap();
        let _ = writer.add_label(&db, id, "tag"); // duplicate -- may error on empty commit

        let labels = db.get_labels(id).unwrap();
        let tag_count = labels.iter().filter(|l| l.as_str() == "tag").count();
        assert_eq!(tag_count, 1, "Duplicate label should not be double-added");
        drop(work_dir);
    }

    // --- add_blocker() / remove_blocker() ---

    #[test]
    fn test_add_blocker() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let blocked = writer
            .create_issue(&db, "Blocked issue", None, "medium")
            .unwrap();
        let blocker = writer
            .create_issue(&db, "Blocker issue", None, "high")
            .unwrap();

        writer.add_blocker(&db, blocked, blocker).unwrap();

        // The blocked issue's JSON should contain the blocker UUID
        let issue_file = writer.load_issue_by_id(blocked, &db).unwrap();
        assert!(
            !issue_file.blockers.is_empty(),
            "Blocker should be recorded"
        );
        drop(work_dir);
    }

    #[test]
    fn test_remove_blocker() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let blocked = writer
            .create_issue(&db, "Was blocked", None, "medium")
            .unwrap();
        let blocker = writer
            .create_issue(&db, "Was blocker", None, "high")
            .unwrap();

        writer.add_blocker(&db, blocked, blocker).unwrap();
        writer.remove_blocker(&db, blocked, blocker).unwrap();

        let issue_file = writer.load_issue_by_id(blocked, &db).unwrap();
        assert!(issue_file.blockers.is_empty(), "Blocker should be removed");
        drop(work_dir);
    }

    // --- add_relation() / remove_relation() ---

    #[test]
    fn test_add_relation() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id1 = writer
            .create_issue(&db, "Related A", None, "medium")
            .unwrap();
        let id2 = writer
            .create_issue(&db, "Related B", None, "medium")
            .unwrap();

        writer.add_relation(&db, id1, id2).unwrap();

        let issue = writer.load_issue_by_id(id1, &db).unwrap();
        assert!(!issue.related.is_empty(), "Relation should be recorded");
        drop(work_dir);
    }

    #[test]
    fn test_remove_relation() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id1 = writer
            .create_issue(&db, "Related C", None, "medium")
            .unwrap();
        let id2 = writer
            .create_issue(&db, "Related D", None, "medium")
            .unwrap();

        writer.add_relation(&db, id1, id2).unwrap();
        writer.remove_relation(&db, id1, id2).unwrap();

        let issue = writer.load_issue_by_id(id1, &db).unwrap();
        assert!(issue.related.is_empty(), "Relation should be removed");
        drop(work_dir);
    }

    // --- create_milestone() / close_milestone() / delete_milestone() ---

    #[test]
    fn test_create_milestone() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms_id = writer
            .create_milestone(&db, "v1.0", Some("First release"))
            .unwrap();
        assert!(ms_id > 0, "Milestone ID should be positive");
        drop(work_dir);
    }

    #[test]
    fn test_create_multiple_milestones() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms1 = writer.create_milestone(&db, "v1.0", None).unwrap();
        let ms2 = writer.create_milestone(&db, "v2.0", None).unwrap();
        assert_eq!(ms2, ms1 + 1, "Milestone IDs should be sequential");
        drop(work_dir);
    }

    #[test]
    fn test_close_milestone() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms_id = writer.create_milestone(&db, "v1.0", None).unwrap();
        writer.close_milestone(&db, ms_id).unwrap();

        // Read back and verify
        let entry = writer.load_milestone_by_id(ms_id).unwrap();
        assert_eq!(entry.status, IssueStatus::Closed);
        assert!(entry.closed_at.is_some());
        drop(work_dir);
    }

    #[test]
    fn test_delete_milestone() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms_id = writer.create_milestone(&db, "v1.0-del", None).unwrap();
        writer.delete_milestone(&db, ms_id).unwrap();

        // After deletion, load should fail
        let result = writer.load_milestone_by_id(ms_id);
        assert!(result.is_err(), "Deleted milestone should not be loadable");
        drop(work_dir);
    }

    // --- set_milestone_on_issues() / clear_milestone_on_issue() ---

    #[test]
    fn test_set_milestone_on_issues() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms_id = writer.create_milestone(&db, "Sprint 1", None).unwrap();
        let issue_id = writer
            .create_issue(&db, "Sprint task", None, "medium")
            .unwrap();

        writer
            .set_milestone_on_issues(&db, ms_id, &[issue_id])
            .unwrap();

        let issue = writer.load_issue_by_id(issue_id, &db).unwrap();
        assert!(
            issue.milestone_uuid.is_some(),
            "Issue should have milestone_uuid set"
        );
        drop(work_dir);
    }

    #[test]
    fn test_clear_milestone_on_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let ms_id = writer.create_milestone(&db, "Sprint 2", None).unwrap();
        let issue_id = writer
            .create_issue(&db, "Sprint 2 task", None, "medium")
            .unwrap();

        writer
            .set_milestone_on_issues(&db, ms_id, &[issue_id])
            .unwrap();
        writer.clear_milestone_on_issue(&db, issue_id).unwrap();

        let issue = writer.load_issue_by_id(issue_id, &db).unwrap();
        assert!(
            issue.milestone_uuid.is_none(),
            "Issue should have milestone_uuid cleared"
        );
        drop(work_dir);
    }

    // --- read_lock_v2() ---

    #[test]
    fn test_read_lock_v2_returns_none_when_no_lock() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let result = writer.read_lock_v2(999).unwrap();
        assert!(
            result.is_none(),
            "No lock should exist for non-existent issue"
        );
        drop(work_dir);
    }

    #[test]
    fn test_read_lock_v2_reads_existing_lock_file() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Manually write a lock file
        let locks_dir = crosslink_dir.join(".hub-cache").join("locks");
        std::fs::create_dir_all(&locks_dir).unwrap();
        let lock = crate::issue_file::LockFileV2 {
            issue_id: 42,
            agent_id: "test-agent".to_string(),
            branch: Some("feature/x".to_string()),
            claimed_at: chrono::Utc::now(),
            signed_by: None,
        };
        std::fs::write(
            locks_dir.join("42.json"),
            serde_json::to_string_pretty(&lock).unwrap(),
        )
        .unwrap();

        let result = writer.read_lock_v2(42).unwrap();
        assert!(result.is_some());
        let read_lock = result.unwrap();
        assert_eq!(read_lock.issue_id, 42);
        assert_eq!(read_lock.agent_id, "test-agent");
        assert_eq!(read_lock.branch, Some("feature/x".to_string()));
        drop(work_dir);
    }

    // --- Hydration roundtrip ---

    #[test]
    fn test_hydration_roundtrip_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Hydration test", Some("desc"), "high")
            .unwrap();

        // Re-hydrate from cache
        let cache_dir = crosslink_dir.join(".hub-cache");
        crate::hydration::hydrate_to_sqlite(&cache_dir, &db).unwrap();

        let issue = db.get_issue(id).unwrap();
        assert!(issue.is_some());
        let issue = issue.unwrap();
        assert_eq!(issue.title, "Hydration test");
        assert_eq!(issue.priority, Priority::High);
        drop(work_dir);
    }

    #[test]
    fn test_hydration_after_close() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Close hydration", None, "medium")
            .unwrap();
        writer.close_issue(&db, id).unwrap();

        let cache_dir = crosslink_dir.join(".hub-cache");
        crate::hydration::hydrate_to_sqlite(&cache_dir, &db).unwrap();

        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.status, IssueStatus::Closed);
        drop(work_dir);
    }

    #[test]
    fn test_hydration_after_comment() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let issue_id = writer
            .create_issue(&db, "Comment hydration", None, "medium")
            .unwrap();
        writer
            .add_comment(&db, issue_id, "Hydrated comment", "note")
            .unwrap();

        let cache_dir = crosslink_dir.join(".hub-cache");
        crate::hydration::hydrate_to_sqlite(&cache_dir, &db).unwrap();

        let comments = db.get_comments(issue_id).unwrap();
        assert!(!comments.is_empty());
        assert_eq!(comments[0].content, "Hydrated comment");
        drop(work_dir);
    }

    // --- RewriteStats ---

    #[test]
    fn test_rewrite_stats_total() {
        let stats = RewriteStats {
            comments_updated: 3,
            descriptions_updated: 2,
            sessions_updated: 1,
        };
        assert_eq!(stats.total(), 6);
    }

    #[test]
    fn test_rewrite_stats_default_total() {
        let stats = RewriteStats::default();
        assert_eq!(stats.total(), 0);
    }

    // --- rewrite_local_references() ---

    #[test]
    fn test_rewrite_local_references_empty_mapping() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let stats = writer.rewrite_local_references(&db, &[]).unwrap();
        assert_eq!(
            stats.total(),
            0,
            "Empty mapping should produce zero rewrites"
        );
        drop(work_dir);
    }

    #[test]
    fn test_rewrite_local_references_no_matches() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Create an issue with a description that won't match any local refs
        let id = writer
            .create_issue(&db, "No local refs here", Some("Clean description"), "low")
            .unwrap();

        // Mapping says L1 -> #5, but the issue has no L1 refs
        let mapping = vec![(1i64, 5i64, "Some title".to_string())];
        let stats = writer.rewrite_local_references(&db, &mapping).unwrap();
        // Comments and descriptions with no matches should yield 0 updates
        assert_eq!(stats.comments_updated, 0);
        assert_eq!(stats.descriptions_updated, 0);
        let _ = id; // suppress unused warning
        drop(work_dir);
    }

    // --- promote_offline_issues() ---

    #[test]
    fn test_promote_offline_issues_empty() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let mapping = writer.promote_offline_issues(&db).unwrap();
        assert!(mapping.is_empty(), "No offline issues to promote");
        drop(work_dir);
    }

    // --- read_promoted_uuids() / record_promoted_uuids() ---

    #[test]
    fn test_promoted_uuids_roundtrip() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Initially empty
        let before = writer.read_promoted_uuids();
        assert!(before.is_empty());

        // Record some UUIDs
        let uuid1 = Uuid::new_v4();
        let uuid2 = Uuid::new_v4();
        writer.record_promoted_uuids(&[uuid1, uuid2]).unwrap();

        // Read back
        let after = writer.read_promoted_uuids();
        assert!(after.contains(&uuid1));
        assert!(after.contains(&uuid2));
        drop(work_dir);
    }

    #[test]
    fn test_promoted_uuids_are_not_re_promoted() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Record a UUID as promoted
        let uuid = Uuid::new_v4();
        writer.record_promoted_uuids(&[uuid]).unwrap();

        // Write an issue JSON with display_id=None and that UUID -- simulates an offline issue
        let cache_dir = crosslink_dir.join(".hub-cache");
        let issues_dir = cache_dir.join("issues");
        std::fs::create_dir_all(&issues_dir).unwrap();

        // V1-style: a flat file issues/{uuid}.json with display_id null and created_by matching agent
        let issue = crate::issue_file::IssueFile {
            uuid,
            display_id: None,
            title: "Already promoted".to_string(),
            description: None,
            status: IssueStatus::Open,
            priority: Priority::Low,
            parent_uuid: None,
            created_by: "test-agent".to_string(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            closed_at: None,
            labels: vec![],
            comments: vec![],
            blockers: vec![],
            related: vec![],
            milestone_uuid: None,
            time_entries: vec![],
        };
        crate::issue_file::write_issue_file(&issues_dir.join(format!("{uuid}.json")), &issue)
            .unwrap();

        // promote_offline_issues should skip this one (UUID in promoted set)
        let promoted = writer.promote_offline_issues(&db).unwrap();
        assert!(
            promoted.is_empty(),
            "Already-promoted UUID should not be re-promoted"
        );
        drop(work_dir);
    }

    // --- layout_version() ---

    #[test]
    fn test_layout_version_is_v2_for_new_hub() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // init_cache() sets up v2 layout
        assert_eq!(writer.layout_version(), 2, "New hub should be v2 layout");
        drop(work_dir);
    }

    // --- issue_path() / issue_rel_path() -- via V2 layout ---

    #[test]
    fn test_v2_issue_path_uses_subdir() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "V2 path check", None, "low")
            .unwrap();

        // Find the issue UUID from the DB
        let uuid_str = db.get_issue_uuid_by_id(id).unwrap();
        let uuid: Uuid = uuid_str.parse().unwrap();

        // V2: the issue file should be at issues/{uuid}/issue.json
        let cache_dir = crosslink_dir.join(".hub-cache");
        let v2_path = cache_dir
            .join("issues")
            .join(uuid.to_string())
            .join("issue.json");
        assert!(
            v2_path.exists(),
            "V2 issue.json should exist at {}",
            v2_path.display()
        );

        // And the comments subdirectory should also exist
        let comments_dir = cache_dir
            .join("issues")
            .join(uuid.to_string())
            .join("comments");
        assert!(
            comments_dir.exists(),
            "V2 comments dir should exist at {}",
            comments_dir.display()
        );
        drop(work_dir);
    }

    // --- Multiple operations / end-to-end ---

    #[test]
    fn test_full_issue_lifecycle() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Create
        let id = writer
            .create_issue(&db, "Lifecycle issue", Some("Initial desc"), "medium")
            .unwrap();

        // Comment
        writer
            .add_comment(&db, id, "Planning note", "plan")
            .unwrap();

        // Label
        writer.add_label(&db, id, "in-progress").unwrap();

        // Update
        writer
            .update_issue(
                &db,
                id,
                Some("Updated lifecycle"),
                DescriptionUpdate::Unchanged,
                None,
                Some("high"),
            )
            .unwrap();

        // Close
        writer.close_issue(&db, id).unwrap();

        // Verify final state
        let issue = db.get_issue(id).unwrap().unwrap();
        assert_eq!(issue.title, "Updated lifecycle");
        assert_eq!(issue.priority, Priority::High);
        assert_eq!(issue.status, IssueStatus::Closed);

        let labels = db.get_labels(id).unwrap();
        assert!(labels.contains(&"in-progress".to_string()));

        let comments = db.get_comments(id).unwrap();
        assert_eq!(comments.len(), 1);
        drop(work_dir);
    }

    #[test]
    fn test_multiple_issues_independent() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id1 = writer
            .create_issue(&db, "Issue Alpha", None, "high")
            .unwrap();
        let id2 = writer.create_issue(&db, "Issue Beta", None, "low").unwrap();
        let id3 = writer
            .create_issue(&db, "Issue Gamma", None, "medium")
            .unwrap();

        writer.close_issue(&db, id2).unwrap();
        writer.add_label(&db, id1, "critical").unwrap();

        let i1 = db.get_issue(id1).unwrap().unwrap();
        let i2 = db.get_issue(id2).unwrap().unwrap();
        let i3 = db.get_issue(id3).unwrap().unwrap();

        assert_eq!(i1.status, IssueStatus::Open);
        assert_eq!(i2.status, IssueStatus::Closed);
        assert_eq!(i3.status, IssueStatus::Open);

        let labels = db.get_labels(id1).unwrap();
        assert!(labels.contains(&"critical".to_string()));
        drop(work_dir);
    }

    #[test]
    fn test_crosslink_dir_accessor() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let dir = writer.crosslink_dir();
        // crosslink_dir() should return the parent of the cache dir
        // The cache dir is crosslink_dir/.hub-cache, so parent = crosslink_dir
        assert!(
            dir.exists(),
            "crosslink_dir() should point to an existing dir"
        );
        drop(work_dir);
    }

    #[test]
    fn test_event_seq_increments() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Each create_issue triggers emit which calls next_event_seq
        writer.create_issue(&db, "Seq 1", None, "low").unwrap();
        writer.create_issue(&db, "Seq 2", None, "low").unwrap();

        // The event_seq field should be > 0 after two operations
        // We can't directly read event_seq, but we can verify events exist in the log
        let cache_dir = crosslink_dir.join(".hub-cache");
        let log_path = cache_dir
            .join("agents")
            .join("test-agent")
            .join("events.log");

        // The log may or may not exist depending on whether emit_compact_push is called
        // For write_commit_push path (not emit_compact_push), events aren't written
        // Just verify the writer operated successfully
        drop(log_path);
        drop(work_dir);
    }

    #[test]
    fn test_counters_persist_across_writer_instances() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();

        // First writer creates 2 issues
        {
            let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
            let db = make_db(work_dir.path());
            writer.create_issue(&db, "Issue 1", None, "low").unwrap();
            writer.create_issue(&db, "Issue 2", None, "low").unwrap();
        }

        // Second writer should continue from counter 3
        {
            let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
            let db = make_db(work_dir.path());
            let id = writer.create_issue(&db, "Issue 3", None, "low").unwrap();
            assert_eq!(id, 3, "Counter should persist: 3rd issue should get ID 3");
        }

        drop(work_dir);
    }

    #[test]
    fn test_promoted_uuids_path() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let path = writer.promoted_uuids_path();
        assert!(
            path.to_string_lossy().contains(".promoted-uuids"),
            "promoted_uuids_path should contain .promoted-uuids"
        );
        drop(work_dir);
    }

    #[test]
    fn test_event_log_path() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let path = writer.event_log_path();
        assert!(
            path.to_string_lossy().contains("test-agent"),
            "event_log_path should contain agent_id"
        );
        assert!(
            path.to_string_lossy().contains("events.log"),
            "event_log_path should end in events.log"
        );
        drop(work_dir);
    }

    #[test]
    fn test_resolve_ssh_key_path_returns_none_without_key() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // The test agent has no SSH key configured
        let key_path = writer.resolve_ssh_key_path();
        assert!(
            key_path.is_none(),
            "resolve_ssh_key_path should return None when no key is configured"
        );
        drop(work_dir);
    }

    #[test]
    fn test_read_counters_defaults_to_one() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Before any issues are created, next_display_id should be 1
        let counters = writer.read_counters().unwrap();
        assert_eq!(counters.next_display_id, 1);
        drop(work_dir);
    }

    #[test]
    fn test_write_then_read_counters() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        writer
            .create_issue(&db, "Counter check", None, "low")
            .unwrap();

        let counters = writer.read_counters().unwrap();
        assert_eq!(
            counters.next_display_id, 2,
            "After one create, next_display_id should be 2"
        );
        drop(work_dir);
    }

    #[test]
    fn test_load_issue_by_id_positive() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Load by ID", Some("description"), "medium")
            .unwrap();
        let loaded = writer.load_issue_by_id(id, &db).unwrap();
        assert_eq!(loaded.title, "Load by ID");
        assert_eq!(loaded.status, IssueStatus::Open);
        drop(work_dir);
    }

    #[test]
    fn test_load_issue_by_display_id_not_found() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let result = writer.load_issue_by_display_id(9999);
        assert!(result.is_err(), "Non-existent issue should return error");
        drop(work_dir);
    }

    #[test]
    fn test_resolve_uuid_for_positive_id() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "UUID resolve", None, "low")
            .unwrap();
        let uuid = writer.resolve_uuid(id, &db).unwrap();

        let issue = writer.load_issue_by_display_id(id).unwrap();
        assert_eq!(uuid, issue.uuid, "Resolved UUID should match issue UUID");
        drop(work_dir);
    }

    #[test]
    fn test_sign_comment_without_key_returns_none() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // No SSH key configured -- sign_comment should return (None, None)
        let (signed_by, signature) = writer.sign_comment("content", "author", 1);
        assert!(signed_by.is_none());
        assert!(signature.is_none());
        drop(work_dir);
    }

    #[test]
    fn test_create_envelope_without_signing() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let event = crate::events::Event::IssueCreated {
            uuid: Uuid::new_v4(),
            title: "test".to_string(),
            description: None,
            priority: "low".to_string(),
            labels: vec![],
            parent_uuid: None,
            created_by: "test-agent".to_string(),
        };
        let envelope = writer.create_envelope(event);
        assert_eq!(envelope.agent_id, "test-agent");
        assert!(envelope.signature.is_none(), "No signature without key");
        assert!(envelope.signed_by.is_none(), "No signed_by without key");
        assert_eq!(envelope.agent_seq, 1, "First event should have seq 1");
        drop(work_dir);
    }

    #[test]
    fn test_next_event_seq_increments() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let s1 = writer.next_event_seq();
        let s2 = writer.next_event_seq();
        let s3 = writer.next_event_seq();

        assert_eq!(s1 + 1, s2);
        assert_eq!(s2 + 1, s3);
        drop(work_dir);
    }

    #[test]
    fn test_find_offline_issues_empty_when_all_have_ids() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Create issues normally (they get display IDs)
        writer.create_issue(&db, "Normal 1", None, "low").unwrap();
        writer.create_issue(&db, "Normal 2", None, "low").unwrap();

        // find_offline_issues should return empty since all have display_id
        let offline = writer.find_offline_issues().unwrap();
        assert!(
            offline.is_empty(),
            "No offline issues expected when all have display IDs"
        );
        drop(work_dir);
    }

    #[test]
    fn test_claim_display_id_uses_correct_starting_value() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let (first, counters) = writer.claim_display_id(1).unwrap();
        assert_eq!(first, 1, "First claimed ID should be 1");
        assert_eq!(
            counters.next_display_id, 2,
            "After claiming 1, next should be 2"
        );
        drop(work_dir);
    }

    #[test]
    fn test_claim_display_id_bulk() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let (first, counters) = writer.claim_display_id(5).unwrap();
        assert_eq!(first, 1);
        assert_eq!(
            counters.next_display_id, 6,
            "After claiming 5, next should be 6"
        );
        drop(work_dir);
    }

    #[test]
    fn test_claim_milestone_id() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let (id, counters) = writer.claim_milestone_id().unwrap();
        assert_eq!(id, 1, "First milestone ID should be 1");
        assert_eq!(counters.next_milestone_id, 2);
        drop(work_dir);
    }

    /// Regression: `claim_display_id` must not hand out an ID that
    /// already belongs to an existing issue file, even when
    /// `counters.json` is stale. Simulates a freshly-cloned repo
    /// whose hub branch contains closed issues but whose local
    /// `counters.json` still reports `next_display_id = 1`.
    #[test]
    fn test_claim_display_id_reconciles_against_stale_counter() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Simulate: issues directory already contains higher-ID files
        // (from a hub branch that was synced but whose counters.json
        // was never updated — e.g., a closed issue preserved from a
        // prior session).
        let issues_dir = writer.sync.cache_path().join("issues");
        std::fs::create_dir_all(&issues_dir).unwrap();
        let stale = make_issue(100, "closed-from-hub");
        write_issue_file(&issues_dir.join(format!("{}.json", stale.uuid)), &stale).unwrap();

        // counters.json still at the default (next_display_id = 1).
        let counters = writer.read_counters().unwrap();
        assert_eq!(
            counters.next_display_id, 1,
            "precondition: counter is stale"
        );

        // Claim — the reconciler should jump ahead past the existing
        // max so the new ID does not collide.
        let (first, updated) = writer.claim_display_id(1).unwrap();
        assert_eq!(first, 101, "first claim must be past the max existing ID");
        assert_eq!(updated.next_display_id, 102);
        drop(work_dir);
    }

    /// Regression: the reconciler must walk both V1 and V2 layouts.
    #[test]
    fn test_claim_display_id_reconciles_across_v1_and_v2_layouts() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let issues_dir = writer.sync.cache_path().join("issues");
        std::fs::create_dir_all(&issues_dir).unwrap();

        // V1 layout: issues/{uuid}.json
        let v1 = make_issue(50, "v1-issue");
        write_issue_file(&issues_dir.join(format!("{}.json", v1.uuid)), &v1).unwrap();

        // V2 layout: issues/{uuid}/issue.json with a HIGHER display_id
        let v2 = make_issue(200, "v2-issue");
        let v2_dir = issues_dir.join(v2.uuid.to_string());
        std::fs::create_dir_all(&v2_dir).unwrap();
        write_issue_file(&v2_dir.join("issue.json"), &v2).unwrap();

        let (first, _) = writer.claim_display_id(1).unwrap();
        assert_eq!(
            first, 201,
            "reconciler must see the highest ID across both layouts"
        );
        drop(work_dir);
    }

    /// When the counter is already ahead of the cache (the normal
    /// steady-state case), reconciliation must NOT decrease it.
    /// Otherwise a successful push that bumped the counter could be
    /// silently undone on the next claim.
    #[test]
    fn test_claim_display_id_does_not_regress_advanced_counter() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Advance the counter well beyond any files on disk.
        let mut counters = writer.read_counters().unwrap();
        counters.next_display_id = 500;
        writer.write_counters_to_cache(&counters).unwrap();

        // Add a few issue files with much lower IDs.
        let issues_dir = writer.sync.cache_path().join("issues");
        std::fs::create_dir_all(&issues_dir).unwrap();
        let low = make_issue(5, "low");
        write_issue_file(&issues_dir.join(format!("{}.json", low.uuid)), &low).unwrap();

        let (first, updated) = writer.claim_display_id(1).unwrap();
        assert_eq!(first, 500, "counter must not be regressed by older files");
        assert_eq!(updated.next_display_id, 501);
        drop(work_dir);
    }

    /// Regression: `claim_milestone_id` has the same potential
    /// collision; verify the parallel reconciler fixes it.
    #[test]
    fn test_claim_milestone_id_reconciles_against_stale_counter() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Seed meta/milestones/ with a pre-existing milestone file.
        let milestones_dir = writer.sync.cache_path().join("meta").join("milestones");
        std::fs::create_dir_all(&milestones_dir).unwrap();
        let ms_uuid = Uuid::new_v4();
        let milestone = crate::issue_file::MilestoneEntry {
            uuid: ms_uuid,
            display_id: 42,
            name: "Q1".to_string(),
            description: None,
            status: IssueStatus::Open,
            created_at: Utc::now(),
            closed_at: None,
        };
        let path = milestones_dir.join(format!("{ms_uuid}.json"));
        std::fs::write(&path, serde_json::to_string_pretty(&milestone).unwrap()).unwrap();

        // counters.json default says next_milestone_id = 1.
        let counters = writer.read_counters().unwrap();
        assert_eq!(counters.next_milestone_id, 1, "precondition: counter stale");

        let (id, updated) = writer.claim_milestone_id().unwrap();
        assert_eq!(id, 43, "milestone id must skip past the existing max");
        assert_eq!(updated.next_milestone_id, 44);
        drop(work_dir);
    }

    #[test]
    fn test_read_max_event_seq_returns_zero_when_no_log() {
        let dir = tempfile::tempdir().unwrap();
        let seq = SharedWriter::read_max_event_seq(dir.path(), "nonexistent-agent");
        assert_eq!(seq, 0, "Max event seq should be 0 when no log exists");
    }

    #[test]
    fn test_layout_version_one_for_v1_hub() {
        let dir = tempfile::tempdir().unwrap();
        let meta_dir = dir.path().join("meta");
        std::fs::create_dir_all(&meta_dir).unwrap();

        // Don't write a version file -> defaults to v1
        let version = crate::issue_file::read_layout_version(&meta_dir).unwrap_or(1);
        assert_eq!(version, 1);
    }

    #[test]
    fn test_write_counters_to_cache() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        let mut counters = writer.read_counters().unwrap();
        counters.next_display_id = 42;
        writer.write_counters_to_cache(&counters).unwrap();

        let reloaded = writer.read_counters().unwrap();
        assert_eq!(reloaded.next_display_id, 42);
        drop(work_dir);
    }

    #[test]
    fn test_push_outcome_eq() {
        assert_eq!(PushOutcome::Pushed, PushOutcome::Pushed);
        assert_eq!(PushOutcome::LocalOnly, PushOutcome::LocalOnly);
        assert_ne!(PushOutcome::Pushed, PushOutcome::LocalOnly);
    }

    #[test]
    fn test_push_outcome_copy() {
        let o = PushOutcome::Pushed;
        let o2 = o; // copy
        assert_eq!(o, o2);
    }

    #[test]
    fn test_max_retries_constant() {
        assert_eq!(MAX_RETRIES, 3);
    }

    // ---- V1 layout coverage ----

    /// Create a V1-layout environment by deleting `meta/version.json` from the hub
    /// cache after normal V2 setup. `layout_version()` returns 1 when this file
    /// is absent, routing `add_comment` / `add_intervention_comment` through the V1
    /// inline-append code paths (lines 679-701, 762-785).
    fn setup_shared_writer_env_v1() -> (TempDir, TempDir, std::path::PathBuf) {
        let (work_dir, remote_dir, crosslink_dir) = setup_shared_writer_env();
        // Remove meta/version.json so layout_version() returns 1
        let version_file = crosslink_dir
            .join(".hub-cache")
            .join("meta")
            .join("version.json");
        if version_file.exists() {
            std::fs::remove_file(&version_file).unwrap();
        }
        (work_dir, remote_dir, crosslink_dir)
    }

    #[test]
    fn test_add_comment_v1_layout() {
        // Exercises lines 679-701: V1 path that appends comment inline to issue.json
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env_v1();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Verify we are in V1 layout
        assert_eq!(
            writer.layout_version(),
            1,
            "Should be V1 layout after version.json removal"
        );

        // In V1 layout, create_issue writes a flat issues/{uuid}.json file.
        let issue_id = writer
            .create_issue(&db, "V1 comment host", None, "medium")
            .unwrap();

        let comment_id = writer
            .add_comment(&db, issue_id, "V1 inline comment", "note")
            .unwrap();

        assert!(comment_id > 0, "Comment ID should be positive");

        // In V1 layout, the comment is stored inline inside issues/{uuid}.json.
        // Verify it appeared in the DB (hydration reads it from the issue file).
        let comments = db.get_comments(issue_id).unwrap();
        assert!(
            !comments.is_empty(),
            "V1 comment should appear in DB after hydration"
        );
        assert_eq!(comments[0].content, "V1 inline comment");

        drop(work_dir);
    }

    #[test]
    fn test_add_intervention_comment_v1_layout() {
        // Exercises lines 762-785: V1 path that appends intervention comment inline.
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env_v1();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        assert_eq!(writer.layout_version(), 1);

        let issue_id = writer
            .create_issue(&db, "V1 intervention host", None, "medium")
            .unwrap();

        let comment_id = writer
            .add_intervention_comment(
                &db,
                issue_id,
                "V1 intervention content",
                "manual_redirect",
                Some("V1 context"),
                None,
            )
            .unwrap();

        assert!(comment_id > 0, "Intervention comment ID should be positive");

        let comments = db.get_comments(issue_id).unwrap();
        assert!(
            !comments.is_empty(),
            "V1 intervention comment should appear in DB"
        );
        assert_eq!(comments[0].content, "V1 intervention content");

        drop(work_dir);
    }

    // ---- SharedWriter::new() anonymous path ----

    #[test]
    fn test_new_without_agent_config_but_hub_already_initialized() {
        // Exercises line 144-145: no agent.json, hub branch already initialized.
        // SharedWriter::new() should return Some with an anonymous config.
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();

        // Remove agent.json so we exercise the anonymous code path
        std::fs::remove_file(crosslink_dir.join("agent.json")).unwrap();

        // Hub cache already exists from setup -- is_initialized() returns true immediately
        let writer = SharedWriter::new(&crosslink_dir).unwrap();
        assert!(
            writer.is_some(),
            "SharedWriter::new() should return Some when hub cache already exists (anonymous mode)"
        );

        let writer = writer.unwrap();
        // Anonymous agent_id starts with "anon-"
        assert!(
            writer.agent_id().starts_with("anon-"),
            "Anonymous writer should have agent_id starting with 'anon-', got: {}",
            writer.agent_id()
        );

        drop(work_dir);
    }

    #[test]
    fn test_new_without_agent_config_hub_init_fails_returns_none() {
        // Exercises lines 138-139: no agent.json, and init_cache() fails because the
        // remote is unreachable (invalid URL), so SharedWriter::new() returns Ok(None).
        let work_dir = tempfile::tempdir().unwrap();

        // Init a git repo with a bogus remote that can't be reached
        Command::new("git")
            .current_dir(work_dir.path())
            .args(["init", "-b", "main"])
            .output()
            .unwrap();

        for args in [
            vec!["config", "user.email", "test@test.local"],
            vec!["config", "user.name", "Test"],
            // Use an invalid remote path so ls-remote / worktree add will fail
            vec!["remote", "add", "origin", "/nonexistent/path/to/remote"],
        ] {
            Command::new("git")
                .current_dir(work_dir.path())
                .args(&args)
                .output()
                .unwrap();
        }

        // Create .crosslink dir with hook-config.json but NO agent.json
        let crosslink_dir = work_dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        std::fs::write(
            crosslink_dir.join("hook-config.json"),
            r#"{"remote":"origin","layout":"v2"}"#,
        )
        .unwrap();

        // No agent.json. The hub cache dir doesn't exist so is_initialized() = false.
        // init_cache() will try to create an orphan worktree. If it does succeed (creating
        // a local orphan) we get Some; if it fails we get None.
        // Either way, the test validates that the code path is reachable and doesn't panic.
        let result = SharedWriter::new(&crosslink_dir);
        // The result should be Ok (no panic), regardless of Some/None depending on git
        assert!(
            result.is_ok(),
            "SharedWriter::new() should not error even when hub unavailable"
        );

        drop(work_dir);
    }

    // ---- resolve_ssh_key_path coverage ----

    #[test]
    fn test_resolve_ssh_key_path_nonexistent_file() {
        // Exercises line 254: ssh_key_path is configured but the file doesn't exist.
        // resolve_ssh_key_path() should return None.
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();

        // Reconfigure agent.json with a key path that doesn't exist on disk
        let agent_config = AgentConfig {
            agent_id: "test-agent".to_string(),
            machine_id: "test-machine".to_string(),
            description: None,
            ssh_key_path: Some("nonexistent_key_file.pem".to_string()),
            ssh_fingerprint: Some("SHA256:fakefingerprint".to_string()),
            ssh_public_key: None,
        };
        let agent_json = serde_json::to_string_pretty(&agent_config).unwrap();
        std::fs::write(crosslink_dir.join("agent.json"), agent_json).unwrap();

        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // The key file doesn't exist -> resolve_ssh_key_path returns None (line 254)
        let resolved = writer.resolve_ssh_key_path();
        assert!(
            resolved.is_none(),
            "resolve_ssh_key_path should return None when file doesn't exist"
        );

        drop(work_dir);
    }

    #[test]
    fn test_resolve_ssh_key_path_existing_file() {
        // Exercises line 251-252: ssh_key_path is configured and file exists.
        // resolve_ssh_key_path() should return Some(path).
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();

        // Create a fake key file inside .crosslink/
        let fake_key_name = "test_agent_key.pem";
        let fake_key_path = crosslink_dir.join(fake_key_name);
        std::fs::write(&fake_key_path, "fake key content").unwrap();

        // Reconfigure agent.json to point at the fake key
        let agent_config = AgentConfig {
            agent_id: "test-agent".to_string(),
            machine_id: "test-machine".to_string(),
            description: None,
            ssh_key_path: Some(fake_key_name.to_string()),
            ssh_fingerprint: Some("SHA256:fakefingerprint".to_string()),
            ssh_public_key: None,
        };
        let agent_json = serde_json::to_string_pretty(&agent_config).unwrap();
        std::fs::write(crosslink_dir.join("agent.json"), agent_json).unwrap();

        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // The key file exists -> resolve_ssh_key_path returns Some
        let resolved = writer.resolve_ssh_key_path();
        assert!(
            resolved.is_some(),
            "resolve_ssh_key_path should return Some when key file exists"
        );
        assert!(
            resolved.unwrap().ends_with(fake_key_name),
            "Resolved path should end with the key filename"
        );

        drop(work_dir);
    }

    // ---- replace_local_refs "after" boundary rejection ----

    #[test]
    fn test_replace_local_refs_after_boundary_rejection() {
        // Exercises line 64: before_ok=true but after_ok=false -> else { i = end_pos }.
        // "L1" appears at start of "L10" -- before boundary OK, but "0" after is alphanumeric.
        let replacements = vec![("L1".to_string(), "#5".to_string())];

        // "L10" -- L1 is followed by "0" (alphanumeric), so the word-boundary check rejects it.
        let result = replace_local_refs("L10 is a thing", &replacements);
        assert!(
            result.is_none(),
            "L1 in L10 should NOT be replaced (after-boundary alphanumeric char)"
        );

        // Mixed: "L10 and L1" -- L10 should not replace, standalone L1 should
        let result = replace_local_refs("L10 and L1 done", &replacements);
        assert_eq!(
            result,
            Some("L10 and #5 done".to_string()),
            "Only standalone L1 should be replaced, not L1 inside L10"
        );

        // At end of string: "L10" -- after end_pos is string end but "0" terminates the match
        let result = replace_local_refs("L10", &replacements);
        assert!(
            result.is_none(),
            "L1 at start of L10 (entire string) should NOT be replaced"
        );
    }

    // --- claim_lock_v2() / release_lock_v2() ---
    // Exercises emit_compact_push() path (lines 286-360)

    #[test]
    fn test_claim_lock_v2_succeeds() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Lock target", None, "medium")
            .unwrap();

        let result = writer.claim_lock_v2(id, Some("feature/test")).unwrap();
        assert_eq!(result, LockClaimResult::Claimed);
        drop(work_dir);
    }

    #[test]
    fn test_claim_lock_v2_already_held() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Lock target 2", None, "medium")
            .unwrap();

        writer.claim_lock_v2(id, None).unwrap();

        // Claim again -- should return AlreadyHeld
        let result = writer.claim_lock_v2(id, None).unwrap();
        assert_eq!(result, LockClaimResult::AlreadyHeld);
        drop(work_dir);
    }

    #[test]
    fn test_release_lock_v2_held() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Lock release", None, "medium")
            .unwrap();
        writer.claim_lock_v2(id, None).unwrap();

        let released = writer.release_lock_v2(id).unwrap();
        assert!(released, "Should release own lock");
        drop(work_dir);
    }

    #[test]
    fn test_release_lock_v2_not_locked() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();

        // Issue ID 999 doesn't exist / isn't locked
        let released = writer.release_lock_v2(999).unwrap();
        assert!(!released, "Releasing non-existent lock returns false");
        drop(work_dir);
    }

    #[test]
    fn test_steal_lock_v2() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Steal target", None, "medium")
            .unwrap();
        writer.claim_lock_v2(id, None).unwrap();

        // Steal the lock (pretending the owner is stale)
        let result = writer
            .steal_lock_v2(id, "test-agent", Some("feature/steal"))
            .unwrap();
        assert_eq!(result, LockClaimResult::Claimed);
        drop(work_dir);
    }

    // --- rewrite_local_references() additional ---

    #[test]
    fn test_rewrite_local_references_rewrites_description() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Create an issue with a description referencing L1
        let id = writer
            .create_issue(&db, "Rewrite test", Some("See L1 for details"), "medium")
            .unwrap();

        // Mapping: neg_id=-1 -> new_id=id, simulate promotion
        let mapping = vec![(-1i64, id, "Rewrite test".to_string())];
        let stats = writer.rewrite_local_references(&db, &mapping).unwrap();

        assert_eq!(stats.descriptions_updated, 1);

        let issue = db.get_issue(id).unwrap().unwrap();
        assert!(
            issue
                .description
                .as_deref()
                .unwrap()
                .contains(&format!("#{id}")),
            "L1 should be rewritten to #{id}"
        );
        drop(work_dir);
    }

    #[test]
    fn test_rewrite_local_references_rewrites_comments() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "Comment rewrite", None, "medium")
            .unwrap();
        writer
            .add_comment(&db, id, "Related to L2", "observation")
            .unwrap();

        let mapping = vec![(-2i64, id, "Comment rewrite".to_string())];
        let stats = writer.rewrite_local_references(&db, &mapping).unwrap();

        assert_eq!(stats.comments_updated, 1);
        drop(work_dir);
    }

    #[test]
    fn test_rewrite_local_references_no_refs_no_changes() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        let id = writer
            .create_issue(&db, "No refs", Some("Plain description"), "medium")
            .unwrap();

        let mapping = vec![(-1i64, id, "No refs".to_string())];
        let stats = writer.rewrite_local_references(&db, &mapping).unwrap();

        assert_eq!(stats.descriptions_updated, 0);
        assert_eq!(stats.comments_updated, 0);
        drop(work_dir);
    }

    // --- SharedWriter::new() anonymous path ---

    #[test]
    fn test_new_without_agent_json_and_no_hub() {
        let dir = tempfile::tempdir().unwrap();
        let crosslink_dir = dir.path().join(".crosslink");
        std::fs::create_dir_all(&crosslink_dir).unwrap();
        std::fs::write(
            crosslink_dir.join("hook-config.json"),
            r#"{"remote":"origin"}"#,
        )
        .unwrap();

        // No agent.json, no hub branch -> should return None
        let result = SharedWriter::new(&crosslink_dir).unwrap();
        assert!(result.is_none());
    }

    // --- promote_offline_issues() with actual offline issues ---

    #[test]
    fn test_promote_offline_issues_with_offline_issue() {
        let (work_dir, _remote, crosslink_dir) = setup_shared_writer_env();
        let writer = SharedWriter::new(&crosslink_dir).unwrap().unwrap();
        let db = make_db(work_dir.path());

        // Manually create an offline issue (display_id: null, created_by: test-agent)
        let uuid = uuid::Uuid::new_v4();
        let now = chrono::Utc::now();
        let issue = crate::issue_file::IssueFile {
            uuid,
            display_id: None,
            title: "Offline issue".to_string(),
            description: None,
            status: IssueStatus::Open,
            priority: Priority::Medium,
            parent_uuid: None,
            created_by: "test-agent".to_string(),
            created_at: now,
            updated_at: now,
            closed_at: None,
            labels: vec![],
            comments: vec![],
            blockers: vec![],
            related: vec![],
            milestone_uuid: None,
            time_entries: vec![],
        };

        // Write it in V2 format (issues/{uuid}/issue.json)
        let cache_dir = crosslink_dir.join(".hub-cache");
        let issue_dir = cache_dir.join("issues").join(uuid.to_string());
        std::fs::create_dir_all(&issue_dir).unwrap();
        let json = serde_json::to_string_pretty(&issue).unwrap();
        std::fs::write(issue_dir.join("issue.json"), &json).unwrap();

        // Also git add + commit so the cache is clean
        writer
            .git_in_cache(&["add", &format!("issues/{uuid}/issue.json")])
            .unwrap();
        let _ = writer.git_in_cache(&["commit", "-m", "add offline issue", "--no-gpg-sign"]);

        // Now promote
        let mapping = writer.promote_offline_issues(&db).unwrap();
        assert_eq!(mapping.len(), 1, "Should promote exactly 1 issue");
        let (_neg_id, new_id, title) = &mapping[0];
        assert_eq!(title, "Offline issue");
        assert!(*new_id > 0, "New display ID should be positive");

        // write_commit_push writes the promoted file in V1 format
        // (issues/{uuid}.json) regardless of layout version
        let v1_file = cache_dir.join("issues").join(format!("{uuid}.json"));
        if v1_file.exists() {
            let content = std::fs::read_to_string(&v1_file).unwrap();
            let updated: crate::issue_file::IssueFile = serde_json::from_str(&content).unwrap();
            assert!(
                updated.display_id.is_some(),
                "display_id should be set after promotion"
            );
        }

        drop(work_dir);
    }
}