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
// ── Crate-level clippy configuration ────────────────────────────────────────
#![warn(clippy::pedantic, clippy::nursery)]
// Impractical to add `# Errors` doc sections to 300+ fallible functions retroactively.
#![allow(clippy::missing_errors_doc)]
// Panic doc sections are similarly impractical at scale.
#![allow(clippy::missing_panics_doc)]
// `Self` vs type name in return position is a style preference; current naming is clear.
#![allow(clippy::use_self)]
// Field/module name repetition (e.g. `IssueStatus` inside `issue` module) is intentional.
#![allow(clippy::module_name_repetitions)]
// Long functions are an architectural concern, not a lint fix.
#![allow(clippy::too_many_lines)]
// Similar variable names (e.g. `src`/`dst`, `old`/`new`) are often intentional.
#![allow(clippy::similar_names)]
// Items after statements is common in test code and builder patterns.
#![allow(clippy::items_after_statements)]
// Wildcard imports are idiomatic in test modules.
#![allow(clippy::wildcard_imports)]
// `must_use` on every pure function is too noisy for a CLI app.
#![allow(clippy::must_use_candidate)]
// Drop tightening suggestions often make code less readable.
#![allow(clippy::significant_drop_tightening)]
// Cast lints: numeric casts are context-dependent and reviewed at write time.
#![allow(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    clippy::cast_precision_loss,
    clippy::cast_possible_wrap,
    clippy::cast_lossless
)]
// pub(crate) inside private modules is harmless and matches intent.
#![allow(clippy::redundant_pub_crate)]
// Struct field naming is a style preference.
#![allow(clippy::struct_field_names)]
// Bool params: sometimes clearer than a dedicated enum for 2-3 bools.
#![allow(clippy::struct_excessive_bools, clippy::fn_params_excessive_bools)]
// Option<&T> vs &Option<T>: both are valid depending on context.
#![allow(clippy::ref_option)]
// Large stack arrays in test code: `vec![...]` literals expand to array literals
// internally, and clippy can't trace the span back through macro expansion to
// suggest a fix. Test code where stack frame size doesn't matter for production.
// See https://github.com/rust-lang/rust-clippy/issues for the underlying span bug.
#![allow(clippy::large_stack_arrays)]

mod checkpoint;
mod clock_skew;
mod commands;
mod compaction;
mod daemon;
mod db;
mod events;
mod external;
mod findings;
mod hydration;
mod identity;
mod issue_file;
mod issue_filing;
mod knowledge;
mod lock_check;
mod locks;
mod models;
mod orchestrator;
mod pipeline;
mod seam;
mod server;
mod shared_writer;
mod signing;
mod sync;
mod trust_model;
mod tui;
mod utils;

use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use std::env;
use std::path::PathBuf;

use db::Database;

#[derive(Parser)]
#[command(name = "crosslink")]
#[command(about = "A simple, lean issue tracker CLI")]
#[command(version = option_env!("CROSSLINK_VERSION").unwrap_or(env!("CARGO_PKG_VERSION")))]
struct Cli {
    /// Quiet mode: only output essential data (IDs, counts)
    #[arg(short, long, global = true)]
    quiet: bool,

    /// Output as JSON (supported by list, show, search, session status)
    #[arg(long, global = true)]
    json: bool,

    /// Log level for diagnostic output (error, warn, info, debug, trace)
    #[arg(long, global = true, default_value = "warn", env = "CROSSLINK_LOG")]
    log_level: String,

    /// Log format (text, json)
    #[arg(
        long,
        global = true,
        default_value = "text",
        env = "CROSSLINK_LOG_FORMAT"
    )]
    log_format: String,

    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Initialize crosslink in the current directory.
    ///
    /// On first run, launches an interactive walkthrough to choose a preset
    /// (Team, Solo, or Custom) and configure behavioral hooks. Use --defaults
    /// to skip the walkthrough and apply team-mode defaults non-interactively.
    Init {
        /// Force update hooks even if already initialized
        #[arg(short, long, conflicts_with = "update")]
        force: bool,
        /// Safe upgrade: update managed files using manifest-tracked three-way merge
        #[arg(long, conflicts_with_all = ["force", "reconfigure"])]
        update: bool,
        /// Show what --update would change without writing anything
        #[arg(long, requires = "update")]
        dry_run: bool,
        /// Skip conflict prompts — silently keep user-modified files (for CI)
        #[arg(long, requires = "update")]
        no_prompt: bool,
        /// Override auto-detected Python prefix for hook commands (e.g. "uv run python3")
        #[arg(long)]
        python_prefix: Option<String>,
        /// Skip automatic cpitd installation
        #[arg(long)]
        skip_cpitd: bool,
        /// Skip driver SSH signing key setup
        #[arg(long)]
        skip_signing: bool,
        /// Path to SSH key for commit signing (auto-detected if omitted)
        #[arg(long)]
        signing_key: Option<String>,
        /// Re-run TUI walkthrough even if config exists
        #[arg(long, conflicts_with = "update")]
        reconfigure: bool,
        /// Skip TUI and use opinionated team-mode defaults
        #[arg(long)]
        defaults: bool,
    },

    /// Issue lifecycle commands (create, show, list, close, ...)
    Issue {
        #[command(subcommand)]
        action: IssueCommands,
    },

    /// Time tracking (start, stop, show)
    Timer {
        #[command(subcommand)]
        action: TimerCommands,
    },

    /// Export issues to JSON or markdown
    Export {
        /// Output file path (defaults to stdout)
        #[arg(short, long)]
        output: Option<String>,
        /// Format (json, markdown)
        #[arg(short, long, default_value = "json")]
        format: String,
    },

    /// Import issues from JSON file
    Import {
        /// Input file path
        input: String,
    },

    /// Archive management
    Archive {
        #[command(subcommand)]
        action: ArchiveCommands,
    },

    /// Milestone management
    Milestone {
        #[command(subcommand)]
        action: MilestoneCommands,
    },

    /// Session management
    Session {
        #[command(subcommand)]
        action: SessionCommands,
    },

    /// Daemon management
    Daemon {
        #[command(subcommand)]
        action: DaemonCommands,
    },

    /// Code clone detection via cpitd
    Cpitd {
        #[command(subcommand)]
        action: CpitdCommands,
    },

    /// Agent identity management
    Agent {
        #[command(subcommand)]
        action: AgentCommands,
    },

    /// Manage signing trust (approve/revoke agent keys)
    Trust {
        #[command(subcommand)]
        action: TrustCommands,
    },

    /// View and manage issue locks
    Locks {
        #[command(subcommand)]
        action: LocksCommands,
    },

    /// Push a heartbeat for the current agent (used by hooks)
    #[command(hide = true)]
    Heartbeat,

    /// Sync locks and issue state from remote
    Sync,

    /// Schema migration (to-shared, from-shared, rename-branch)
    Migrate {
        #[command(subcommand)]
        action: MigrateCommands,
    },

    /// View and modify repo-level configuration.
    ///
    /// Without a subcommand, opens the interactive walkthrough to choose a
    /// preset (Team, Solo, or Custom) and adjust settings. Use --preset to
    /// apply a preset directly without the TUI.
    Config {
        #[command(subcommand)]
        command: Option<ConfigCommands>,

        /// Apply a preset without the TUI: "team" (strict tracking, CI
        /// verification, enforced signing) or "solo" (relaxed tracking,
        /// local verification, signing disabled)
        #[arg(long)]
        preset: Option<String>,
    },

    /// Measure and check context injection overhead
    Context {
        #[command(subcommand)]
        command: ContextCommands,
    },

    /// Manage crosslink workflow configuration
    Workflow {
        #[command(subcommand)]
        command: WorkflowCommands,
    },

    /// Manage house style syncing
    Style {
        #[command(subcommand)]
        command: StyleCommands,
    },

    /// Manage shared knowledge pages
    Knowledge {
        #[command(subcommand)]
        command: KnowledgeCommands,
    },

    /// Data integrity checks and repair
    Integrity {
        #[command(subcommand)]
        action: Option<IntegrityCommands>,
    },

    /// Run event compaction manually
    Compact {
        /// Force compaction even if lease is held by another agent
        #[arg(long)]
        force: bool,
    },

    /// Prune git history of hub and knowledge branches for storage efficiency
    Prune {
        /// Show what would be pruned without modifying anything
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Skip confirmation and execute the prune
        #[arg(long)]
        force: bool,
        /// Preserve the last N commits (default: 1, squash to current state)
        #[arg(long = "keep-commits", default_value = "1")]
        keep_commits: usize,
        /// Only prune the hub branch
        #[arg(long = "hub-only")]
        hub_only: bool,
        /// Only prune the knowledge branch
        #[arg(long = "knowledge-only")]
        knowledge_only: bool,
    },

    /// Launch an agent to implement a feature (local process or container)
    Kickoff {
        #[command(subcommand)]
        action: Option<KickoffCommands>,
    },
    /// Launch a foreground Claude session for design document authoring
    Design {
        /// Feature description (e.g. "add batch retry logic")
        description: Option<String>,
        /// Pull context from a crosslink issue
        #[arg(long)]
        issue: Option<i64>,
        /// Pull context from a GitHub issue
        #[arg(long = "gh-issue")]
        gh_issue: Option<i64>,
        /// Resume iteration on an existing draft (.design/<slug>.md)
        #[arg(long = "continue", value_name = "SLUG")]
        continue_slug: Option<String>,
    },
    /// Multi-agent swarm coordination (plan, status, resume)
    Swarm {
        #[command(subcommand)]
        action: SwarmCommands,
    },
    /// Autonomous maintenance sentinel (monitors sources, dispatches agents)
    Sentinel {
        #[command(subcommand)]
        action: SentinelCommands,
    },
    /// Interactive terminal dashboard (read-only)
    Tui,
    /// Mission control: tmux dashboard showing all active agents
    #[command(alias = "mission-control")]
    Mc {
        /// Panel layout: tiled, even-horizontal, even-vertical
        #[arg(long, default_value = "tiled")]
        layout: String,
    },
    /// Start the crosslink web dashboard server
    Serve {
        /// Port to listen on
        #[arg(long, default_value = "3100")]
        port: u16,
        /// Directory to serve the React dashboard from (optional)
        #[arg(long)]
        dashboard_dir: Option<PathBuf>,
    },
    /// Manage container-based agent execution
    Container {
        #[command(subcommand)]
        action: ContainerCommands,
    },

    // === Hidden top-level shortcuts (delegate to `issue <verb>`) ===
    /// Create a new issue (shortcut for `issue create`)
    #[command(hide = true)]
    Create {
        /// Issue title
        title: String,
        /// Issue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Template (bug, feature, refactor, research)
        #[arg(short, long)]
        template: Option<String>,
        /// Add labels to the issue
        #[arg(short, long)]
        label: Vec<String>,
        /// Set as current session work item
        #[arg(short, long)]
        work: bool,
        /// Skip compaction after creation (batch mode -- display ID assigned later)
        #[arg(long)]
        defer_id: bool,
        /// Parent issue ID (creates a subissue)
        #[arg(long, value_parser = parse_issue_id_clap)]
        parent: Option<i64>,
    },

    /// Quick-create an issue (shortcut for `issue quick`)
    #[command(hide = true)]
    Quick {
        /// Issue title
        title: String,
        /// Issue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Template (bug, feature, refactor, research)
        #[arg(short, long)]
        template: Option<String>,
        /// Add labels to the issue
        #[arg(short, long)]
        label: Vec<String>,
        /// Parent issue ID (creates a subissue)
        #[arg(long, value_parser = parse_issue_id_clap)]
        parent: Option<i64>,
    },

    /// List issues (shortcut for `issue list`)
    #[command(hide = true)]
    List {
        /// Filter by status (open, closed, all)
        #[arg(short, long, default_value = "open")]
        status: String,
        /// Filter by label
        #[arg(short, long)]
        label: Option<String>,
        /// Filter by priority
        #[arg(short, long)]
        priority: Option<String>,
    },

    /// Show issue details (shortcut for `issue show`)
    #[command(hide = true)]
    Show {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },

    /// Close an issue (shortcut for `issue close`)
    #[command(hide = true)]
    Close {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Skip changelog entry
        #[arg(long)]
        no_changelog: bool,
    },

    // === Hidden aliases for common agent mistakes ===
    /// Alias for `issue create`
    #[command(hide = true)]
    New {
        /// Issue title
        title: String,
        /// Issue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Template (bug, feature, refactor, research)
        #[arg(short, long)]
        template: Option<String>,
        /// Add labels to the issue
        #[arg(short, long)]
        label: Vec<String>,
        /// Set as current session work item
        #[arg(short, long)]
        work: bool,
        /// Parent issue ID (creates a subissue)
        #[arg(long, value_parser = parse_issue_id_clap)]
        parent: Option<i64>,
    },

    /// Alias for `issue list`
    #[command(hide = true)]
    Issues {
        #[command(subcommand)]
        action: Option<IssuesAliasCommands>,
    },

    /// Alias for `issue create --parent`
    #[command(hide = true)]
    Subissue {
        /// Parent issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        parent: i64,
        /// Subissue title
        title: String,
        /// Subissue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Add labels to the subissue
        #[arg(short, long)]
        label: Vec<String>,
        /// Set as current session work item
        #[arg(short, long)]
        work: bool,
    },

    /// Alias for `timer start`
    #[command(hide = true, name = "start")]
    TimerStart {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },

    /// Alias for `timer stop`
    #[command(hide = true, name = "stop")]
    TimerStop,

    // === Hidden migration aliases ===
    /// Alias for `migrate to-shared`
    #[command(hide = true, name = "migrate-to-shared")]
    MigrateToShared,

    /// Alias for `migrate from-shared`
    #[command(hide = true, name = "migrate-from-shared")]
    MigrateFromShared,

    /// Alias for `migrate rename-branch`
    #[command(hide = true, name = "migrate-rename-branch")]
    MigrateRenameBranch,
}

/// Issue lifecycle subcommands
#[derive(Subcommand)]
enum IssueCommands {
    /// Create a new issue
    Create {
        /// Issue title
        title: String,
        /// Issue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Template (bug, feature, refactor, research)
        #[arg(short, long)]
        template: Option<String>,
        /// Add labels to the issue
        #[arg(short, long)]
        label: Vec<String>,
        /// Set as current session work item
        #[arg(short, long)]
        work: bool,
        /// Skip compaction after creation (batch mode -- display ID assigned later)
        #[arg(long)]
        defer_id: bool,
        /// Parent issue ID (creates a subissue)
        #[arg(long, value_parser = parse_issue_id_clap)]
        parent: Option<i64>,
    },

    /// Quick-create an issue and start working on it (create + label + session work)
    Quick {
        /// Issue title
        title: String,
        /// Issue description
        #[arg(short, long)]
        description: Option<String>,
        /// Priority (low, medium, high, critical)
        #[arg(short, long, default_value = "medium")]
        priority: String,
        /// Template (bug, feature, refactor, research)
        #[arg(short, long)]
        template: Option<String>,
        /// Add labels to the issue
        #[arg(short, long)]
        label: Vec<String>,
        /// Parent issue ID (creates a subissue)
        #[arg(long, value_parser = parse_issue_id_clap)]
        parent: Option<i64>,
    },

    /// List issues
    List {
        /// Filter by status (open, closed, all)
        #[arg(short, long, default_value = "open")]
        status: String,
        /// Filter by label
        #[arg(short, long)]
        label: Option<String>,
        /// Filter by priority
        #[arg(short, long)]
        priority: Option<String>,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },

    /// Search issues by text
    Search {
        /// Search query
        query: String,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },

    /// Show issue details
    Show {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },

    /// Update an issue
    Update {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// New title
        #[arg(short, long)]
        title: Option<String>,
        /// New description
        #[arg(short, long)]
        description: Option<String>,
        /// New priority
        #[arg(short, long)]
        priority: Option<String>,
    },

    /// Close an issue
    Close {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Skip changelog entry
        #[arg(long)]
        no_changelog: bool,
    },

    /// Close all issues matching filters
    CloseAll {
        /// Filter by label
        #[arg(short, long)]
        label: Option<String>,
        /// Filter by priority
        #[arg(short, long)]
        priority: Option<String>,
        /// Skip changelog entries
        #[arg(long)]
        no_changelog: bool,
    },

    /// Reopen a closed issue
    Reopen {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },

    /// Delete an issue
    Delete {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Skip confirmation
        #[arg(short, long)]
        force: bool,
    },

    /// Add a comment to an issue
    Comment {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Comment text
        text: String,
        /// Comment kind (note, plan, decision, observation, blocker, resolution, result, handoff, human)
        #[arg(long, default_value = "note")]
        kind: String,
    },

    /// Log a driver intervention on an issue
    Intervene {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Description of the intervention
        description: String,
        /// Trigger type (`tool_rejected`, `tool_blocked`, `redirect`, `context_provided`, `manual_action`, `question_answered`)
        #[arg(long)]
        trigger: String,
        /// Context: what the agent was attempting when intervention occurred
        #[arg(long)]
        context: Option<String>,
    },

    /// Add a label to an issue
    Label {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Label name
        label: String,
    },

    /// Remove a label from an issue
    Unlabel {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Label name
        label: String,
    },

    /// Mark an issue as blocked by another
    Block {
        /// Issue ID that is blocked
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Issue ID that is blocking
        #[arg(value_parser = parse_issue_id_clap)]
        blocker: i64,
    },

    /// Remove a blocking relationship
    Unblock {
        /// Issue ID that was blocked
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Issue ID that was blocking
        #[arg(value_parser = parse_issue_id_clap)]
        blocker: i64,
    },

    /// List blocked issues
    Blocked,

    /// List issues ready to work on (no open blockers)
    Ready,

    /// Link two related issues
    Relate {
        /// First issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Second issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        related: i64,
    },

    /// Remove a relation between issues
    Unrelate {
        /// First issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Second issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        related: i64,
    },

    /// List related issues
    Related {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },

    /// Suggest the next issue to work on
    Next,

    /// Show issues as a tree hierarchy
    Tree {
        /// Filter by status (open, closed, all)
        #[arg(short, long, default_value = "all")]
        status: String,
    },

    /// Mark tests as run (resets test reminder)
    Tested,
}

/// Timer subcommands
#[derive(Subcommand)]
enum TimerCommands {
    /// Start a timer for an issue
    Start {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// Stop the current timer
    Stop,
    /// Show current timer status
    Show,
}

/// Migration subcommands
#[derive(Subcommand)]
enum MigrateCommands {
    /// Migrate local `SQLite` issues to shared coordination branch
    ToShared,
    /// Import shared issues from coordination branch into local `SQLite`
    FromShared,
    /// Rename coordination branch from crosslink/locks to crosslink/hub
    RenameBranch,
}

/// Helper enum for `crosslink issues <subcommand>` alias
#[derive(Subcommand)]
enum IssuesAliasCommands {
    /// Alias for `issue list`
    List {
        /// Filter by status (open, closed, all)
        #[arg(short, long, default_value = "open")]
        status: String,
        /// Filter by label
        #[arg(short, long)]
        label: Option<String>,
        /// Filter by priority
        #[arg(short, long)]
        priority: Option<String>,
    },
}

#[derive(Subcommand)]
enum ContainerCommands {
    /// Build the crosslink agent container image
    Build {
        /// Rebuild from scratch (no cache)
        #[arg(long)]
        force: bool,
        /// Image tag (default: latest)
        #[arg(long)]
        tag: Option<String>,
        /// Path to a custom Dockerfile
        #[arg(long)]
        dockerfile: Option<String>,
    },
    /// Start a task container for a worktree
    Start {
        /// Path to the worktree directory
        worktree: String,
        /// Container name (default: derived from worktree slug)
        #[arg(long)]
        name: Option<String>,
        /// Path to the prompt file (default: KICKOFF.md in worktree)
        #[arg(long)]
        prompt: Option<String>,
        /// Crosslink issue ID being worked on
        #[arg(long)]
        issue: Option<i64>,
        /// Memory limit (default: auto-detect from host)
        #[arg(long)]
        memory: Option<String>,
    },
    /// List running task containers
    Ps,
    /// Stream logs from a container
    Logs {
        /// Container name
        name: String,
        /// Follow log output
        #[arg(short, long)]
        follow: bool,
        /// Number of lines to show (default: 100)
        #[arg(long)]
        tail: Option<u32>,
    },
    /// Stop a running container
    Stop {
        /// Container name
        name: String,
    },
    /// Remove a stopped container
    Rm {
        /// Container name
        name: String,
    },
    /// Stop and remove a container
    Kill {
        /// Container name
        name: String,
    },
    /// Open a shell inside a running container
    Shell {
        /// Container name
        name: String,
    },
    /// Snapshot a container as a cached image (preserves installed toolchains)
    Snapshot {
        /// Container name
        name: String,
        /// Image tag for the snapshot (default: cached)
        #[arg(long)]
        tag: Option<String>,
    },
}

#[derive(Subcommand, Clone, Copy)]
enum ArchiveCommands {
    /// Archive a closed issue
    Add {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// Unarchive an issue (restore to closed)
    Remove {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// List archived issues
    List,
    /// Archive all issues closed more than N days ago
    Older {
        /// Days threshold
        days: i64,
    },
}

#[derive(Subcommand)]
enum MilestoneCommands {
    /// Create a new milestone
    Create {
        /// Milestone name
        name: String,
        /// Description
        #[arg(short, long)]
        description: Option<String>,
    },
    /// List milestones
    List {
        /// Filter by status (open, closed, all)
        #[arg(short, long, default_value = "open")]
        status: String,
    },
    /// Show milestone details
    Show {
        /// Milestone ID
        id: i64,
    },
    /// Add issues to a milestone
    Add {
        /// Milestone ID
        id: i64,
        /// Issue IDs to add
        issues: Vec<i64>,
    },
    /// Remove an issue from a milestone
    Remove {
        /// Milestone ID
        id: i64,
        /// Issue ID to remove
        issue: i64,
    },
    /// Close a milestone
    Close {
        /// Milestone ID
        id: i64,
    },
    /// Delete a milestone
    Delete {
        /// Milestone ID
        id: i64,
    },
}

#[derive(Subcommand)]
enum SessionCommands {
    /// Start a new session
    Start,
    /// End the current session
    End {
        /// Handoff notes for the next session
        #[arg(short, long)]
        notes: Option<String>,
    },
    /// Show current session status
    Status,
    /// Set the issue being worked on
    Work {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// Show handoff notes from the previous session
    LastHandoff,
    /// Record last action for context compression breadcrumbs
    Action {
        /// Description of what you just did or are doing
        text: String,
    },
}

#[derive(Subcommand)]
enum CpitdCommands {
    /// Scan for code clones and create issues
    Scan {
        /// Paths to scan (defaults to current directory)
        paths: Vec<String>,
        /// Minimum token sequence length to report
        #[arg(long, default_value = "50")]
        min_tokens: u32,
        /// Glob patterns to exclude (repeatable)
        #[arg(long)]
        ignore: Vec<String>,
        /// Show what would be created without creating issues
        #[arg(long = "dry-run")]
        dry_run: bool,
    },
    /// Show open clone issues
    Status,
    /// Close all open clone issues
    Clear,
}

#[derive(Subcommand)]
enum DaemonCommands {
    /// Start the background daemon
    Start,
    /// Stop the background daemon
    Stop,
    /// Check daemon status
    Status,
    /// Internal: run the daemon loop (used by start)
    #[command(hide = true)]
    Run {
        #[arg(long)]
        dir: PathBuf,
    },
}

#[derive(Subcommand)]
enum AgentCommands {
    /// Initialize agent identity on this machine
    Init {
        /// Agent ID (alphanumeric, hyphens, underscores)
        agent_id: String,
        /// Agent description
        #[arg(short, long)]
        description: Option<String>,
        /// Skip SSH key generation
        #[arg(long)]
        no_key: bool,
        /// Overwrite existing agent configuration
        #[arg(long)]
        force: bool,
    },
    /// Show current agent identity
    Status,
    /// Send a prompt to a running tmux-based agent session
    Prompt {
        /// Agent slug or tmux session name
        session: String,
        /// Prompt text to send (supports multiline)
        message: String,
        /// Don't press Enter after pasting (just type, don't submit)
        #[arg(long)]
        no_submit: bool,
    },
    /// Bootstrap agent identity in a new or existing repo clone
    Bootstrap {
        /// Git repository URL to clone
        #[arg(long)]
        repo: String,
        /// Agent ID (alphanumeric, hyphens, underscores)
        #[arg(long)]
        identity: String,
        /// Branch to checkout after cloning
        #[arg(long)]
        branch: Option<String>,
        /// Agent description
        #[arg(short, long)]
        description: Option<String>,
        /// Skip SSH key generation
        #[arg(long)]
        no_key: bool,
        /// Target directory (default: current directory)
        #[arg(long, default_value = ".")]
        target: String,
    },
}

#[derive(Subcommand)]
enum TrustCommands {
    /// Approve an agent's signing key
    Approve {
        /// Agent ID to approve
        agent_id: String,
    },
    /// Revoke an agent's signing key
    Revoke {
        /// Agent ID to revoke
        agent_id: String,
    },
    /// List all trusted signers
    List,
    /// Show agent keys awaiting approval
    Pending,
    /// Check trust status of a specific agent
    Check {
        /// Agent ID to check
        agent_id: String,
    },
}

#[derive(Subcommand)]
enum LocksCommands {
    /// List all active locks
    List,
    /// Check if a specific issue is locked
    Check {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// Claim a lock on an issue
    Claim {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Branch name for context
        #[arg(short, long)]
        branch: Option<String>,
    },
    /// Release a lock on an issue
    Release {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
    /// Steal a stale lock from another agent
    Steal {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
    },
}

#[derive(Subcommand)]
enum WorkflowCommands {
    /// Compare deployed policy files against embedded defaults
    Diff {
        /// Filter by section: tracking, rules, languages, hooks
        #[arg(short, long)]
        section: Option<String>,
        /// CI mode: exit 1 if any files have drifted without '# crosslink:custom' marker
        #[arg(long)]
        check: bool,
    },
    /// Show chronological comment trail for an issue
    Trail {
        /// Issue ID
        #[arg(value_parser = parse_issue_id_clap)]
        id: i64,
        /// Filter by comment kind(s), comma-separated (e.g. plan,decision)
        #[arg(long)]
        kind: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
}

#[derive(Subcommand)]
enum StyleCommands {
    /// Set the house style source (a git repo URL + optional ref)
    Set {
        /// Git repository URL for the house style
        url: String,
        /// Branch or tag to track (default: main)
        #[arg(long, name = "ref")]
        ref_name: Option<String>,
    },
    /// Sync: pull latest from the house style source
    Sync {
        /// Show what would change without writing
        #[arg(long = "dry-run")]
        dry_run: bool,
    },
    /// Diff: show what's drifted from house style
    Diff,
    /// Show current house style configuration
    Show,
    /// Remove house style association
    Unset,
}

#[derive(Subcommand)]
enum KnowledgeCommands {
    /// Create a new knowledge page
    Add {
        /// Page slug (filename without .md)
        slug: String,
        /// Page title
        #[arg(short, long)]
        title: Option<String>,
        /// Tags for the page (repeatable)
        #[arg(long)]
        tag: Vec<String>,
        /// Source URL (repeatable)
        #[arg(long)]
        source: Vec<String>,
        /// Page content (body text after frontmatter)
        #[arg(long)]
        content: Option<String>,
        /// Import from a design document file
        #[arg(long, value_name = "PATH")]
        from_doc: Option<PathBuf>,
        /// (Rejected — external sources are read-only)
        #[arg(long, hide = true)]
        repo: Option<String>,
    },
    /// Display a knowledge page
    Show {
        /// Page slug
        slug: String,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },
    /// List all knowledge pages
    List {
        /// Filter by tag
        #[arg(long)]
        tag: Option<String>,
        /// Filter by contributor
        #[arg(long)]
        contributor: Option<String>,
        /// Filter pages updated since date (YYYY-MM-DD)
        #[arg(long)]
        since: Option<String>,
        /// Output as JSON
        #[arg(long)]
        json: bool,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },
    /// Update an existing knowledge page
    Edit {
        /// Page slug
        slug: String,
        /// Append content to the page (mutually exclusive with section flags)
        #[arg(long, group = "content_mode")]
        append: Option<String>,
        /// Replace page content entirely
        #[arg(long)]
        content: Option<String>,
        /// Replace the content of a specific markdown section (requires --content)
        #[arg(long, value_name = "HEADING", group = "content_mode")]
        replace_section: Option<String>,
        /// Append to a specific markdown section (requires --content)
        #[arg(long, value_name = "HEADING", group = "content_mode")]
        append_to_section: Option<String>,
        /// Add tags (repeatable)
        #[arg(long)]
        tag: Vec<String>,
        /// Add source URL (repeatable)
        #[arg(long)]
        source: Vec<String>,
        /// Replace content from a document file
        #[arg(long, value_name = "PATH")]
        from_doc: Option<PathBuf>,
        /// (Rejected — external sources are read-only)
        #[arg(long, hide = true)]
        repo: Option<String>,
    },
    /// Remove a knowledge page
    Remove {
        /// Page slug
        slug: String,
        /// (Rejected — external sources are read-only)
        #[arg(long, hide = true)]
        repo: Option<String>,
    },
    /// Manually sync from remote
    Sync {
        /// (Rejected — external sources are read-only)
        #[arg(long, hide = true)]
        repo: Option<String>,
    },
    /// Bulk import markdown files as knowledge pages
    Import {
        /// Directory containing .md files to import
        directory: PathBuf,
        /// Extra tags to apply to all imports (repeatable)
        #[arg(long)]
        tag: Vec<String>,
        /// Overwrite existing pages
        #[arg(long)]
        overwrite: bool,
        /// Preview imports without writing
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// (Rejected — external sources are read-only)
        #[arg(long, hide = true)]
        repo: Option<String>,
    },
    /// Search knowledge page content
    Search {
        /// Search query (case-insensitive substring match)
        query: Option<String>,
        /// Number of context lines around each match
        #[arg(short = 'C', long, default_value = "1")]
        context: usize,
        /// Search by source URL domain instead of content
        #[arg(long)]
        source: Option<String>,
        /// Filter results by tag
        #[arg(long)]
        tag: Option<String>,
        /// Filter results updated since date (YYYY-MM-DD)
        #[arg(long)]
        since: Option<String>,
        /// Filter results by contributor
        #[arg(long)]
        contributor: Option<String>,
        /// Query an external repository (URL, local path, or @alias)
        #[arg(long)]
        repo: Option<String>,
        /// Force refresh of cached external data
        #[arg(long)]
        refresh: bool,
    },
}

#[derive(Subcommand)]
enum IntegrityCommands {
    /// Check counter consistency (`next_display_id`, `next_comment_id`)
    Counters {
        /// Repair inconsistencies by recalculating from data
        #[arg(long)]
        repair: bool,
    },
    /// Verify `SQLite` matches JSON issue files
    Hydration {
        /// Re-hydrate `SQLite` from JSON
        #[arg(long)]
        repair: bool,
    },
    /// Check for stale or orphaned locks
    Locks {
        /// Release stale locks
        #[arg(long)]
        repair: bool,
    },
    /// Verify `SQLite` schema version
    Schema {
        /// Re-run migrations to update schema
        #[arg(long)]
        repair: bool,
    },
    /// Detect mixed V1/V2 hub layout files
    Layout {
        /// Migrate V1 files to V2 and remove stale duplicates
        #[arg(long)]
        repair: bool,
    },
    /// Retroactively sign unsigned hub entries with a human key (attestation)
    SignBackfill {
        /// Actually apply signatures (dry-run without this flag)
        #[arg(long)]
        confirm: bool,
        /// Path to SSH private key (defaults to git's configured signing key)
        #[arg(long)]
        key: Option<std::path::PathBuf>,
    },
}

#[derive(Subcommand)]
enum KickoffCommands {
    /// Launch a new agent to implement a feature
    Run {
        /// Human-readable feature description
        description: String,
        /// Existing issue to work on (creates one if omitted)
        #[arg(long)]
        issue: Option<i64>,
        /// Container runtime: none (local process), docker, podman
        #[arg(long, default_value = "none")]
        container: String,
        /// Verification level: local, ci, thorough
        #[arg(long, default_value = "local")]
        verify: String,
        /// LLM model to use
        #[arg(long, default_value = "opus")]
        model: String,
        /// Container image (for --container docker/podman)
        #[arg(long, default_value = "ghcr.io/forecast-bio/crosslink-agent:latest")]
        image: String,
        /// Max runtime before killing agent (e.g. "1h", "30m")
        #[arg(long, default_value = "1h")]
        timeout: String,
        /// Print the agent prompt without launching
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Branch to use (auto-creates feature branch if omitted)
        #[arg(long)]
        branch: Option<String>,
        /// Path to a design document (markdown) with structured requirements
        #[arg(long, value_name = "PATH")]
        doc: Option<PathBuf>,
        /// Pass --dangerously-skip-permissions to the claude CLI (for sandboxed agents)
        #[arg(long)]
        skip_permissions: bool,
    },
    /// Check status of a running kickoff agent (no args = pipeline overview)
    Status {
        /// Agent ID or branch name (omit for pipeline overview)
        agent: Option<String>,
    },
    /// Tail an agent's event log
    Logs {
        /// Agent ID or branch name
        agent: String,
        /// Number of recent events to show
        #[arg(short, long, default_value = "20")]
        lines: usize,
    },
    /// Stop a running kickoff agent
    Stop {
        /// Agent ID or branch name
        agent: String,
        /// Force kill (SIGKILL instead of SIGTERM)
        #[arg(long)]
        force: bool,
    },
    /// Analyze a design document against the codebase (read-only)
    Plan {
        /// Path to design document
        doc: PathBuf,
        /// Existing issue to associate with
        #[arg(long)]
        issue: Option<i64>,
        /// LLM model to use
        #[arg(long, default_value = "opus")]
        model: String,
        /// Max runtime (e.g. "30m", "1h")
        #[arg(long, default_value = "30m")]
        timeout: String,
        /// Print the analysis prompt without launching
        #[arg(long = "dry-run")]
        dry_run: bool,
    },
    /// Display a gap report from a previous plan analysis
    ShowPlan {
        /// Agent ID or branch slug
        agent: String,
    },
    /// Display the spec validation report from a completed agent
    Report {
        /// Agent ID or branch slug (required unless --all)
        agent: Option<String>,
        /// Output as raw JSON
        #[arg(long)]
        json: bool,
        /// Output as PR-ready markdown
        #[arg(long)]
        markdown: bool,
        /// Show aggregated reports from all agent worktrees
        #[arg(long)]
        all: bool,
    },
    /// List all kickoff agents across worktrees, tmux, and Docker
    List {
        /// Filter by status: running, done, failed, all
        #[arg(long, default_value = "all")]
        status: String,
    },
    /// Remove completed/stale agent worktrees, tmux sessions, and containers
    Cleanup {
        /// Show what would be cleaned without doing anything
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Also clean up potentially stale agents (not just confirmed-done)
        #[arg(long)]
        force: bool,
        /// Keep the N most recently completed agents
        #[arg(long, default_value = "0")]
        keep: usize,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Show branch topology of kickoff feature branches
    Graph {
        /// Include completed, stopped, and orphaned branches
        #[arg(long)]
        all: bool,
        /// Reserved for future pager support (no-op in V1)
        #[arg(long)]
        no_pager: bool,
    },
    /// Interactive pipeline wizard or direct launch from a design doc
    #[command(alias = "go")]
    Launch {
        /// Path to design document (skips source selection in wizard)
        doc: Option<PathBuf>,
        /// Run gap analysis (plan mode) — non-interactive
        #[arg(long)]
        plan: bool,
        /// Run implementation — non-interactive
        #[arg(long)]
        run: bool,
        /// Verification level: local, ci, thorough
        #[arg(long, default_value = "local")]
        verify: String,
        /// LLM model to use
        #[arg(long, default_value = "opus")]
        model: String,
        /// Max runtime (e.g. "1h", "30m")
        #[arg(long, default_value = "1h")]
        timeout: String,
        /// Container runtime: none, docker, podman
        #[arg(long, default_value = "none")]
        container: String,
        /// Existing issue to work on
        #[arg(long)]
        issue: Option<i64>,
        /// Print the prompt without launching
        #[arg(long = "dry-run")]
        dry_run: bool,
        /// Pass --dangerously-skip-permissions to the claude CLI
        #[arg(long)]
        skip_permissions: bool,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Show all configuration with default annotations
    Show,
    /// Get a specific config value
    Get {
        /// Config key name
        key: String,
    },
    /// Set a config value
    Set {
        /// Config key name
        key: String,
        /// Value to set (for arrays: comma-separated, or use --add/--remove)
        value: Option<String>,
        /// Add a value to an array field
        #[arg(long)]
        add: Option<String>,
        /// Remove a value from an array field
        #[arg(long)]
        remove: Option<String>,
        /// Write to hook-config.local.json instead of hook-config.json
        #[arg(long)]
        local: bool,
    },
    /// List all available config keys with descriptions
    List,
    /// Reset config to defaults (all keys, or a single key)
    Reset {
        /// Specific key to reset (omit for full reset)
        key: Option<String>,
    },
    /// Show differences from default config
    Diff,
}

#[derive(Subcommand)]
enum SwarmCommands {
    /// Initialize a swarm plan from a design document
    Init {
        /// Path to design document (markdown)
        #[arg(long, value_name = "PATH")]
        doc: PathBuf,
    },
    /// Show current swarm status (agents, phases, progress, next steps)
    Status,
    /// Reconstruct state and show next steps for resuming
    Resume,
    /// Sync agent statuses from live worktree state into phase JSON
    SyncStatus,
    /// Associate an external agent/branch with a swarm slot
    Adopt {
        /// Agent slug or branch name of the external agent
        agent: String,
        /// Swarm slot slug to assign the agent to
        #[arg(long, value_name = "SLUG")]
        slot: String,
    },
    /// Archive the current swarm and clear the active slot
    Archive,
    /// Reset the active swarm (archives by default)
    Reset {
        /// Delete without archiving
        #[arg(long)]
        no_archive: bool,
    },
    /// List active and archived swarms
    #[command(name = "list")]
    ListSwarms,
    /// Launch all planned agents for a phase
    Launch {
        /// Phase slug (e.g. "phase-1")
        phase: String,
        /// Retry only previously failed agents
        #[arg(long)]
        retry_failed: bool,
        /// Check budget before launching; block if insufficient
        #[arg(long)]
        budget_aware: bool,
    },
    /// Run the project test suite as a phase gate
    Gate {
        /// Phase slug (e.g. "phase-1")
        phase: String,
    },
    /// Record a checkpoint after a phase completes
    Checkpoint {
        /// Phase slug (e.g. "phase-1")
        phase: String,
        /// Handoff notes for the next session
        #[arg(long)]
        notes: Option<String>,
        /// Checkpoint even if gate hasn't passed
        #[arg(long)]
        force: bool,
    },
    /// Set budget parameters (window duration, model)
    Config {
        /// Budget time window (e.g. "5h", "3h30m")
        #[arg(long, value_name = "DURATION")]
        budget_window: String,
        /// Model to estimate costs for
        #[arg(long, default_value = "opus")]
        model: String,
    },
    /// Estimate wall-clock cost for a phase
    Estimate {
        /// Phase slug (e.g. "phase-1")
        phase: String,
    },
    /// Scan completed agents and update cost history
    Harvest,
    /// Plan a multi-phase build across budget windows
    Plan {
        /// Budget window duration (e.g. "5h"); uses saved config if omitted
        #[arg(long, value_name = "DURATION")]
        budget_window: Option<String>,
    },
    /// Show the current window plan (alias for plan with saved config)
    PlanShow,
    /// Launch parallel adversarial review agents across codebase partitions
    Review {
        /// Number of review agents to launch
        #[arg(long, default_value = "4")]
        agents: usize,
        /// Review mandate type
        #[arg(long, default_value = "adversarial")]
        mandate: String,
        /// Output path for consolidated findings document
        #[arg(long, value_name = "PATH")]
        doc: Option<PathBuf>,
        /// Also file issues for findings after review
        #[arg(long)]
        file_issues: bool,
        /// Also launch fix agents after filing issues
        #[arg(long)]
        fix: bool,
    },
    /// Launch parallel fix agents, one per issue
    Fix {
        /// Comma-separated issue numbers (e.g., "326,327,328")
        #[arg(long, value_name = "IDS")]
        issues: Option<String>,
        /// Label filter to select issues (e.g., "review-finding")
        #[arg(long, value_name = "LABEL")]
        from_label: Option<String>,
        /// Maximum number of concurrent agents
        #[arg(long, default_value = "6")]
        max_agents: usize,
        /// Check budget before launching
        #[arg(long)]
        budget_aware: bool,
    },
    /// Merge changes from completed agent worktrees into a single branch
    Merge {
        /// Target branch name for merged changes
        #[arg(long, default_value = "swarm-combined")]
        branch: String,
        /// Base branch to create the target from (default: auto-detect develop or main)
        #[arg(long)]
        base: Option<String>,
        /// Only analyze conflicts, don't apply changes
        #[arg(long)]
        dry_run: bool,
        /// Agent slugs to merge (default: all completed agents from current swarm)
        #[arg(long, value_name = "SLUGS")]
        agents: Option<String>,
    },
    /// Move an agent to a different phase
    #[command(name = "move")]
    MoveAgent {
        /// Agent slug to move
        agent: String,
        /// Target phase name
        #[arg(long, value_name = "PHASE")]
        to_phase: String,
    },
    /// Merge two phases into one
    MergePhases {
        /// First phase name
        phase_a: String,
        /// Second phase name
        phase_b: String,
    },
    /// Split a phase after a specific agent
    SplitPhase {
        /// Phase name to split
        phase: String,
        /// Split after this agent slug
        #[arg(long, value_name = "SLUG")]
        after: String,
    },
    /// Remove an agent from the plan
    RemoveAgent {
        /// Agent slug to remove
        agent: String,
    },
    /// Reorder a phase to a new position
    Reorder {
        /// Phase name to move
        phase: String,
        /// New position (1-based)
        #[arg(long)]
        position: usize,
    },
    /// Rename a phase
    RenamePhase {
        /// Current phase name
        old: String,
        /// New phase name
        new: String,
    },
    /// Continue a paused pipeline (e.g., after human checkpoint)
    ReviewContinue,
    /// Show pipeline status
    ReviewStatus,
    /// Run the full review→fix pipeline (standalone pipeline driver with stage logging)
    Pipeline {
        /// Number of agents
        #[arg(long, default_value = "4")]
        agents: usize,
        /// Review mandate
        #[arg(long, default_value = "adversarial")]
        mandate: String,
        /// Target branch for merging fixes
        #[arg(long, default_value = "main")]
        target_branch: String,
        /// Automatically fix findings
        #[arg(long)]
        auto_fix: bool,
        /// Automatically file issues for findings
        #[arg(long)]
        auto_file_issues: bool,
    },
    /// Initialize trust model configuration (writes swarm.toml)
    TrustInit {
        /// Trust model type: local-only, multi-tenant, public-api
        #[arg(long, default_value = "local-only")]
        model: String,
    },
}

#[derive(Subcommand)]
pub enum SentinelCommands {
    /// One-shot sentinel sweep
    Run {
        /// Print what would be dispatched without acting
        #[arg(long)]
        dry_run: bool,
        /// Only process signals matching this label
        #[arg(long)]
        label: Option<String>,
    },
    /// Start persistent sentinel daemon
    Watch {
        /// Poll interval in minutes
        #[arg(long, default_value = "10")]
        interval: u64,
    },
    /// Show sentinel daemon status and in-flight agents
    Status,
    /// Show past sentinel runs and outcomes
    History {
        /// Maximum number of runs to show
        #[arg(long, default_value = "10")]
        limit: usize,
        /// Show per-dispatch details for each run
        #[arg(long)]
        detail: bool,
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Stop the sentinel daemon
    Stop,
    /// Show dispatch success rates per model and rule
    Metrics {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Analyze dispatch history for recurring patterns and hotspots
    Patterns {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },
    /// Internal: run the sentinel watch loop (used by watch)
    #[command(hide = true)]
    RunDaemon {
        #[arg(long)]
        dir: std::path::PathBuf,
        #[arg(long, default_value = "10")]
        interval: u64,
    },
}

#[derive(Subcommand, Clone, Copy)]
enum ContextCommands {
    /// Measure context injection sizes and estimate token overhead
    Measure {
        /// Show additional details (hook config contents, etc.)
        #[arg(short, long)]
        verbose: bool,
    },
    /// Verify all expected crosslink files are deployed and valid
    Check,
}

fn init_tracing(log_level: &str, log_format: &str) {
    use tracing_subscriber::{fmt, layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
    let filter = EnvFilter::try_new(log_level).unwrap_or_else(|_| EnvFilter::new("warn"));
    if log_format == "json" {
        tracing_subscriber::registry()
            .with(filter)
            .with(fmt::layer().json().with_writer(std::io::stderr))
            .init();
    } else {
        tracing_subscriber::registry()
            .with(filter)
            .with(fmt::layer().with_target(false).with_writer(std::io::stderr))
            .init();
    }
}

fn find_crosslink_dir() -> Result<PathBuf> {
    let mut current = env::current_dir()?;

    // First, walk up from cwd looking for .crosslink (works in main repo)
    let start = current.clone();
    loop {
        let candidate = current.join(".crosslink");
        if candidate.is_dir() {
            return Ok(candidate);
        }

        if !current.pop() {
            break;
        }
    }

    // Not found — check if we're in a git worktree and look in the main repo root
    if let Some(main_root) = utils::resolve_main_repo_root(&start) {
        let candidate = main_root.join(".crosslink");
        if candidate.is_dir() {
            return Ok(candidate);
        }
    }

    bail!("Not a crosslink repository (or any parent). Run 'crosslink init' first.");
}

fn get_db() -> Result<Database> {
    let crosslink_dir = find_crosslink_dir()?;
    let db_path = crosslink_dir.join("issues.db");
    let db = Database::open(&db_path).context("Failed to open database")?;

    // Auto-hydrate if the hub branch has moved since last hydration (#500).
    // This is a sub-millisecond check (git rev-parse HEAD in the cache
    // worktree) that only triggers re-hydration when the ref actually changed.
    if let Err(e) = hydration::maybe_auto_hydrate(&crosslink_dir, &db) {
        tracing::debug!("auto-hydration skipped: {}", e);
    }

    Ok(db)
}

/// Try to create a `SharedWriter` for multi-agent mode.
/// Returns None if agent.json is absent or sync cache isn't initialized.
fn get_writer(crosslink_dir: &std::path::Path) -> Option<shared_writer::SharedWriter> {
    match shared_writer::SharedWriter::new(crosslink_dir) {
        Ok(w) => w,
        Err(e) => {
            tracing::warn!("SharedWriter unavailable: {}", e);
            None
        }
    }
}

/// Clap value parser for issue IDs (supports `L1` offline notation).
fn parse_issue_id_clap(s: &str) -> std::result::Result<i64, String> {
    parse_issue_id(s).map_err(|e| e.to_string())
}

/// Parse an issue ID string, supporting both regular IDs and offline local IDs.
///
/// - `"42"` → `42` (regular display ID)
/// - `"L1"` or `"l1"` → `-1` (offline local ID, stored as negative in `SQLite`)
///
/// Used when offline issue creation is enabled (`display_id`: null in JSON).
fn parse_issue_id(s: &str) -> Result<i64> {
    if let Some(n) = s.strip_prefix('L').or_else(|| s.strip_prefix('l')) {
        let num: i64 = n
            .parse()
            .with_context(|| format!("Invalid local issue ID: {s}"))?;
        if num <= 0 {
            bail!("Local issue ID must be positive: {s}");
        }
        Ok(-num)
    } else {
        s.parse().with_context(|| format!("Invalid issue ID: {s}"))
    }
}

/// Emit a hint to stderr (suppressed in quiet mode).
fn hint(quiet: bool, msg: &str) {
    if !quiet {
        tracing::info!("hint: {}", msg);
    }
}

/// Dispatch an `IssueCommands` variant.
fn dispatch_issue(action: IssueCommands, quiet: bool, json: bool) -> Result<()> {
    match action {
        IssueCommands::Create {
            title,
            description,
            priority,
            template,
            label,
            work,
            defer_id,
            parent,
        } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            let opts = commands::create::CreateOpts {
                labels: &label,
                work,
                quiet,
                crosslink_dir: Some(&crosslink_dir),
                defer_id: parent.is_none() && defer_id,
            };
            parent.map_or_else(
                || {
                    commands::create::run(
                        &db,
                        writer.as_ref(),
                        &title,
                        description.as_deref(),
                        &priority,
                        template.as_deref(),
                        &opts,
                    )
                },
                |parent_id| {
                    commands::create::run_subissue(
                        &db,
                        writer.as_ref(),
                        parent_id,
                        &title,
                        description.as_deref(),
                        &priority,
                        &opts,
                    )
                },
            )
        }

        IssueCommands::Quick {
            title,
            description,
            priority,
            template,
            label,
            parent,
        } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            let opts = commands::create::CreateOpts {
                labels: &label,
                work: true,
                quiet,
                crosslink_dir: Some(&crosslink_dir),
                defer_id: false,
            };
            parent.map_or_else(
                || {
                    commands::create::run(
                        &db,
                        writer.as_ref(),
                        &title,
                        description.as_deref(),
                        &priority,
                        template.as_deref(),
                        &opts,
                    )
                },
                |parent_id| {
                    commands::create::run_subissue(
                        &db,
                        writer.as_ref(),
                        parent_id,
                        &title,
                        description.as_deref(),
                        &priority,
                        &opts,
                    )
                },
            )
        }

        IssueCommands::List {
            status,
            label,
            priority,
            repo,
            refresh,
        } => {
            if let Some(repo_value) = repo {
                let crosslink_dir = find_crosslink_dir()?;
                commands::external_issues::list(
                    &crosslink_dir,
                    &repo_value,
                    Some(&status),
                    label.as_deref(),
                    priority.as_deref(),
                    refresh,
                    json,
                    quiet,
                )
            } else {
                let db = get_db()?;
                if json {
                    commands::list::run_json(
                        &db,
                        Some(&status),
                        label.as_deref(),
                        priority.as_deref(),
                    )
                } else {
                    commands::list::run(&db, Some(&status), label.as_deref(), priority.as_deref())
                }
            }
        }

        IssueCommands::Search {
            query,
            repo,
            refresh,
        } => {
            if let Some(repo_value) = repo {
                let crosslink_dir = find_crosslink_dir()?;
                commands::external_issues::search(
                    &crosslink_dir,
                    &repo_value,
                    &query,
                    refresh,
                    json,
                    quiet,
                )
            } else {
                let db = get_db()?;
                if json {
                    commands::search::run_json(&db, &query)
                } else {
                    commands::search::run(&db, &query)
                }
            }
        }

        IssueCommands::Show { id, repo, refresh } => {
            if let Some(repo_value) = repo {
                let crosslink_dir = find_crosslink_dir()?;
                commands::external_issues::show(
                    &crosslink_dir,
                    &repo_value,
                    id,
                    refresh,
                    json,
                    quiet,
                )
            } else {
                let db = get_db()?;
                if json {
                    commands::show::run_json(&db, id)
                } else {
                    commands::show::run(&db, id)
                }
            }
        }

        IssueCommands::Update {
            id,
            title,
            description,
            priority,
        } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::update::run(
                &db,
                writer.as_ref(),
                id,
                title.as_deref(),
                description.as_deref(),
                priority.as_deref(),
            )
        }

        IssueCommands::Close { id, no_changelog } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            if quiet {
                commands::lifecycle::close_quiet(
                    &db,
                    writer.as_ref(),
                    id,
                    !no_changelog,
                    &crosslink_dir,
                )
            } else {
                commands::lifecycle::close(&db, writer.as_ref(), id, !no_changelog, &crosslink_dir)
            }
        }

        IssueCommands::CloseAll {
            label,
            priority,
            no_changelog,
        } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::lifecycle::close_all(
                &db,
                writer.as_ref(),
                label.as_deref(),
                priority.as_deref(),
                !no_changelog,
                &crosslink_dir,
            )
        }

        IssueCommands::Reopen { id } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::lifecycle::reopen(&db, writer.as_ref(), id)
        }

        IssueCommands::Delete { id, force } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::delete::run(&db, writer.as_ref(), id, force)
        }

        IssueCommands::Comment { id, text, kind } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::comment::run(&db, writer.as_ref(), id, &text, &kind)
        }

        IssueCommands::Intervene {
            id,
            description,
            trigger,
            context,
        } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::intervene::run(
                &db,
                writer.as_ref(),
                id,
                &description,
                &trigger,
                context.as_deref(),
                &crosslink_dir,
            )
        }

        IssueCommands::Label { id, label } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::label::add(&db, writer.as_ref(), id, &label)
        }

        IssueCommands::Unlabel { id, label } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::label::remove(&db, writer.as_ref(), id, &label)
        }

        IssueCommands::Block { id, blocker } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::deps::block(&db, writer.as_ref(), id, blocker)
        }

        IssueCommands::Unblock { id, blocker } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::deps::unblock(&db, writer.as_ref(), id, blocker)
        }

        IssueCommands::Blocked => {
            let db = get_db()?;
            commands::deps::list_blocked(&db, json)
        }

        IssueCommands::Ready => {
            let db = get_db()?;
            commands::deps::list_ready(&db, json)
        }

        IssueCommands::Relate { id, related } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::relate::add(&db, writer.as_ref(), id, related)
        }

        IssueCommands::Unrelate { id, related } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            let writer = get_writer(&crosslink_dir);
            commands::relate::remove(&db, writer.as_ref(), id, related)
        }

        IssueCommands::Related { id } => {
            let db = get_db()?;
            commands::relate::list(&db, id)
        }

        IssueCommands::Next => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            commands::next::run(&db, &crosslink_dir)
        }

        IssueCommands::Tree { status } => {
            let db = get_db()?;
            commands::tree::run(&db, Some(&status), json)
        }

        IssueCommands::Tested => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::tested::run(&crosslink_dir)
        }
    }
}

fn main() -> Result<()> {
    let cli = Cli::parse();

    let log_format = match &cli.command {
        Commands::Serve { .. } if cli.log_format == "text" => "json",
        _ => cli.log_format.as_str(),
    };
    init_tracing(&cli.log_level, log_format);

    match cli.command {
        Commands::Init {
            force,
            update,
            dry_run,
            no_prompt,
            python_prefix,
            skip_cpitd,
            skip_signing,
            signing_key,
            reconfigure,
            defaults,
        } => {
            let cwd = env::current_dir()?;
            let opts = commands::init::InitOpts {
                force,
                update,
                dry_run,
                no_prompt,
                python_prefix: python_prefix.as_deref(),
                skip_cpitd,
                skip_signing,
                signing_key: signing_key.as_deref(),
                reconfigure,
                defaults,
            };
            commands::init::run(&cwd, &opts)
        }

        // === Canonical grouped commands ===
        Commands::Issue { action } => dispatch_issue(action, cli.quiet, cli.json),

        Commands::Timer { action } => {
            let db = get_db()?;
            match action {
                TimerCommands::Start { id } => commands::timer::start(&db, id),
                TimerCommands::Stop => commands::timer::stop(&db),
                TimerCommands::Show => commands::timer::status(&db),
            }
        }

        Commands::Migrate { action } => match action {
            MigrateCommands::ToShared => {
                let crosslink_dir = find_crosslink_dir()?;
                let db = get_db()?;
                commands::migrate::to_shared(&crosslink_dir, &db)
            }
            MigrateCommands::FromShared => {
                let crosslink_dir = find_crosslink_dir()?;
                let db = get_db()?;
                commands::migrate::from_shared(&crosslink_dir, &db)
            }
            MigrateCommands::RenameBranch => {
                let crosslink_dir = find_crosslink_dir()?;
                commands::migrate::rename_branch(&crosslink_dir)
            }
        },

        // === Hidden top-level shortcuts ===
        Commands::Create {
            title,
            description,
            priority,
            template,
            label,
            work,
            defer_id,
            parent,
        } => dispatch_issue(
            IssueCommands::Create {
                title,
                description,
                priority,
                template,
                label,
                work,
                defer_id,
                parent,
            },
            cli.quiet,
            cli.json,
        ),

        Commands::Quick {
            title,
            description,
            priority,
            template,
            label,
            parent,
        } => dispatch_issue(
            IssueCommands::Quick {
                title,
                description,
                priority,
                template,
                label,
                parent,
            },
            cli.quiet,
            cli.json,
        ),

        Commands::List {
            status,
            label,
            priority,
        } => dispatch_issue(
            IssueCommands::List {
                status,
                label,
                priority,
                repo: None,
                refresh: false,
            },
            cli.quiet,
            cli.json,
        ),

        Commands::Show { id } => dispatch_issue(
            IssueCommands::Show {
                id,
                repo: None,
                refresh: false,
            },
            cli.quiet,
            cli.json,
        ),

        Commands::Close { id, no_changelog } => dispatch_issue(
            IssueCommands::Close { id, no_changelog },
            cli.quiet,
            cli.json,
        ),

        // === Hidden aliases (emit hints) ===
        Commands::New {
            title,
            description,
            priority,
            template,
            label,
            work,
            parent,
        } => {
            hint(
                cli.quiet,
                "did you mean 'crosslink issue create'? Using that.",
            );
            dispatch_issue(
                IssueCommands::Create {
                    title,
                    description,
                    priority,
                    template,
                    label,
                    work,
                    defer_id: false,
                    parent,
                },
                cli.quiet,
                cli.json,
            )
        }

        Commands::Issues { action } => {
            hint(
                cli.quiet,
                "did you mean 'crosslink issue list'? Using that.",
            );
            if let Some(IssuesAliasCommands::List {
                status,
                label,
                priority,
            }) = action
            {
                dispatch_issue(
                    IssueCommands::List {
                        status,
                        label,
                        priority,
                        repo: None,
                        refresh: false,
                    },
                    cli.quiet,
                    cli.json,
                )
            } else {
                dispatch_issue(
                    IssueCommands::List {
                        status: "open".to_string(),
                        label: None,
                        priority: None,
                        repo: None,
                        refresh: false,
                    },
                    cli.quiet,
                    cli.json,
                )
            }
        }

        Commands::Subissue {
            parent,
            title,
            description,
            priority,
            label,
            work,
        } => {
            hint(
                cli.quiet,
                "did you mean 'crosslink issue create --parent'? Using that.",
            );
            dispatch_issue(
                IssueCommands::Create {
                    title,
                    description,
                    priority,
                    template: None,
                    label,
                    work,
                    defer_id: false,
                    parent: Some(parent),
                },
                cli.quiet,
                cli.json,
            )
        }

        Commands::TimerStart { id } => {
            hint(
                cli.quiet,
                "did you mean 'crosslink timer start'? Using that.",
            );
            let db = get_db()?;
            commands::timer::start(&db, id)
        }

        Commands::TimerStop => {
            hint(
                cli.quiet,
                "did you mean 'crosslink timer stop'? Using that.",
            );
            let db = get_db()?;
            commands::timer::stop(&db)
        }

        // === Hidden migration aliases ===
        Commands::MigrateToShared => {
            hint(
                cli.quiet,
                "did you mean 'crosslink migrate to-shared'? Using that.",
            );
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::migrate::to_shared(&crosslink_dir, &db)
        }

        Commands::MigrateFromShared => {
            hint(
                cli.quiet,
                "did you mean 'crosslink migrate from-shared'? Using that.",
            );
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::migrate::from_shared(&crosslink_dir, &db)
        }

        Commands::MigrateRenameBranch => {
            hint(
                cli.quiet,
                "did you mean 'crosslink migrate rename-branch'? Using that.",
            );
            let crosslink_dir = find_crosslink_dir()?;
            commands::migrate::rename_branch(&crosslink_dir)
        }

        // === Remaining top-level commands (unchanged) ===
        Commands::Export { output, format } => {
            let db = get_db()?;
            match format.as_str() {
                "json" => commands::export::run_json(&db, output.as_deref()),
                "markdown" | "md" => commands::export::run_markdown(&db, output.as_deref()),
                _ => {
                    bail!("Unknown format '{format}'. Use 'json' or 'markdown'");
                }
            }
        }

        Commands::Import { input } => {
            let db = get_db()?;
            let path = std::path::Path::new(&input);
            commands::import::run_json(&db, path)
        }

        Commands::Archive { action } => {
            let db = get_db()?;
            commands::archive::run(action, &db)
        }

        Commands::Milestone { action } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            commands::milestone::run(action, &db, &crosslink_dir)
        }

        Commands::Session { action } => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            commands::session::run(action, &db, &crosslink_dir, cli.json)
        }

        Commands::Daemon { action } => match action {
            DaemonCommands::Start => {
                let crosslink_dir = find_crosslink_dir()?;
                daemon::start(&crosslink_dir)
            }
            DaemonCommands::Stop => {
                let crosslink_dir = find_crosslink_dir()?;
                daemon::stop(&crosslink_dir)
            }
            DaemonCommands::Status => {
                let crosslink_dir = find_crosslink_dir()?;
                daemon::status(&crosslink_dir);
                Ok(())
            }
            DaemonCommands::Run { dir } => daemon::run_daemon(&dir),
        },

        Commands::Cpitd { action } => {
            let db = get_db()?;
            commands::cpitd::run(action, &db, cli.quiet)
        }

        Commands::Agent { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::agent::run(action, &crosslink_dir)
        }

        Commands::Trust { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::trust::run(action, &crosslink_dir)
        }

        Commands::Locks { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::locks_cmd::run(action, &crosslink_dir, &db, cli.json)
        }

        Commands::Heartbeat => {
            let crosslink_dir = find_crosslink_dir()?;
            let agent = crate::identity::AgentConfig::load(&crosslink_dir)?;
            match agent {
                Some(agent) => {
                    let sync = crate::sync::SyncManager::new(&crosslink_dir)?;
                    let _ = sync.init_cache();
                    let db = get_db()?;
                    let active_issue = db
                        .get_current_session_for_agent(None)?
                        .and_then(|s| s.active_issue_id);
                    sync.push_heartbeat(&agent, active_issue)?;
                    Ok(())
                }
                None => Ok(()),
            }
        }

        Commands::Sync => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::locks_cmd::sync_cmd(&crosslink_dir, &db)
        }

        Commands::Integrity { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::integrity_cmd::run(action.as_ref(), &crosslink_dir, &db)
        }

        Commands::Prune {
            dry_run,
            force,
            keep_commits,
            hub_only,
            knowledge_only,
        } => {
            let crosslink_dir = find_crosslink_dir()?;
            let opts = commands::prune::PruneOpts {
                dry_run,
                force,
                keep_commits,
                hub_only,
                knowledge_only,
            };
            commands::prune::run(&crosslink_dir, &opts, cli.json)
        }

        Commands::Compact { force } => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            commands::compact::run(&crosslink_dir, &db, force)
        }

        Commands::Container { action } => commands::container::run(action),

        Commands::Style { command } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::style::run(command, &crosslink_dir)
        }

        Commands::Knowledge { command } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::knowledge::dispatch(command, &crosslink_dir, cli.json)
        }

        Commands::Config { command, preset } => {
            let crosslink_dir = find_crosslink_dir()?;
            command.map_or_else(
                || commands::config::run_bare(&crosslink_dir, preset.as_deref()),
                |cmd| commands::config::run(cmd, &crosslink_dir),
            )
        }
        Commands::Context { command } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::context::run(command, &crosslink_dir)
        }
        Commands::Workflow { command } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::workflow::run(command, &crosslink_dir, get_db)
        }

        Commands::Kickoff { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            let writer = get_writer(&crosslink_dir);
            // Bare `crosslink kickoff` → launch the interactive wizard
            let action = action.unwrap_or_else(|| KickoffCommands::Launch {
                doc: None,
                plan: false,
                run: false,
                verify: "local".to_string(),
                model: "opus".to_string(),
                timeout: "1h".to_string(),
                container: "none".to_string(),
                issue: None,
                dry_run: false,
                skip_permissions: false,
            });
            commands::kickoff::dispatch(
                action,
                &crosslink_dir,
                &db,
                writer.as_ref(),
                cli.quiet,
                cli.json,
            )
        }
        Commands::Design {
            description,
            issue,
            gh_issue,
            continue_slug,
        } => commands::design_cmd::run(
            description.as_deref(),
            issue,
            gh_issue,
            continue_slug.as_deref(),
        ),
        Commands::Swarm { action } => {
            let crosslink_dir = find_crosslink_dir()?;
            match action {
                SwarmCommands::Init { doc } => commands::swarm::init(&crosslink_dir, &doc),
                SwarmCommands::Status => commands::swarm::status(&crosslink_dir, cli.json),
                SwarmCommands::Resume => commands::swarm::resume(&crosslink_dir),
                SwarmCommands::SyncStatus => commands::swarm::sync_status(&crosslink_dir),
                SwarmCommands::Adopt { agent, slot } => {
                    commands::swarm::adopt(&crosslink_dir, &agent, &slot)
                }
                SwarmCommands::Archive => commands::swarm::archive(&crosslink_dir),
                SwarmCommands::Reset { no_archive } => {
                    commands::swarm::reset(&crosslink_dir, no_archive)
                }
                SwarmCommands::ListSwarms => commands::swarm::list_swarms(&crosslink_dir),
                SwarmCommands::Launch {
                    phase,
                    budget_aware,
                    retry_failed,
                } => {
                    let db = get_db()?;
                    let writer = get_writer(&crosslink_dir);
                    if retry_failed {
                        commands::swarm::launch_retry_failed(
                            &crosslink_dir,
                            &db,
                            writer.as_ref(),
                            &phase,
                            cli.quiet,
                        )
                    } else if budget_aware {
                        commands::swarm::launch_budget_aware(
                            &crosslink_dir,
                            &db,
                            writer.as_ref(),
                            &phase,
                            cli.quiet,
                        )
                    } else {
                        commands::swarm::launch(
                            &crosslink_dir,
                            &db,
                            writer.as_ref(),
                            &phase,
                            cli.quiet,
                        )
                    }
                }
                SwarmCommands::Gate { phase } => commands::swarm::gate(&crosslink_dir, &phase),
                SwarmCommands::Checkpoint {
                    phase,
                    notes,
                    force,
                } => commands::swarm::checkpoint(&crosslink_dir, &phase, notes.as_deref(), force),
                SwarmCommands::Config {
                    budget_window,
                    model,
                } => commands::swarm::config_budget(&crosslink_dir, &budget_window, &model),
                SwarmCommands::Estimate { phase } => {
                    commands::swarm::estimate(&crosslink_dir, &phase)
                }
                SwarmCommands::Harvest => commands::swarm::harvest_costs(&crosslink_dir),
                SwarmCommands::Plan { budget_window } => {
                    commands::swarm::plan(&crosslink_dir, budget_window.as_deref())
                }
                SwarmCommands::PlanShow => commands::swarm::plan_show(&crosslink_dir),
                SwarmCommands::Review {
                    agents,
                    mandate,
                    doc,
                    file_issues,
                    fix,
                } => commands::swarm::review(
                    &crosslink_dir,
                    agents,
                    &mandate,
                    doc.as_deref(),
                    file_issues,
                    fix,
                ),
                SwarmCommands::Fix {
                    issues,
                    from_label,
                    max_agents,
                    budget_aware,
                } => commands::swarm::fix(
                    &crosslink_dir,
                    issues.as_deref(),
                    from_label.as_deref(),
                    max_agents,
                    budget_aware,
                ),
                SwarmCommands::Merge {
                    branch,
                    base,
                    dry_run,
                    agents,
                } => commands::swarm::merge(
                    &crosslink_dir,
                    &branch,
                    base.as_deref(),
                    dry_run,
                    agents.as_deref(),
                ),
                SwarmCommands::MoveAgent { agent, to_phase } => {
                    commands::swarm::move_agent(&crosslink_dir, &agent, &to_phase)
                }
                SwarmCommands::MergePhases { phase_a, phase_b } => {
                    commands::swarm::merge_phases(&crosslink_dir, &phase_a, &phase_b)
                }
                SwarmCommands::SplitPhase { phase, after } => {
                    commands::swarm::split_phase(&crosslink_dir, &phase, &after)
                }
                SwarmCommands::RemoveAgent { agent } => {
                    commands::swarm::remove_agent(&crosslink_dir, &agent)
                }
                SwarmCommands::Reorder { phase, position } => {
                    commands::swarm::reorder_phase(&crosslink_dir, &phase, position)
                }
                SwarmCommands::RenamePhase { old, new } => {
                    commands::swarm::rename_phase(&crosslink_dir, &old, &new)
                }
                SwarmCommands::ReviewContinue => commands::swarm::review_continue(&crosslink_dir),
                SwarmCommands::ReviewStatus => commands::swarm::review_status(&crosslink_dir),
                SwarmCommands::Pipeline {
                    agents,
                    mandate,
                    target_branch,
                    auto_fix,
                    auto_file_issues,
                } => commands::swarm::run_pipeline_cmd(
                    &crosslink_dir,
                    agents,
                    &mandate,
                    &target_branch,
                    auto_fix,
                    auto_file_issues,
                ),
                SwarmCommands::TrustInit { model } => {
                    commands::swarm::trust_init(&crosslink_dir, &model)
                }
            }
        }
        Commands::Sentinel { action } => {
            // RunDaemon is the internal loop entry point — dir is explicit, no auto-detection
            if let SentinelCommands::RunDaemon { ref dir, interval } = action {
                return commands::sentinel::watch::run_watch_loop(dir, interval);
            }
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            let writer = get_writer(&crosslink_dir);
            commands::sentinel::dispatch_cmd(
                action,
                &crosslink_dir,
                &db,
                writer.as_ref(),
                cli.quiet,
                cli.json,
            )
        }
        Commands::Tui => {
            let db = get_db()?;
            let crosslink_dir = find_crosslink_dir()?;
            commands::tui::run(&db, &crosslink_dir)
        }
        Commands::Mc { layout } => {
            let crosslink_dir = find_crosslink_dir()?;
            commands::mission_control::run(&crosslink_dir, &layout)
        }
        Commands::Serve {
            port,
            dashboard_dir,
        } => {
            let crosslink_dir = find_crosslink_dir()?;
            let db = get_db()?;
            tokio::runtime::Runtime::new()?.block_on(server::run(
                port,
                dashboard_dir,
                db,
                crosslink_dir,
            ))
        }
    }
}