task-journal-cli 0.7.0

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

mod tui;

/// Diagnostic snapshot returned by `task-journal doctor`. Fields are
/// stable enough for scripting against `--json`. `issues` is the empty
/// list when everything looks healthy.
#[derive(Serialize)]
struct DoctorReport {
    task_journal_version: &'static str,
    claude_in_path: bool,
    claude_version: Option<String>,
    data_dir: PathBuf,
    events_dir: PathBuf,
    state_dir: PathBuf,
    metrics_dir: PathBuf,
    events_dir_writable: bool,
    state_dir_writable: bool,
    metrics_dir_writable: bool,
    known_projects: Vec<String>,
    schema_versions_applied: Vec<i64>,
    /// Hard problems that block normal use (non-writable dirs, broken
    /// schema, missing files, etc.). A non-empty `issues` list causes
    /// `task-journal doctor` to exit with code 1.
    issues: Vec<String>,
    /// Soft observations: install hints, optional dependencies missing,
    /// configuration suggestions. Always exits 0 even if non-empty —
    /// these are informational, not errors.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    notes: Vec<String>,
}

impl DoctorReport {
    fn print_human(&self) {
        println!("task-journal doctor");
        println!("  version          {}", self.task_journal_version);
        println!(
            "  claude binary    {}",
            if self.claude_in_path {
                self.claude_version
                    .clone()
                    .unwrap_or_else(|| "found (version unknown)".into())
            } else {
                "NOT FOUND in PATH".into()
            }
        );
        println!("  data dir         {}", self.data_dir.display());
        println!(
            "  events dir       {} ({})",
            self.events_dir.display(),
            if self.events_dir_writable {
                "writable"
            } else {
                "NOT writable"
            }
        );
        println!(
            "  state dir        {} ({})",
            self.state_dir.display(),
            if self.state_dir_writable {
                "writable"
            } else {
                "NOT writable"
            }
        );
        println!(
            "  metrics dir      {} ({})",
            self.metrics_dir.display(),
            if self.metrics_dir_writable {
                "writable"
            } else {
                "NOT writable"
            }
        );
        println!("  known projects   {}", self.known_projects.len());
        if !self.schema_versions_applied.is_empty() {
            let v: Vec<String> = self
                .schema_versions_applied
                .iter()
                .map(|n| format!("v{n:03}"))
                .collect();
            println!("  schema (current) {}", v.join(", "));
        }
        if !self.notes.is_empty() {
            println!("\n{} note(s):", self.notes.len());
            for n in &self.notes {
                println!("  - {n}");
            }
        }
        if self.issues.is_empty() {
            println!("\n✓ all checks passed");
        } else {
            println!("\n{} issue(s):", self.issues.len());
            for i in &self.issues {
                println!("  - {i}");
            }
        }
    }
}

fn dir_writable(dir: &std::path::Path) -> bool {
    if std::fs::create_dir_all(dir).is_err() {
        return false;
    }
    let probe = dir.join(".tj-doctor-write-probe");
    let r = std::fs::write(&probe, b"ok").is_ok();
    let _ = std::fs::remove_file(&probe);
    r
}

/// Move all on-disk data for one project_hash to another. Used by the
/// `migrate-project` subcommand when a project's directory has been
/// moved on disk and the canonical-path hash no longer matches.
fn run_migrate_project(from: &std::path::Path, to: &std::path::Path, force: bool) -> Result<()> {
    let from_hash = tj_core::project_hash::from_path(from)
        .with_context(|| format!("compute project_hash for --from {from:?}"))?;
    let to_hash = tj_core::project_hash::from_path(to)
        .with_context(|| format!("compute project_hash for --to {to:?}"))?;

    if from_hash == to_hash {
        anyhow::bail!(
            "--from and --to resolve to the same project_hash ({from_hash}) — nothing to migrate"
        );
    }

    let events_dir = tj_core::paths::events_dir()?;
    let state_dir = tj_core::paths::state_dir()?;
    let metrics_dir = tj_core::paths::metrics_dir()?;

    // (source, destination) tuples to attempt to rename.
    let pairs = [
        (
            events_dir.join(format!("{from_hash}.jsonl")),
            events_dir.join(format!("{to_hash}.jsonl")),
        ),
        (
            state_dir.join(format!("{from_hash}.sqlite")),
            state_dir.join(format!("{to_hash}.sqlite")),
        ),
        (
            metrics_dir.join(format!("{from_hash}.jsonl")),
            metrics_dir.join(format!("{to_hash}.jsonl")),
        ),
    ];

    // Pre-flight: refuse overwrite of any destination unless --force.
    if !force {
        for (_src, dst) in &pairs {
            if dst.exists() {
                anyhow::bail!(
                    "destination already exists: {} — pass --force to overwrite",
                    dst.display()
                );
            }
        }
    }

    let mut moved: Vec<String> = Vec::new();
    for (src, dst) in &pairs {
        if !src.exists() {
            continue;
        }
        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)?;
        }
        if dst.exists() && force {
            std::fs::remove_file(dst).with_context(|| format!("remove existing {dst:?}"))?;
        }
        std::fs::rename(src, dst).with_context(|| format!("rename {src:?} -> {dst:?}"))?;
        moved.push(dst.display().to_string());
    }

    // Re-key the project_hash columns inside the (now renamed) SQLite.
    let new_state_path = state_dir.join(format!("{to_hash}.sqlite"));
    if new_state_path.exists() {
        let conn = tj_core::db::open(&new_state_path)?;
        conn.execute(
            "UPDATE tasks SET project_hash = ?1 WHERE project_hash = ?2",
            rusqlite::params![to_hash, from_hash],
        )?;
        conn.execute(
            "UPDATE index_state SET project_hash = ?1 WHERE project_hash = ?2",
            rusqlite::params![to_hash, from_hash],
        )?;
    }

    if moved.is_empty() {
        println!("no on-disk data found for project_hash {from_hash} — nothing to migrate");
    } else {
        println!("migrated {} file(s):", moved.len());
        for path in moved {
            println!("  {path}");
        }
        println!("  project_hash {from_hash} -> {to_hash}");
    }
    Ok(())
}

/// Minimal HTML attribute/text escape. Five characters cover the body of
/// `text/html` for our use case (no script context, no URL emission).
fn html_escape(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for c in s.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&#39;"),
            _ => out.push(c),
        }
    }
    out
}

const HTML_TIMELINE_CSS: &str = r#"
:root { color-scheme: light dark; --fg:#222; --bg:#fafafa; --muted:#666; --accent:#0366d6; }
@media (prefers-color-scheme: dark) { :root { --fg:#eee; --bg:#1a1a1a; --muted:#999; --accent:#58a6ff; } }
* { box-sizing: border-box; }
body { font: 14px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
       color: var(--fg); background: var(--bg); margin: 0; padding: 1.5rem; }
header h1 { margin: 0 0 1.5rem; font-size: 1.4rem; }
article { margin-bottom: 2rem; padding: 1rem 1.25rem; background: rgba(127,127,127,0.07);
          border-radius: 6px; }
article h2 { margin: 0; font-size: 1.05rem; font-weight: 600; }
.tid { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
       color: var(--accent); margin-right: 0.4em; }
.meta { color: var(--muted); font-size: 0.85rem; margin: 0.25rem 0 0.75rem; }
ol.timeline { list-style: none; margin: 0; padding-left: 0; }
ol.timeline li { padding: 0.4rem 0; border-top: 1px solid rgba(127,127,127,0.15); }
ol.timeline li:first-child { border-top: none; }
time { font-family: ui-monospace, monospace; color: var(--muted); margin-right: 0.6em; }
.type { display: inline-block; padding: 0 0.35em; margin-right: 0.4em; border-radius: 3px;
        font-size: 0.75rem; text-transform: uppercase; letter-spacing: 0.05em;
        background: rgba(127,127,127,0.15); }
.type-decision { background: rgba(3,102,214,0.18); color: var(--accent); }
.type-rejection { background: rgba(214,3,3,0.18); }
.type-evidence { background: rgba(40,167,69,0.18); }
.type-finding { background: rgba(255,166,0,0.20); }
.suggested::after { content: " ?"; color: var(--muted); }
"#;

fn render_html_timeline(events: &[&tj_core::event::Event]) -> String {
    use std::collections::BTreeMap;

    let mut tasks: BTreeMap<String, Vec<&tj_core::event::Event>> = BTreeMap::new();
    for e in events {
        tasks.entry(e.task_id.clone()).or_default().push(e);
    }

    let mut out = String::new();
    out.push_str("<!doctype html>\n");
    out.push_str("<html lang=\"en\"><head>");
    out.push_str("<meta charset=\"utf-8\">");
    out.push_str("<meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">");
    out.push_str("<title>Task Journal — Export</title>");
    out.push_str("<style>");
    out.push_str(HTML_TIMELINE_CSS);
    out.push_str("</style>");
    out.push_str("</head><body>");
    out.push_str("<header><h1>Task Journal — Export</h1></header>");
    out.push_str("<main>");

    for (task_id, task_events) in &tasks {
        let title = task_events
            .iter()
            .find(|e| e.event_type == tj_core::event::EventType::Open)
            .and_then(|e| {
                e.meta
                    .get("title")
                    .and_then(|v| v.as_str())
                    .map(String::from)
                    .or_else(|| Some(e.text.clone()))
            })
            .unwrap_or_else(|| "(untitled)".into());

        let closed = task_events
            .last()
            .map(|e| e.event_type == tj_core::event::EventType::Close)
            .unwrap_or(false);
        let status = if closed { "closed" } else { "open" };

        let created = task_events
            .first()
            .map(|e| e.timestamp.as_str())
            .unwrap_or("?");

        out.push_str("<article>");
        out.push_str(&format!(
            "<h2><span class=\"tid\">{}</span>{}</h2>",
            html_escape(task_id),
            html_escape(&title)
        ));
        out.push_str(&format!(
            "<p class=\"meta\">status: {} · created: {}</p>",
            status,
            html_escape(created)
        ));
        out.push_str("<ol class=\"timeline\">");
        for e in task_events {
            let etype = serde_json::to_value(e.event_type)
                .ok()
                .and_then(|v| v.as_str().map(String::from))
                .unwrap_or_else(|| "unknown".into());
            let suggested_class = if matches!(e.status, tj_core::event::EventStatus::Suggested) {
                " suggested"
            } else {
                ""
            };
            out.push_str(&format!(
                "<li class=\"event{}\"><time>{}</time>\
                 <span class=\"type type-{}\">{}</span>{}</li>",
                suggested_class,
                html_escape(&e.timestamp),
                html_escape(&etype),
                html_escape(&etype),
                html_escape(&e.text)
            ));
        }
        out.push_str("</ol>");
        out.push_str("</article>");
    }

    out.push_str("</main></body></html>\n");
    out
}

/// Resolve `<events_dir>/../../pending` for the current project. Mirrors
/// the path layout used by `persist_pending`.
fn pending_dir() -> Result<std::path::PathBuf> {
    let cwd = std::env::current_dir()?;
    let project_hash = tj_core::project_hash::from_path(&cwd)?;
    let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
    let dir = events_path
        .parent()
        .and_then(|p| p.parent())
        .ok_or_else(|| anyhow::anyhow!("events_dir has no grandparent"))?
        .join("pending");
    Ok(dir)
}

fn run_pending_list() -> Result<()> {
    let dir = pending_dir()?;
    if !dir.exists() {
        println!("(no pending entries)");
        return Ok(());
    }
    let mut entries: Vec<(String, String, String, u32)> = Vec::new();
    for entry in std::fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        let id = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("?")
            .to_string();
        let body = std::fs::read_to_string(&path)?;
        let v: serde_json::Value = serde_json::from_str(&body)?;
        let queued_at = v
            .get("queued_at")
            .and_then(|x| x.as_str())
            .unwrap_or("?")
            .to_string();
        let text_preview: String = v
            .get("text")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .chars()
            .take(72)
            .collect();
        let attempts = v.get("attempts").and_then(|x| x.as_u64()).unwrap_or(0) as u32;
        let dead_marker = if id.ends_with(".dead") { " [DEAD]" } else { "" };
        entries.push((id, queued_at, text_preview, attempts));
        let _ = dead_marker;
    }
    if entries.is_empty() {
        println!("(no pending entries)");
        return Ok(());
    }
    println!("{:<26} {:<25} attempts  text", "id", "queued_at");
    for (id, qa, text, attempts) in &entries {
        println!("{id:<26} {qa:<25} {attempts:<8}  {text}");
    }
    Ok(())
}

fn run_pending_retry(
    mock_etype: Option<&str>,
    mock_tid: Option<&str>,
    mock_conf: Option<f64>,
) -> Result<()> {
    let dir = pending_dir()?;
    if !dir.exists() {
        println!("(no pending entries)");
        return Ok(());
    }
    let cwd = std::env::current_dir()?;
    let project_hash = tj_core::project_hash::from_path(&cwd)?;
    let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));

    let mut succeeded = 0usize;
    let mut died = 0usize;
    let mut still_pending = 0usize;
    for entry in std::fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }
        if path
            .file_stem()
            .and_then(|s| s.to_str())
            .map(|s| s.ends_with(".dead"))
            .unwrap_or(false)
        {
            continue; // already dead, skip
        }
        let body = std::fs::read_to_string(&path)?;
        let mut v: serde_json::Value = serde_json::from_str(&body)?;
        // v0.6.2: skip v2 entries here — those are async-queued events
        // owned by classify-worker. The retry path is for legacy v1
        // entries that already failed in the inline path.
        if v.get("schema").and_then(|x| x.as_str()) == Some("v2") {
            continue;
        }
        let attempts = v.get("attempts").and_then(|x| x.as_u64()).unwrap_or(0) as u32;
        let text = v
            .get("text")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();

        // The real retry path would call the classifier. The CI-safe
        // mock branch lets tests drive a deterministic outcome.
        let outcome: anyhow::Result<()> = match (mock_etype, mock_tid) {
            (Some(etype), Some(tid)) => {
                let mut event = tj_core::event::Event::new(
                    tid,
                    parse_event_type(etype)?,
                    tj_core::event::Author::Classifier,
                    tj_core::event::Source::Hook,
                    text,
                );
                event.confidence = mock_conf;
                event.status = tj_core::classifier::decide_status(mock_conf.unwrap_or(1.0));
                let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
                writer.append(&event)?;
                writer.flush_durable()?;
                Ok(())
            }
            _ => Err(anyhow::anyhow!(
                "no real classifier wired in retry path yet — pass --mock-* for tests, or run install-hooks and let the hook drain the queue"
            )),
        };

        match outcome {
            Ok(()) => {
                std::fs::remove_file(&path)?;
                succeeded += 1;
            }
            Err(_) => {
                let new_attempts = attempts + 1;
                if new_attempts >= PENDING_MAX_ATTEMPTS {
                    let dead_path = path.with_file_name(format!(
                        "{}.dead.json",
                        path.file_stem().and_then(|s| s.to_str()).unwrap_or("dead")
                    ));
                    std::fs::rename(&path, &dead_path)?;
                    died += 1;
                } else {
                    if let Some(obj) = v.as_object_mut() {
                        obj.insert(
                            "attempts".into(),
                            serde_json::Value::Number(new_attempts.into()),
                        );
                    }
                    std::fs::write(&path, serde_json::to_string_pretty(&v)?)?;
                    still_pending += 1;
                }
            }
        }
    }
    println!(
        "pending retry: {succeeded} drained, {still_pending} still pending, {died} marked dead"
    );
    Ok(())
}

fn run_doctor() -> Result<DoctorReport> {
    let mut issues: Vec<String> = Vec::new();
    let mut notes: Vec<String> = Vec::new();

    // 1. claude binary in PATH (note, not issue — API backend works without it)
    let claude_check = PCommand::new("claude").arg("--version").output();
    let (claude_in_path, claude_version) = match claude_check {
        Ok(out) if out.status.success() => {
            let v = String::from_utf8_lossy(&out.stdout).trim().to_string();
            (true, Some(v))
        }
        Ok(_) | Err(_) => {
            notes.push(
                "claude CLI not on PATH — that's fine if you use the API backend \
                 (set ANTHROPIC_API_KEY). For the CLI backend (free with Pro/Max), \
                 install Claude Code from https://claude.com/claude-code"
                    .into(),
            );
            (false, None)
        }
    };

    // 2. data dir + sub-dir writability
    let data_dir = tj_core::paths::data_dir()?;
    let events_dir = tj_core::paths::events_dir()?;
    let state_dir = tj_core::paths::state_dir()?;
    let metrics_dir = tj_core::paths::metrics_dir()?;
    let events_dir_writable = dir_writable(&events_dir);
    let state_dir_writable = dir_writable(&state_dir);
    let metrics_dir_writable = dir_writable(&metrics_dir);
    if !events_dir_writable {
        issues.push(format!("events dir not writable: {}", events_dir.display()));
    }
    if !state_dir_writable {
        issues.push(format!("state dir not writable: {}", state_dir.display()));
    }
    if !metrics_dir_writable {
        issues.push(format!(
            "metrics dir not writable: {}",
            metrics_dir.display()
        ));
    }

    // 3. known projects (from state dir SQLite stems)
    let known_projects = tj_core::db::list_all_projects(&state_dir).unwrap_or_default();

    // 4. schema versions for the current cwd's project (if any).
    let schema_versions_applied = (|| -> Result<Vec<i64>> {
        let cwd = std::env::current_dir()?;
        let project_hash = tj_core::project_hash::from_path(&cwd)?;
        let state_path = state_dir.join(format!("{project_hash}.sqlite"));
        if !state_path.exists() {
            return Ok(Vec::new());
        }
        let conn = tj_core::db::open(&state_path)?;
        let mut stmt = conn.prepare("SELECT version FROM schema_migrations ORDER BY version")?;
        let v: Vec<i64> = stmt
            .query_map([], |r| r.get::<_, i64>(0))?
            .collect::<Result<_, _>>()?;
        Ok(v)
    })()
    .unwrap_or_default();

    Ok(DoctorReport {
        task_journal_version: env!("CARGO_PKG_VERSION"),
        claude_in_path,
        claude_version,
        data_dir,
        events_dir,
        state_dir,
        metrics_dir,
        events_dir_writable,
        state_dir_writable,
        metrics_dir_writable,
        known_projects,
        schema_versions_applied,
        issues,
        notes,
    })
}

#[derive(Parser)]
#[command(name = "task-journal", version, about = "Task Journal CLI", long_about = None)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Create a new task (writes an `open` event).
    Create {
        /// Task title (one line).
        title: String,
        /// Optional initial context paragraph.
        #[arg(long)]
        context: Option<String>,
        /// Optional one-line goal: what is this task trying to achieve?
        /// Renders prominently in `pack`/TUI; can be filled in later
        /// with `task-journal goal <id> "<text>"`.
        #[arg(long)]
        goal: Option<String>,
    },
    /// Inspect events for a project.
    Events {
        #[command(subcommand)]
        action: EventsCmd,
    },
    /// Rebuild SQLite state from the JSONL log.
    RebuildState,
    /// Render and print the resume pack for a task.
    Pack {
        /// Task id (e.g. tj-7f3a).
        task_id: String,
        /// Output mode: compact|full.
        #[arg(long, default_value = "compact")]
        mode: String,
    },
    /// Append a typed event to a task.
    Event {
        task_id: String,
        /// Event type: hypothesis, finding, evidence, decision, rejection,
        /// constraint, correction, reopen, supersede, close, redirect.
        #[arg(long, name = "type")]
        r#type: String,
        /// Event text body.
        #[arg(long)]
        text: String,
        /// Optional event id this corrects (for type=correction).
        #[arg(long)]
        corrects: Option<String>,
        /// Optional event id this supersedes (for type=supersede).
        #[arg(long)]
        supersedes: Option<String>,
    },
    /// Close a task (writes a `close` event).
    Close {
        task_id: String,
        #[arg(long)]
        reason: Option<String>,
        /// One-line outcome: what shipped / why we stopped.
        #[arg(long)]
        outcome: Option<String>,
        /// Structured tag for the outcome: `done`, `abandoned`, or
        /// `superseded`. Free-form text via `--outcome` is the
        /// primary field; the tag is for filtering / aggregation.
        #[arg(long)]
        outcome_tag: Option<String>,
    },
    /// Reopen a previously closed task (writes a `reopen` event and
    /// flips status back to `open`). Use when the same scope comes
    /// back, e.g. a regression on a shipped fix or a follow-up bug
    /// that belongs in the original chain rather than a new task.
    Reopen {
        task_id: String,
        /// One-line reason for reopening (regression, follow-up, etc).
        #[arg(long)]
        reason: Option<String>,
    },
    /// List open tasks with no activity for N+ days. Use to clean up
    /// tasks that auto-opened, got a few events, then went silent —
    /// candidates for `task-journal close --outcome-tag abandoned`.
    Stale {
        /// Inactivity threshold in days. Default 7.
        #[arg(long, default_value_t = 7)]
        days: i64,
    },
    /// Garbage-collect the pending classifier queue. Removes entries
    /// older than N days OR marked dead by retry exhaustion. Run after
    /// classifier auth was broken for a while and the queue grew
    /// stale.
    PendingGc {
        /// Age threshold in days. Default 7.
        #[arg(long, default_value_t = 7)]
        days: i64,
    },
    /// Set or update the goal of an existing task.
    Goal {
        task_id: String,
        /// New goal text (one line). Pass an empty string to clear.
        text: String,
    },
    /// Manage external references on a task (beads ids, GitHub PRs,
    /// JIRA issues — anything that ties this journal entry to work
    /// outside the journal).
    External {
        task_id: String,
        /// Reference to append, e.g. `beads:claude-memory-rsw`,
        /// `github:#42`. Append-only; pass multiple times to add
        /// several references over time.
        #[arg(long = "add")]
        add: String,
    },
    /// Re-run artifact extraction over every event of a task and
    /// refresh the pack cache. Use after upgrading from v0.4.x — older
    /// events were ingested before the artifact column was populated,
    /// so they have empty `artifacts` JSON until reclassify backfills.
    Reclassify { task_id: String },
    /// Full-text search across events (FTS5).
    Search {
        /// Query string.
        query: String,
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Search across all projects on this machine, not just the cwd one.
        #[arg(long)]
        all_projects: bool,
    },
    /// Append a correction event referencing an earlier event_id.
    EventCorrect {
        #[arg(long)]
        corrects: String,
        #[arg(long)]
        task: String,
        #[arg(long)]
        text: String,
    },
    /// Install Claude Code hooks that ingest events into the task journal.
    InstallHooks {
        /// Scope: user (~/.claude/settings.json) or project (./.claude/settings.json).
        #[arg(long, default_value = "user")]
        scope: String,
        /// Remove our hook entries instead of installing.
        #[arg(long)]
        uninstall: bool,
        /// Override classifier command. Writes env.TJ_CLASSIFIER_CLI into settings.json
        /// so wrappers (aimux, litellm, etc.) work without manual env setup.
        /// Default: classifier uses `claude -p`.
        #[arg(long)]
        classifier_command: Option<String>,
        /// After installing hooks, retro-import existing Claude Code session
        /// history for the current project. Equivalent to running
        /// `task-journal backfill` afterwards. Onboarding shortcut.
        #[arg(long)]
        backfill: bool,
    },
    /// Show local classifier and journal statistics.
    Stats,
    /// Interactive TUI: browse the journal's tasks (default) or, with
    /// `--chats`, the underlying Claude Code chat-session JSONLs.
    #[command(alias = "tui")]
    Ui {
        /// Project path override (default: current directory).
        #[arg(long)]
        project: Option<String>,
        /// Legacy mode: open the chat-session browser instead of the
        /// task list. Lets you read raw Claude Code session history
        /// when the task journal alone isn't enough.
        #[arg(long)]
        chats: bool,
    },
    /// Import task-journal events from existing Claude Code session history.
    /// Parses JSONL session files and creates tasks retroactively.
    Backfill {
        /// Dry run: show what would be imported without writing.
        #[arg(long)]
        dry_run: bool,
        /// Limit to N most recent sessions (default: all).
        #[arg(long)]
        limit: Option<usize>,
        /// Project path override (default: current directory).
        #[arg(long)]
        project: Option<String>,
    },
    /// Export tasks as Markdown or JSON to stdout.
    Export {
        /// Output format: md, json.
        #[arg(long, default_value = "md")]
        format: String,
        /// Export specific task by ID (default: all open tasks).
        #[arg(long)]
        task: Option<String>,
        /// Project path override.
        #[arg(long)]
        project: Option<String>,
    },
    /// Self-check the install: claude binary, data dirs, known projects,
    /// schema migrations. Exits 0 when all checks pass; 1 otherwise.
    Doctor {
        /// Emit a machine-readable JSON report instead of human text.
        #[arg(long)]
        json: bool,
    },
    /// Inspect or retry classifier failures queued under pending/.
    /// The auto-capture hook writes a pending entry whenever the
    /// classifier errors (network down, rate limit, missing API key);
    /// this command surfaces them.
    Pending {
        #[command(subcommand)]
        action: PendingCmd,
    },
    /// Re-key on-disk data when a project moved on disk. The project_hash
    /// is derived from the canonical path, so a moved project orphans its
    /// own data; this command renames the JSONL + SQLite + metrics files.
    MigrateProject {
        /// Old project path (the data we want to keep).
        #[arg(long, value_name = "PATH")]
        from: PathBuf,
        /// New project path (where the project lives now).
        #[arg(long, value_name = "PATH")]
        to: PathBuf,
        /// Overwrite the destination if data already exists for it.
        #[arg(long)]
        force: bool,
    },
    /// Hook entry point: ingest a chat chunk through the classifier.
    ///
    /// When `--kind` and `--text` are both omitted, reads the Claude Code
    /// hook payload as JSON from stdin (the actual production wiring).
    /// `--kind` / `--text` remain for tests and ad-hoc use.
    IngestHook {
        /// Hook kind: UserPromptSubmit | PostToolUse | Stop | SessionStart.
        /// If omitted, derived from stdin JSON (`hook_event_name`).
        #[arg(long)]
        kind: Option<String>,
        /// The chat chunk text. If omitted, derived from stdin JSON
        /// (`prompt` for UserPromptSubmit, synthesized from
        /// tool_name+input+response for PostToolUse, etc.).
        #[arg(long)]
        text: Option<String>,
        /// Classifier backend: "cli" uses `claude -p` (free with your Pro/Max
        /// subscription) or "api" uses Anthropic API (requires `ANTHROPIC_API_KEY`).
        /// Default: cli.
        #[arg(long, default_value = "cli")]
        backend: String,
        /// Test/dev override: bypass classifier and force this event type. Hidden from --help.
        #[arg(long, hide = true)]
        mock_event_type: Option<String>,
        /// Test/dev override: target task id. Hidden from --help.
        #[arg(long, hide = true)]
        mock_task_id: Option<String>,
        /// Test/dev override: confidence value. Hidden from --help.
        #[arg(long, hide = true)]
        mock_confidence: Option<f64>,
    },
    /// Internal: drain pending v2 entries and classify each one.
    /// Spawned as a detached child by ingest-hook so the hook can
    /// return in <100ms instead of blocking 5-30s on `claude -p`.
    /// Holds a project-scoped file lock — only one worker per project
    /// at a time. Hidden from --help; not a public API.
    #[command(hide = true)]
    ClassifyWorker {
        /// Classifier backend: "cli" or "api". Defaults to cli.
        #[arg(long, default_value = "cli")]
        backend: String,
    },
    /// One-line status snapshot for the Claude Code statusline. Prints
    /// `[tj-x9rz · open: N · pending: N · stale: N]`. Sub-100ms by
    /// design — wire it via `~/.claude/settings.json` `statusLine`.
    /// Hidden from --help; not a human command.
    #[command(hide = true)]
    Statusline,
    /// Cross-task search for `rejection` events matching a topic. Helpful
    /// when the agent is about to repeat a path that was already turned
    /// down — query the topic, see the prior rejection.
    Rejected {
        /// Search topic (FTS5 when possible, LIKE fallback for tokens
        /// containing FTS-unfriendly chars like `-`).
        topic: String,
        /// Search across all projects on this machine.
        #[arg(long)]
        all_projects: bool,
        #[arg(long, default_value_t = 20)]
        limit: usize,
        /// Restrict to events newer than N days.
        #[arg(long)]
        since: Option<i64>,
    },
    /// Render a task as PR-description Markdown (Summary, Changes,
    /// Why-this-approach, Verification, Affected). Reuses event log +
    /// artifacts; introduces no new tables.
    ExportPr {
        task_id: String,
    },
}

#[derive(Subcommand)]
enum EventsCmd {
    /// List events (most recent first).
    List {
        /// Limit to N events.
        #[arg(long, default_value_t = 20)]
        limit: usize,
    },
}

#[derive(Subcommand)]
enum PendingCmd {
    /// List queued classifier failures.
    List,
    /// Re-feed every pending entry through the classifier. Marks an
    /// entry as `<id>.dead.json` after PENDING_MAX_ATTEMPTS failures.
    Retry {
        /// Test/dev override: bypass classifier and force this event
        /// type. Hidden from --help.
        #[arg(long, hide = true)]
        mock_event_type: Option<String>,
        /// Test/dev override: target task id. Hidden from --help.
        #[arg(long, hide = true)]
        mock_task_id: Option<String>,
        /// Test/dev override: confidence value. Hidden from --help.
        #[arg(long, hide = true)]
        mock_confidence: Option<f64>,
    },
}

const PENDING_MAX_ATTEMPTS: u32 = 3;

fn main() -> Result<()> {
    let cli = Cli::parse();
    match cli.command {
        Commands::Create {
            title,
            context,
            goal,
        } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_dir = tj_core::paths::events_dir()?;
            let events_path = events_dir.join(format!("{project_hash}.jsonl"));
            std::fs::create_dir_all(&events_dir)?;

            let task_id = tj_core::new_task_id();
            let mut event = tj_core::event::Event::new(
                task_id.clone(),
                tj_core::event::EventType::Open,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                context.clone().unwrap_or_else(|| title.clone()),
            );
            event.meta = serde_json::json!({ "title": title });

            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;

            // If --goal was provided, ingest the open event into SQLite
            // (so the row exists) and write the goal column. Skipping
            // this when --goal is absent keeps the SQLite hot path
            // exclusive to ingest-hook / pack callers.
            if let Some(g) = goal {
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                let conn = tj_core::db::open(&state_path)?;
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                tj_core::db::set_task_goal(&conn, &task_id, &g)?;
            }

            println!("{}", task_id);
        }
        Commands::Events { action } => match action {
            EventsCmd::List { limit } => {
                let cwd = std::env::current_dir()?;
                let project_hash = tj_core::project_hash::from_path(&cwd)?;
                let events_path =
                    tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
                if !events_path.exists() {
                    println!("(no events yet)");
                    return Ok(());
                }
                let body = std::fs::read_to_string(&events_path)?;
                let mut events: Vec<tj_core::event::Event> = body
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .map(serde_json::from_str)
                    .collect::<Result<_, _>>()?;
                events.reverse();
                for e in events.into_iter().take(limit) {
                    let title = e
                        .meta
                        .get("title")
                        .and_then(|v| v.as_str())
                        .map(|s| s.to_string())
                        .unwrap_or_else(|| e.text.clone());
                    println!("{}  [{:?}]  {}", e.timestamp, e.event_type, title);
                }
            }
        },
        Commands::Pack { task_id, mode } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            let pmode = match mode.as_str() {
                "compact" => tj_core::pack::PackMode::Compact,
                "full" => tj_core::pack::PackMode::Full,
                other => anyhow::bail!("unknown mode: {other}"),
            };
            let pack = tj_core::pack::assemble(&conn, &task_id, pmode)?;
            print!("{}", pack.text);
        }
        Commands::RebuildState => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

            if !events_path.exists() {
                anyhow::bail!("no events file at {events_path:?}");
            }

            let conn = tj_core::db::open(&state_path)?;
            let n = tj_core::db::rebuild_state(&conn, &events_path, &project_hash)?;
            println!("rebuilt {n} events into {state_path:?}");
        }
        Commands::Event {
            task_id,
            r#type,
            text,
            corrects,
            supersedes,
        } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            std::fs::create_dir_all(events_path.parent().unwrap())?;

            let event_type = parse_event_type(&r#type)?;
            let mut event = tj_core::event::Event::new(
                &task_id,
                event_type,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                text,
            );
            event.corrects = corrects;
            event.supersedes = supersedes;

            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;
            println!("{}", event.event_id);
        }
        Commands::Close {
            task_id,
            reason,
            outcome,
            outcome_tag,
        } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

            // Validate the outcome_tag enum so users don't accumulate
            // arbitrary values in the column. Free-text lives in
            // `outcome`; the tag is for filter/aggregate.
            if let Some(tag) = outcome_tag.as_deref() {
                match tag {
                    "done" | "abandoned" | "superseded" => {}
                    other => anyhow::bail!(
                        "invalid --outcome-tag `{other}` (expected: done | abandoned | superseded)"
                    ),
                }
            }

            // Catch up the index then assert the task is real before we
            // append a close event for an id that never existed.
            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            if !tj_core::db::task_exists(&conn, &task_id)? {
                anyhow::bail!("task not found: {task_id}");
            }
            // Persist outcome BEFORE the close event so the cache wipe
            // inside set_task_outcome doesn't compete with subsequent
            // assemble calls. Both columns optional — caller can pass
            // neither and just get the close event.
            if let Some(o) = outcome.as_deref() {
                tj_core::db::set_task_outcome(&conn, &task_id, o, outcome_tag.as_deref())?;
            }
            drop(conn);

            let mut event = tj_core::event::Event::new(
                &task_id,
                tj_core::event::EventType::Close,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                reason.clone().unwrap_or_else(|| "(closed)".into()),
            );
            if let Some(r) = reason {
                event.meta = serde_json::json!({"reason": r});
            }

            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;
            println!("{}", event.event_id);
        }
        Commands::Stale { days } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            let stale = tj_core::db::stale_tasks(&conn, days)?;
            if stale.is_empty() {
                println!("(no stale tasks — all open tasks active within {days} days)");
            } else {
                println!("# Stale tasks (idle ≥ {days} days)\n");
                for t in stale {
                    println!(
                        "{}  {} days idle  {}  {}",
                        t.task_id, t.days_idle, t.last_event_at, t.title
                    );
                }
                println!(
                    "\nClose abandoned ones with: task-journal close <id> --outcome-tag abandoned --reason <why>"
                );
            }
        }
        Commands::PendingGc { days } => {
            let pending_dir = tj_core::paths::events_dir()?
                .parent()
                .ok_or_else(|| anyhow::anyhow!("events_dir has no parent"))?
                .join("pending");
            if !pending_dir.exists() {
                println!("(no pending dir — nothing to gc)");
                return Ok(());
            }
            let cutoff = chrono::Utc::now() - chrono::Duration::days(days);
            let mut removed = 0usize;
            for entry in std::fs::read_dir(&pending_dir)? {
                let entry = entry?;
                let path = entry.path();
                if path.extension().and_then(|s| s.to_str()) != Some("json") {
                    continue;
                }
                // Prefer the file's mtime over JSON parsing — pending
                // payloads include their own queued_at but are not
                // guaranteed parseable when the classifier corrupted
                // input mid-stream.
                let mtime = entry
                    .metadata()
                    .and_then(|m| m.modified())
                    .ok()
                    .and_then(|t| {
                        chrono::DateTime::<chrono::Utc>::from(t)
                            .signed_duration_since(cutoff)
                            .num_seconds()
                            .into()
                    });
                if let Some(secs) = mtime {
                    if secs < 0 && std::fs::remove_file(&path).is_ok() {
                        removed += 1;
                    }
                }
            }
            println!(
                "removed {} stale pending entries (older than {} days)",
                removed, days
            );
        }
        Commands::Reopen { task_id, reason } => {
            // The Reopen event itself flips tasks.status back to open
            // when ingested (db::apply_lifecycle handles this). The CLI
            // job is just to assert the task exists and write the event.
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            if !tj_core::db::task_exists(&conn, &task_id)? {
                anyhow::bail!("task not found: {task_id}");
            }
            drop(conn);

            let mut event = tj_core::event::Event::new(
                &task_id,
                tj_core::event::EventType::Reopen,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                reason.clone().unwrap_or_else(|| "(reopened)".into()),
            );
            if let Some(r) = reason {
                event.meta = serde_json::json!({"reason": r});
            }
            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;
            println!("{}", event.event_id);
        }
        Commands::Goal { task_id, text } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            if !tj_core::db::task_exists(&conn, &task_id)? {
                anyhow::bail!("task not found: {task_id}");
            }
            tj_core::db::set_task_goal(&conn, &task_id, &text)?;
            println!("ok");
        }
        Commands::External { task_id, add } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            if !tj_core::db::task_exists(&conn, &task_id)? {
                anyhow::bail!("task not found: {task_id}");
            }
            tj_core::db::add_task_external(&conn, &task_id, &add)?;
            println!("ok");
        }
        Commands::Reclassify { task_id } => {
            // Walk events_index for this task, re-run artifact extraction
            // over each event's text (looked up via search_fts), and
            // overwrite the artifacts column. Pack cache is wiped after
            // so the next render picks up the new artifacts block. Used
            // primarily to backfill v0.4.x events that were ingested
            // before extraction existed.
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
            let conn = tj_core::db::open(&state_path)?;
            if events_path.exists() {
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            }
            if !tj_core::db::task_exists(&conn, &task_id)? {
                anyhow::bail!("task not found: {task_id}");
            }
            let count = tj_core::db::reclassify_task_artifacts(&conn, &task_id)?;
            println!("reclassified {} events", count);
        }
        Commands::EventCorrect {
            corrects,
            task,
            text,
        } => {
            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            std::fs::create_dir_all(events_path.parent().unwrap())?;

            let mut event = tj_core::event::Event::new(
                &task,
                tj_core::event::EventType::Correction,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                text,
            );
            event.corrects = Some(corrects);
            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;
            println!("{}", event.event_id);
        }
        Commands::InstallHooks {
            scope,
            uninstall,
            classifier_command,
            backfill,
        } => {
            let settings_path = match scope.as_str() {
                "user" => {
                    let home =
                        std::env::var_os("HOME").ok_or_else(|| anyhow::anyhow!("HOME not set"))?;
                    std::path::PathBuf::from(home)
                        .join(".claude")
                        .join("settings.json")
                }
                "project" => std::env::current_dir()?
                    .join(".claude")
                    .join("settings.json"),
                other => anyhow::bail!("unknown scope: {other}"),
            };
            if let Some(p) = settings_path.parent() {
                std::fs::create_dir_all(p)?;
            }

            let mut current: serde_json::Value = if settings_path.exists() {
                serde_json::from_str(&std::fs::read_to_string(&settings_path)?)
                    .unwrap_or_else(|_| serde_json::json!({}))
            } else {
                serde_json::json!({})
            };

            let hooks_obj = current
                .as_object_mut()
                .ok_or_else(|| anyhow::anyhow!("settings is not a JSON object"))?;
            if uninstall {
                // Surgical removal: walk the `hooks` block, drop only
                // entries whose command contains "task-journal ingest-hook"
                // — leaves co-located third-party plugin hooks (token-pilot
                // etc.) intact. Old behavior `remove("hooks")` nuked
                // everyone's hooks; this is the bxl-bug fix.
                if let Some(hooks_block) =
                    hooks_obj.get_mut("hooks").and_then(|v| v.as_object_mut())
                {
                    let kinds: Vec<String> = hooks_block.keys().cloned().collect();
                    for kind in kinds {
                        let Some(arr) = hooks_block.get_mut(&kind).and_then(|v| v.as_array_mut())
                        else {
                            continue;
                        };
                        // Each entry is { matcher, hooks: [{type, command}, ...] }.
                        // Filter the inner array; keep only non-task-journal commands.
                        for entry in arr.iter_mut() {
                            let Some(inner) = entry.get_mut("hooks").and_then(|v| v.as_array_mut())
                            else {
                                continue;
                            };
                            inner.retain(|h| {
                                h.get("command")
                                    .and_then(|c| c.as_str())
                                    .map(|c| !c.contains("task-journal ingest-hook"))
                                    .unwrap_or(true)
                            });
                        }
                        // Drop matcher entries with empty inner arrays.
                        arr.retain(|entry| {
                            entry
                                .get("hooks")
                                .and_then(|v| v.as_array())
                                .map(|a| !a.is_empty())
                                .unwrap_or(true)
                        });
                        // If the whole kind is empty, remove it.
                        if arr.is_empty() {
                            hooks_block.remove(&kind);
                        }
                    }
                    // Empty hooks block → remove entirely so settings.json
                    // stays tidy when we were the only user.
                    if hooks_block.is_empty() {
                        hooks_obj.remove("hooks");
                    }
                }
                // Remove our env key too — preserve other env entries.
                if let Some(env) = hooks_obj.get_mut("env").and_then(|v| v.as_object_mut()) {
                    env.remove("TJ_CLASSIFIER_CLI");
                    // Drop empty env block to keep settings.json clean.
                    if env.is_empty() {
                        hooks_obj.remove("env");
                    }
                }
            } else {
                // Wrap with `|| true` so a failed classifier (network down, rate limit,
                // missing API key) NEVER breaks Claude Code. Failures land in pending/
                // and replay on next ingest.
                // Default to subscription-based classifier (`claude -p`).
                // Power users with API key can run install-hooks --backend=api below.
                // Claude Code pipes the hook payload as JSON on stdin; the
                // `--kind` / `--text` flags from earlier templates pointed
                // at env vars Claude Code never sets and therefore always
                // fed the classifier empty text. Stdin-only is the correct
                // wiring (see claude-memory-rsw).
                let cmd = "task-journal ingest-hook --backend=cli || true";
                let entries = serde_json::json!({
                    "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                    "PostToolUse":     [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                    "Stop":            [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                    // SessionStart drives the auto resume-pack injection:
                    // ingest-hook short-circuits on this kind, queries open
                    // tasks for the current project, and emits the
                    // additionalContext envelope Claude Code expects.
                    "SessionStart":    [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                    // PreCompact: drop a marker decision event on the most-recent
                    // open task so the post-compact agent sees a clear boundary
                    // in the journal between pre- and post-compaction reasoning.
                    "PreCompact":      [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                });
                hooks_obj.insert("hooks".into(), entries);

                // Optional: set env.TJ_CLASSIFIER_CLI for users running classifier
                // through a wrapper (aimux, litellm, etc.). Claude Code reads this
                // env block and propagates the var to hook subprocesses, so users
                // don't need to mess with bashrc.
                if let Some(cmd) = classifier_command {
                    let env = hooks_obj
                        .entry("env".to_string())
                        .or_insert_with(|| serde_json::json!({}));
                    let env_obj = env
                        .as_object_mut()
                        .ok_or_else(|| anyhow::anyhow!("settings.env is not a JSON object"))?;
                    env_obj.insert(
                        "TJ_CLASSIFIER_CLI".to_string(),
                        serde_json::Value::String(cmd),
                    );
                }
            }
            std::fs::write(&settings_path, serde_json::to_string_pretty(&current)?)?;
            println!("{}", settings_path.display());

            // Onboarding convenience: retro-import existing Claude Code history
            // so the journal isn't empty on day one. Always operates on the
            // current working directory; install-hooks scope is independent.
            // We re-exec ourselves rather than refactoring the (~150-line)
            // backfill body — keeps the pipe simple and the output identical
            // to a manual `task-journal backfill`.
            if !uninstall && backfill {
                let exe =
                    std::env::current_exe().context("locate task-journal binary for backfill")?;
                let status = std::process::Command::new(&exe)
                    .arg("backfill")
                    .status()
                    .with_context(|| format!("spawn `{} backfill`", exe.display()))?;
                if !status.success() {
                    eprintln!("backfill exited with {status}");
                }
            }
        }
        Commands::Stats => {
            let metrics_dir = tj_core::paths::metrics_dir()?;
            let mut total = 0usize;
            let mut confirmed = 0usize;
            let mut suggested = 0usize;
            let mut errors = 0usize;
            if metrics_dir.exists() {
                for entry in std::fs::read_dir(&metrics_dir)? {
                    let path = entry?.path();
                    if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
                        continue;
                    }
                    let body = std::fs::read_to_string(&path)?;
                    for line in body.lines().filter(|l| !l.trim().is_empty()) {
                        total += 1;
                        let v: serde_json::Value = match serde_json::from_str(line) {
                            Ok(v) => v,
                            Err(_) => {
                                errors += 1;
                                continue;
                            }
                        };
                        match v.get("status").and_then(|s| s.as_str()) {
                            Some("confirmed") => confirmed += 1,
                            Some("suggested") => suggested += 1,
                            _ => {}
                        }
                    }
                }
            }
            println!("classified: {total}");
            println!("  confirmed: {confirmed}");
            println!("  suggested: {suggested}");
            println!("  parse errors: {errors}");
            if total > 0 {
                let ratio = confirmed as f64 / total as f64 * 100.0;
                println!("  confirmed ratio: {ratio:.1}%");
            }
        }
        Commands::Doctor { json } => {
            let report = run_doctor()?;
            if json {
                println!("{}", serde_json::to_string_pretty(&report)?);
            } else {
                report.print_human();
            }
            if !report.issues.is_empty() {
                std::process::exit(1);
            }
        }
        Commands::MigrateProject { from, to, force } => {
            run_migrate_project(&from, &to, force)?;
        }
        Commands::Pending { action } => match action {
            PendingCmd::List => {
                run_pending_list()?;
            }
            PendingCmd::Retry {
                mock_event_type,
                mock_task_id,
                mock_confidence,
            } => {
                run_pending_retry(
                    mock_event_type.as_deref(),
                    mock_task_id.as_deref(),
                    mock_confidence,
                )?;
            }
        },
        Commands::IngestHook {
            kind,
            text,
            backend,
            mock_event_type,
            mock_task_id,
            mock_confidence,
        } => {
            // Recursion guard. The classifier spawns `claude -p` to do
            // the actual work; that nested claude invocation re-reads
            // ~/.claude/settings.json and would re-fire our hooks,
            // recursively calling ingest-hook → classifier → claude → …
            // Until v0.2.8 we relied on `--bare` to suppress the hooks
            // on the inner invocation, but --bare doesn't work with
            // subscription auth (claude-memory-0kk), so the classifier
            // now sets TJ_IN_CLASSIFIER=1 in the child env and we bail
            // here when we see it.
            if std::env::var("TJ_IN_CLASSIFIER").is_ok() {
                return Ok(());
            }

            // Resolve (kind, text) source: explicit args win; otherwise
            // read the Claude Code hook payload from stdin. The earlier
            // settings.json template interpolated `$CLAUDE_HOOK_NAME` /
            // `$CLAUDE_HOOK_TEXT` env vars that Claude Code does NOT set,
            // so production was always called with empty text and every
            // event ended up rejected — see claude-memory-rsw.
            let (kind, text) = match (kind, text) {
                (Some(k), Some(t)) => (k, t),
                _ => parse_hook_stdin()?,
            };

            let cwd = std::env::current_dir()?;
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
            std::fs::create_dir_all(events_path.parent().unwrap())?;

            // SessionStart: emit a JSON envelope with compact resume-packs of
            // open tasks so Claude Code injects them into its system context
            // automatically. This is the load-bearing UX for "the journal
            // remembers" — without it, users would have to call task_pack
            // manually each session. Empty stdout when no open tasks → no
            // injection, keeps system prompt clean for fresh projects.
            if kind == "SessionStart" {
                // Skip early on a clean machine: nothing to surface, and we
                // don't want SessionStart to spawn empty SQLite files in
                // every project Claude Code is opened in.
                if !events_path.exists() {
                    return Ok(());
                }
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                let conn = tj_core::db::open(&state_path)?;
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                let recent = recent_task_contexts(&conn, 3)?;
                if recent.is_empty() {
                    return Ok(());
                }
                let mut bundle = String::new();
                for tc in &recent {
                    let pack = tj_core::pack::assemble(
                        &conn,
                        &tc.task_id,
                        tj_core::pack::PackMode::Compact,
                    )?;
                    bundle.push_str(&pack.text);
                    bundle.push_str("\n\n");
                }
                let envelope = serde_json::json!({
                    "hookSpecificOutput": {
                        "hookEventName": "SessionStart",
                        "additionalContext": bundle.trim_end(),
                    }
                });
                println!("{}", serde_json::to_string(&envelope)?);
                return Ok(());
            }

            // PreCompact: Claude Code is about to compact the conversation.
            // Drop a marker decision event on the most-recent open task so
            // the post-compact agent sees a clear boundary in the journal.
            // The marker is intentionally minimal — a future v0.7.x may
            // synthesize a real summary if CC starts exposing one on stdin.
            if kind == "PreCompact" {
                if !events_path.exists() {
                    return Ok(());
                }
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                let conn = tj_core::db::open(&state_path)?;
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                let recent = recent_task_contexts(&conn, 1)?;
                let Some(tc) = recent.into_iter().next() else {
                    return Ok(());
                };
                let now = chrono::Utc::now()
                    .to_rfc3339_opts(chrono::SecondsFormat::Secs, true);
                let marker_text = format!(
                    "Conversation compacted at {now}; preceding events should be treated as a single reasoning unit."
                );
                let mut event = tj_core::event::Event::new(
                    &tc.task_id,
                    tj_core::event::EventType::Decision,
                    tj_core::event::Author::Classifier,
                    tj_core::event::Source::Hook,
                    marker_text,
                );
                event.confidence = Some(1.0);
                event.status = tj_core::event::EventStatus::Confirmed;
                let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
                writer.append(&event)?;
                writer.flush_durable()?;
                let metrics_path =
                    tj_core::paths::metrics_dir()?.join(format!("{project_hash}.jsonl"));
                let _ = tj_core::classifier::telemetry::append(
                    &metrics_path,
                    &tj_core::classifier::telemetry::TelemetryRecord {
                        timestamp: chrono::Utc::now()
                            .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
                        project_hash: project_hash.clone(),
                        task_id_guess: Some(tc.task_id.clone()),
                        event_type: "decision".into(),
                        confidence: 1.0,
                        status: "confirmed".into(),
                        error: None,
                    },
                );
                println!("{}", event.event_id);
                return Ok(());
            }

            // Drain any pending entries first (Task 10 fills the real-classifier branch).
            drain_pending(
                &events_path,
                mock_event_type.as_deref(),
                mock_task_id.as_deref(),
                mock_confidence,
            )?;

            // v0.6.3: drop empty-text events before queueing. PostToolUse
            // hooks for tools without a `tool_response` (SlashCommand,
            // background ops, etc.) used to reach the classifier with
            // text="" — wasting a haiku call per event and littering
            // pending/ with v1 dead entries. Mock path keeps the event
            // for explicit test coverage, so this guard runs only outside
            // mock paths.
            let is_mock_pre = mock_event_type.is_some() && mock_task_id.is_some();
            if !is_mock_pre && text.trim().is_empty() {
                return Ok(());
            }

            // v0.7.0 /rewind sentinel. When the user prepends `/rewind`
            // to their prompt they're telling us: the path I just walked
            // was wrong, ignore it. We don't mass-mark prior events as
            // rejected (too destructive — the agent might have learned
            // useful negatives along the way). Instead leave a single
            // correction event so any pack consumer sees the boundary.
            if !is_mock_pre && kind == "UserPromptSubmit" && is_rewind_prompt(&text) {
                if !events_path.exists() {
                    return Ok(());
                }
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                let conn = tj_core::db::open(&state_path)?;
                tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                let recent = recent_task_contexts(&conn, 1)?;
                let Some(tc) = recent.into_iter().next() else {
                    return Ok(());
                };
                let mut event = tj_core::event::Event::new(
                    &tc.task_id,
                    tj_core::event::EventType::Correction,
                    tj_core::event::Author::User,
                    tj_core::event::Source::Hook,
                    "User invoked /rewind — preceding events on this task should be reconsidered. They may have been part of a path the user explicitly rolled back.".to_string(),
                );
                event.confidence = Some(1.0);
                event.status = tj_core::event::EventStatus::Confirmed;
                let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
                writer.append(&event)?;
                writer.flush_durable()?;
                println!("{}", event.event_id);
                return Ok(());
            }

            // v0.6.2 fork-bomb fix. The real-classifier path used to run
            // `claude -p` synchronously inside the hook, blocking each
            // UserPromptSubmit/PostToolUse/Stop for 5-30s. Symptoms:
            // ~19 stale ingest-hook + task-journal-mcp procs accumulated
            // within minutes (claude-memory-9ty). Now: queue the event
            // to pending/<id>.json (schema v2) and spawn a detached
            // classify-worker child. Hook returns in <100ms.
            //
            // Mock path stays synchronous — many tests rely on it. The
            // env override TJ_INGEST_SYNC=1 also forces sync, used by
            // tests that exercise the real-classifier code path with
            // /bin/false stubs.
            let force_sync = std::env::var("TJ_INGEST_SYNC")
                .ok()
                .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
                .unwrap_or(false);
            let is_mock = mock_event_type.is_some() && mock_task_id.is_some();
            if !is_mock && !force_sync {
                let _ = persist_pending_v2(
                    &events_path,
                    &kind,
                    &text,
                    &project_hash,
                    &backend,
                )?;
                // Fire-and-forget worker. Errors here are best-effort —
                // a failure to spawn just means the entry sits in
                // pending/ until the next hook fires another spawn.
                let _ = spawn_classify_worker(&backend);
                return Ok(());
            }

            // Derive author_hint from hook kind: user prompts → "user", everything else → "assistant"
            let author_hint = if kind.contains("UserPrompt") {
                "user"
            } else {
                "assistant"
            };

            let (etype, task_id, confidence, evidence_strength, suggested_text) =
                if let (Some(t), Some(tid)) = (mock_event_type.as_deref(), mock_task_id.as_deref())
                {
                    (
                        parse_event_type(t)?,
                        tid.to_string(),
                        mock_confidence.unwrap_or(1.0),
                        None,
                        None,
                    )
                } else {
                    let state_path =
                        tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                    let conn = tj_core::db::open(&state_path)?;
                    if events_path.exists() {
                        tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                    }
                    let mut recent = recent_task_contexts(&conn, 5)?;
                    if recent.is_empty() {
                        // No open tasks. v0.5.0 Phase A: auto-open a new
                        // task from the user's prompt so subsequent
                        // events have somewhere to land. Without this
                        // every fresh session was a black hole — events
                        // dropped silently because there was nothing to
                        // classify against. Opt-out via
                        // TJ_AUTO_OPEN_TASKS=0; only fires for
                        // UserPromptSubmit (assistant tool calls
                        // shouldn't conjure tasks).
                        let auto_open_disabled = std::env::var("TJ_AUTO_OPEN_TASKS")
                            .ok()
                            .map(|v| v == "0" || v.eq_ignore_ascii_case("false"))
                            .unwrap_or(false);
                        if auto_open_disabled || !kind.contains("UserPrompt") {
                            return Ok(());
                        }
                        let new_task =
                            auto_open_task_from_prompt(&events_path, &project_hash, &conn, &text)?;
                        recent.push(new_task);
                    }

                    use tj_core::classifier::Classifier;
                    let classifier: Box<dyn Classifier> = match backend.as_str() {
                        "cli" => Box::new(tj_core::classifier::cli::ClaudeCliClassifier::default()),
                        "api" => {
                            Box::new(tj_core::classifier::http::AnthropicClassifier::from_env()?)
                        }
                        other => {
                            anyhow::bail!("unknown backend: {other} (expected `cli` or `api`)")
                        }
                    };
                    let input = tj_core::classifier::ClassifyInput {
                        text: text.clone(),
                        author_hint: author_hint.into(),
                        recent_tasks: recent,
                    };
                    let out = match classifier.classify(&input) {
                        Ok(o) => o,
                        Err(e) => {
                            persist_pending(&events_path, &text, &e.to_string())?;
                            return Ok(());
                        }
                    };

                    let Some(tid) = out.task_id_guess else {
                        return Ok(());
                    };

                    // Journal-integrity safeguards. The classifier sometimes
                    // mis-attributes events to old or closed tasks (no fault
                    // of the model — its prompt only sees recent_tasks). We
                    // reject three patterns that produce confusing journals:
                    //
                    //   1. Stop-hook → Close event. The Stop hook fires at
                    //      every Claude Code session end. Session ending
                    //      != task done. Closes happen via explicit
                    //      `task-journal close <id>` only.
                    //   2. task_id_guess pointing at a non-existent task —
                    //      route to pending so the user can decide later.
                    //   3. task_id_guess pointing at a CLOSED task — same
                    //      treatment; closed tasks must stay closed.
                    use tj_core::event::EventType;
                    if matches!(out.event_type, EventType::Close) && kind == "Stop" {
                        return Ok(());
                    }
                    match tj_core::db::task_status(&conn, &tid)? {
                        None => {
                            persist_pending(
                                &events_path,
                                &text,
                                &format!("task_id_guess `{tid}` not found"),
                            )?;
                            return Ok(());
                        }
                        Some(s) if s == "closed" => {
                            persist_pending(
                                &events_path,
                                &text,
                                &format!("task_id_guess `{tid}` is closed"),
                            )?;
                            return Ok(());
                        }
                        _ => {}
                    }

                    (
                        out.event_type,
                        tid,
                        out.confidence,
                        out.evidence_strength,
                        Some(out.suggested_text),
                    )
                };

            // Use classifier's suggested_text if available (it's more concise and specific),
            // fall back to raw hook text for mock/manual events.
            let event_text = suggested_text.unwrap_or(text);

            let mut event = tj_core::event::Event::new(
                &task_id,
                etype,
                tj_core::event::Author::Classifier,
                tj_core::event::Source::Hook,
                event_text,
            );
            event.confidence = Some(confidence);
            event.status = tj_core::classifier::decide_status(confidence);
            event.evidence_strength = evidence_strength;

            let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
            writer.append(&event)?;
            writer.flush_durable()?;

            // Append telemetry. Errors here MUST NOT fail the hook (best-effort).
            let metrics_path = tj_core::paths::metrics_dir()?.join(format!("{project_hash}.jsonl"));
            let etype_str = serde_json::to_value(etype)?
                .as_str()
                .unwrap_or("?")
                .to_string();
            let status_str = serde_json::to_value(event.status)?
                .as_str()
                .unwrap_or("?")
                .to_string();
            let _ = tj_core::classifier::telemetry::append(
                &metrics_path,
                &tj_core::classifier::telemetry::TelemetryRecord {
                    timestamp: chrono::Utc::now()
                        .to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
                    project_hash: project_hash.clone(),
                    task_id_guess: Some(task_id.clone()),
                    event_type: etype_str,
                    confidence,
                    status: status_str,
                    error: None,
                },
            );

            println!("{}", event.event_id);
        }
        Commands::ClassifyWorker { backend } => {
            run_classify_worker(&backend)?;
        }
        Commands::Export {
            format,
            task,
            project,
        } => {
            let cwd = match project {
                Some(p) => std::path::PathBuf::from(p),
                None => std::env::current_dir()?,
            };
            let project_hash = tj_core::project_hash::from_path(&cwd)?;
            let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));

            if !events_path.exists() {
                anyhow::bail!("no events file at {events_path:?}");
            }

            let body = std::fs::read_to_string(&events_path)?;
            let all_events: Vec<tj_core::event::Event> = body
                .lines()
                .filter(|l| !l.trim().is_empty())
                .map(serde_json::from_str)
                .collect::<Result<_, _>>()?;

            // Filter to specific task if requested.
            let events: Vec<&tj_core::event::Event> = if let Some(ref tid) = task {
                all_events.iter().filter(|e| e.task_id == *tid).collect()
            } else {
                all_events.iter().collect()
            };

            if events.is_empty() {
                if let Some(tid) = task {
                    anyhow::bail!("no events found for task {tid}");
                } else {
                    anyhow::bail!("no events in project");
                }
            }

            match format.as_str() {
                "json" => {
                    let json = serde_json::to_string_pretty(&events)?;
                    println!("{json}");
                }
                "md" => {
                    println!("# Task Journal Export\n");

                    // Group events by task_id.
                    let mut tasks: std::collections::BTreeMap<String, Vec<&tj_core::event::Event>> =
                        std::collections::BTreeMap::new();
                    for e in &events {
                        tasks.entry(e.task_id.clone()).or_default().push(e);
                    }

                    for (task_id, task_events) in &tasks {
                        // Derive title from the first open event's meta, or text.
                        let title = task_events
                            .iter()
                            .find(|e| e.event_type == tj_core::event::EventType::Open)
                            .and_then(|e| {
                                e.meta
                                    .get("title")
                                    .and_then(|v| v.as_str())
                                    .map(String::from)
                                    .or_else(|| Some(e.text.clone()))
                            })
                            .unwrap_or_else(|| "(untitled)".into());

                        // Determine status: closed if last event is close, else open.
                        let status = if task_events
                            .last()
                            .map(|e| e.event_type == tj_core::event::EventType::Close)
                            .unwrap_or(false)
                        {
                            "closed"
                        } else {
                            "open"
                        };

                        // Created timestamp from first event.
                        let created = task_events
                            .first()
                            .map(|e| e.timestamp.as_str())
                            .unwrap_or("?");

                        println!("## [{task_id}] {title}");
                        println!("**Status**: {status}  ");
                        println!("**Created**: {created}\n");
                        println!("### Timeline");
                        for e in task_events {
                            let etype = serde_json::to_value(e.event_type)
                                .ok()
                                .and_then(|v| v.as_str().map(String::from))
                                .unwrap_or_else(|| "?".into());
                            println!("- **[{}] {}**: {}", e.timestamp, etype, e.text);
                        }
                        println!();
                    }
                }
                "html" => {
                    print!("{}", render_html_timeline(&events));
                }
                "sqlite" => {
                    // Snapshot the derived SQLite state. VACUUM INTO
                    // produces a clean, defragmented copy at the target
                    // path; we then shovel its bytes to stdout so the
                    // user can `> backup.sqlite`.
                    //
                    // Always rebuild from JSONL first so the snapshot
                    // reflects every event ever appended, not just what
                    // the latest ingest happened to capture.
                    let state_path =
                        tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                    let conn = tj_core::db::open(&state_path)?;
                    tj_core::db::rebuild_state(&conn, &events_path, &project_hash)?;

                    let tmp = tempfile::TempDir::new()?;
                    let out_path = tmp.path().join("export.sqlite");
                    conn.execute(
                        "VACUUM INTO ?1",
                        rusqlite::params![out_path.to_string_lossy().into_owned()],
                    )?;
                    drop(conn);

                    let bytes = std::fs::read(&out_path)?;
                    use std::io::Write;
                    std::io::stdout()
                        .lock()
                        .write_all(&bytes)
                        .context("write sqlite snapshot to stdout")?;
                }
                other => anyhow::bail!(
                    "unknown format: {other} (expected `md`, `json`, `html`, or `sqlite`)"
                ),
            }
        }
        Commands::Search {
            query,
            limit,
            all_projects,
        } => {
            if all_projects {
                let state_dir = tj_core::paths::state_dir()?;
                let hashes = tj_core::db::list_all_projects(&state_dir)?;
                for hash in hashes {
                    let path = state_dir.join(format!("{hash}.sqlite"));
                    let conn = match rusqlite::Connection::open(&path) {
                        Ok(c) => c,
                        Err(_) => continue,
                    };
                    let mut stmt = match conn.prepare(
                        "SELECT DISTINCT task_id FROM search_fts WHERE search_fts MATCH ?1 LIMIT ?2"
                    ) {
                        Ok(s) => s,
                        Err(_) => continue,
                    };
                    let rows = match stmt.query_map(rusqlite::params![&query, limit as i64], |r| {
                        r.get::<_, String>(0)
                    }) {
                        Ok(r) => r,
                        Err(_) => continue,
                    };
                    for id in rows.flatten() {
                        println!("{hash}\t{id}");
                    }
                }
            } else {
                let cwd = std::env::current_dir()?;
                let project_hash = tj_core::project_hash::from_path(&cwd)?;
                let events_path =
                    tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));

                let conn = tj_core::db::open(&state_path)?;
                if events_path.exists() {
                    tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
                }
                let mut stmt = conn.prepare(
                    "SELECT DISTINCT task_id FROM search_fts WHERE search_fts MATCH ?1 LIMIT ?2",
                )?;
                let ids: Vec<String> = stmt
                    .query_map(rusqlite::params![query, limit as i64], |r| {
                        r.get::<_, String>(0)
                    })?
                    .collect::<Result<_, _>>()?;
                for id in ids {
                    println!("{id}");
                }
            }
        }
        Commands::Ui { project, chats } => {
            let project_path = match project {
                Some(p) => std::path::PathBuf::from(p),
                None => std::env::current_dir()?,
            };
            if chats {
                // Legacy chat-session browser. Bail early when there's
                // nothing to show — the old behavior — so users running
                // `--chats` outside a Claude Code project don't get a
                // confusing empty TUI.
                let mut app = tui::app::App::new_chats(&project_path)?;
                let empty = app
                    .session_list
                    .as_ref()
                    .map(|sl| sl.sessions.is_empty())
                    .unwrap_or(true);
                if empty {
                    eprintln!(
                        "No Claude Code sessions found for: {}",
                        project_path.display()
                    );
                    return Ok(());
                }
                app.run()?;
            } else {
                // Default: task journal browser. Empty list is fine —
                // TaskList renders a helpful "no tasks yet" placeholder
                // pointing at create / install-hooks --backfill.
                let mut app = tui::app::App::new(&project_path)?;
                app.run()?;
            }
        }
        Commands::Backfill {
            dry_run,
            limit,
            project,
        } => {
            use tj_core::session::{discovery, extractor, parser};

            let project_path = match project {
                Some(p) => std::path::PathBuf::from(p),
                None => std::env::current_dir()?,
            };

            let project_hash = tj_core::project_hash::from_path(&project_path)?;
            let events_dir = tj_core::paths::events_dir()?;
            let events_path = events_dir.join(format!("{project_hash}.jsonl"));

            // Find the Claude Code project directory for this path.
            let proj_dir = discovery::find_project_dir(&project_path)?;
            let proj_dir = match proj_dir {
                Some(d) => d,
                None => {
                    eprintln!(
                        "No Claude Code sessions found for: {}",
                        project_path.display()
                    );
                    eprintln!(
                        "Looked in: {}",
                        discovery::projects_dir()
                            .map(|p| p.display().to_string())
                            .unwrap_or_else(|_| "?".into())
                    );
                    return Ok(());
                }
            };

            // List available sessions.
            let mut sessions = discovery::list_sessions(&proj_dir)?;
            if let Some(max) = limit {
                sessions.truncate(max);
            }

            if sessions.is_empty() {
                eprintln!("No session JSONL files found in: {}", proj_dir.display());
                return Ok(());
            }

            eprintln!(
                "Found {} session(s) for {}",
                sessions.len(),
                project_path.display()
            );

            // Check which sessions are already imported (idempotent).
            let already_imported = if events_path.exists() {
                let content = std::fs::read_to_string(&events_path).unwrap_or_default();
                sessions
                    .iter()
                    .filter_map(|p| p.file_stem().and_then(|s| s.to_str()).map(String::from))
                    .filter(|sid| content.contains(sid))
                    .collect::<std::collections::HashSet<_>>()
            } else {
                std::collections::HashSet::new()
            };

            let mut total_tasks = 0;
            let mut total_events = 0;

            for session_path in &sessions {
                let session_id = session_path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("?")
                    .to_string();

                if already_imported.contains(&session_id) {
                    eprintln!(
                        "{} — already imported, skipping",
                        &session_id[..8.min(session_id.len())]
                    );
                    continue;
                }

                // Parse the session JSONL.
                let parsed = match parser::parse_session(session_path) {
                    Ok(p) => p,
                    Err(e) => {
                        eprintln!(
                            "{} — parse error: {}",
                            &session_id[..8.min(session_id.len())],
                            e
                        );
                        continue;
                    }
                };

                // Extract events.
                let task = match extractor::extract_from_session(&parsed) {
                    Some(t) => t,
                    None => {
                        eprintln!(
                            "{} — too small ({} msgs), skipping",
                            &session_id[..8.min(session_id.len())],
                            parsed.user_message_count()
                        );
                        continue;
                    }
                };

                if dry_run {
                    eprintln!(
                        "{} → task {} \"{}\" ({} events)",
                        &session_id[..8.min(session_id.len())],
                        task.task_id,
                        task.title.chars().take(60).collect::<String>(),
                        task.events.len()
                    );
                    for ev in &task.events {
                        let etype = serde_json::to_value(ev.event_type)
                            .ok()
                            .and_then(|v| v.as_str().map(String::from))
                            .unwrap_or_else(|| "?".into());
                        eprintln!(
                            "      {:12} {}",
                            etype,
                            ev.text.chars().take(80).collect::<String>()
                        );
                    }
                } else {
                    // Write events to JSONL.
                    std::fs::create_dir_all(&events_dir)?;
                    let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
                    for event in &task.events {
                        writer.append(event)?;
                    }
                    writer.flush_durable()?;

                    eprintln!(
                        "{}{} \"{}\" ({} events)",
                        &session_id[..8.min(session_id.len())],
                        task.task_id,
                        task.title.chars().take(60).collect::<String>(),
                        task.events.len()
                    );
                }

                total_tasks += 1;
                total_events += task.events.len();
            }

            if dry_run {
                eprintln!(
                    "\nDry run: would create {total_tasks} task(s) with {total_events} event(s)."
                );
                eprintln!("Run without --dry-run to import.");
            } else {
                eprintln!("\nImported {total_tasks} task(s) with {total_events} event(s).");
            }
        }
        Commands::Statusline => {
            // Failure mode: print empty + exit 0. CC re-renders the
            // statusline on every keystroke; a panic or non-zero exit
            // would visibly break the bottom strip. Better to look
            // empty than to look broken.
            print!("{}", run_statusline().unwrap_or_default());
        }
        Commands::Rejected {
            topic,
            all_projects,
            limit,
            since,
        } => {
            run_rejected(&topic, all_projects, limit, since)?;
        }
        Commands::ExportPr { task_id } => {
            run_export_pr(&task_id)?;
        }
    }
    Ok(())
}

/// Returns the rendered statusline string. Sub-100ms target: ONE
/// SQLite open per project, no classifier calls, no FTS5 hits — only
/// the small `tasks` table. Empty string when there's no project
/// state at all (clean cwd outside any tracked project).
fn run_statusline() -> anyhow::Result<String> {
    let cwd = std::env::current_dir()?;
    let project_hash = tj_core::project_hash::from_path(&cwd)?;
    let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
    let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
    // Bail early on a clean machine. Both files missing → nothing to
    // show; printing empty keeps CC's bottom strip silent.
    if !state_path.exists() && !events_path.exists() {
        return Ok(String::new());
    }
    // Lazy-bootstrap the SQLite when events exist but state doesn't —
    // happens right after `create` and before any pack/search call.
    // tj_core::db::open runs migrations; ingest_new_events backfills
    // the tasks/events_index tables from JSONL.
    if !state_path.exists() && events_path.exists() {
        let conn = tj_core::db::open(&state_path)?;
        tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
    }
    let conn = rusqlite::Connection::open(&state_path)?;

    // Most-recently-touched open task. NULL is fine — the task line
    // becomes optional in the output.
    let recent_open: Option<String> = conn
        .query_row(
            "SELECT task_id FROM tasks WHERE project_hash = ?1 AND status = 'open'
             ORDER BY last_event_at DESC LIMIT 1",
            rusqlite::params![project_hash],
            |r| r.get::<_, String>(0),
        )
        .ok();

    let open_count: i64 = conn
        .query_row(
            "SELECT COUNT(*) FROM tasks WHERE project_hash = ?1 AND status = 'open'",
            rusqlite::params![project_hash],
            |r| r.get(0),
        )
        .unwrap_or(0);

    // Stale: open + last_event_at older than 7 days. Reuse stale_tasks
    // to keep the cutoff arithmetic in one place.
    let stale_count = tj_core::db::stale_tasks(&conn, 7)?
        .into_iter()
        .filter(|t| {
            // stale_tasks doesn't filter by project, so do it here.
            // Cheaper than a second query.
            conn.query_row(
                "SELECT project_hash FROM tasks WHERE task_id = ?1",
                rusqlite::params![t.task_id],
                |r| r.get::<_, String>(0),
            )
            .map(|h| h == project_hash)
            .unwrap_or(false)
        })
        .count();

    // Pending dir is global — one entry per queued classifier failure.
    // No project filter (matches the brief; per-project counting would
    // need extra metadata in each pending file).
    let pending_count = pending_dir()
        .ok()
        .and_then(|d| std::fs::read_dir(&d).ok())
        .map(|rd| {
            rd.filter_map(|e| e.ok())
                .filter(|e| {
                    e.path()
                        .extension()
                        .and_then(|x| x.to_str())
                        .map(|x| x == "json")
                        .unwrap_or(false)
                })
                .count()
        })
        .unwrap_or(0);

    let inner = match recent_open {
        Some(id) => format!(
            "{id} · open: {open_count} · pending: {pending_count} · stale: {stale_count}"
        ),
        None => format!(
            "open: {open_count} · pending: {pending_count} · stale: {stale_count}"
        ),
    };
    Ok(format!("[{inner}]"))
}

/// `True` when the prompt's first non-whitespace token is `/rewind`
/// (case-insensitive). Pulled out as a free function so unit tests
/// can hammer the parsing without spinning up a binary.
fn is_rewind_prompt(text: &str) -> bool {
    let trimmed = text.trim_start();
    let token = trimmed
        .split_whitespace()
        .next()
        .unwrap_or("");
    token.eq_ignore_ascii_case("/rewind")
}

/// Tokens FTS5 considers special — fall back to LIKE when the topic
/// contains one of these. Mirrors the heuristic in `task_search`.
fn topic_is_fts_safe(topic: &str) -> bool {
    !topic
        .chars()
        .any(|c| matches!(c, '-' | '"' | '*' | ':' | '(' | ')'))
}

fn run_rejected(
    topic: &str,
    all_projects: bool,
    limit: usize,
    since: Option<i64>,
) -> Result<()> {
    let cutoff: Option<String> = since.map(|d| {
        (chrono::Utc::now() - chrono::Duration::days(d))
            .to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
    });

    let state_dir = tj_core::paths::state_dir()?;
    let project_filter: Option<String> = if all_projects {
        None
    } else {
        let cwd = std::env::current_dir()?;
        Some(tj_core::project_hash::from_path(&cwd)?)
    };

    let hashes: Vec<String> = if let Some(h) = &project_filter {
        // Lazy-create the SQLite for the current project so the cwd
        // case still works on a fresh clone (no events_dir yet).
        let events_path = tj_core::paths::events_dir()?.join(format!("{h}.jsonl"));
        if events_path.exists() {
            let state_path = state_dir.join(format!("{h}.sqlite"));
            let conn = tj_core::db::open(&state_path)?;
            tj_core::db::ingest_new_events(&conn, &events_path, h)?;
        }
        vec![h.clone()]
    } else {
        tj_core::db::list_all_projects(&state_dir)?
    };

    // Collect → sort by ts desc → take limit. A single UNION ALL across
    // attached DBs would be faster but rusqlite's bundled build doesn't
    // ship ATTACH-friendly ergonomics; per-project loop is fine here.
    let mut hits: Vec<(String, String, String, String, String)> = Vec::new();
    for hash in hashes {
        let path = state_dir.join(format!("{hash}.sqlite"));
        let conn = match rusqlite::Connection::open(&path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        let use_fts = topic_is_fts_safe(topic);
        let sql = if use_fts {
            "SELECT ei.event_id, ei.task_id, ei.timestamp, sf.text, t.title
             FROM events_index ei
             JOIN search_fts sf ON sf.event_id = ei.event_id
             JOIN tasks t ON t.task_id = ei.task_id
             WHERE ei.type = 'rejection'
               AND search_fts MATCH ?1
               AND (?2 IS NULL OR ei.timestamp >= ?2)
             ORDER BY ei.timestamp DESC LIMIT ?3"
        } else {
            "SELECT ei.event_id, ei.task_id, ei.timestamp, sf.text, t.title
             FROM events_index ei
             JOIN search_fts sf ON sf.event_id = ei.event_id
             JOIN tasks t ON t.task_id = ei.task_id
             WHERE ei.type = 'rejection'
               AND sf.text LIKE ?1
               AND (?2 IS NULL OR ei.timestamp >= ?2)
             ORDER BY ei.timestamp DESC LIMIT ?3"
        };

        let mut stmt = match conn.prepare(sql) {
            Ok(s) => s,
            Err(_) => continue,
        };
        let bind_q = if use_fts {
            topic.to_string()
        } else {
            format!("%{topic}%")
        };
        let rows = match stmt.query_map(
            rusqlite::params![bind_q, cutoff, limit as i64],
            |r| {
                Ok((
                    r.get::<_, String>(0)?,
                    r.get::<_, String>(1)?,
                    r.get::<_, String>(2)?,
                    r.get::<_, Option<String>>(3)?.unwrap_or_default(),
                    r.get::<_, String>(4)?,
                ))
            },
        ) {
            Ok(r) => r,
            Err(_) => continue,
        };
        for row in rows.flatten() {
            hits.push(row);
        }
    }

    // Cross-project re-sort. Within one project the SQL ORDER BY
    // already did this, but UNION-ALL semantics need a second pass.
    hits.sort_by(|a, b| b.2.cmp(&a.2));
    hits.truncate(limit);

    for (_eid, task_id, ts, text, title) in hits {
        // YYYY-MM-DD slice of an RFC3339 timestamp; cheap and stable.
        let date = ts.get(..10).unwrap_or(&ts);
        // Squash newlines so multi-line rejections still render as
        // one block per hit.
        let one_line: String = text
            .lines()
            .next()
            .unwrap_or("")
            .chars()
            .take(120)
            .collect();
        println!("{task_id}\t{date}\t\"{one_line}\"");
        println!("\t\t(in task: {title})");
    }
    Ok(())
}

fn run_export_pr(task_id: &str) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let project_hash = tj_core::project_hash::from_path(&cwd)?;
    let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
    let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
    let conn = tj_core::db::open(&state_path)?;
    if events_path.exists() {
        tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
    }

    // Fetch task title up-front; bail with a typed exit code so callers
    // can distinguish "not found" from a generic IO error.
    let title: String = match conn
        .query_row(
            "SELECT title FROM tasks WHERE task_id = ?1",
            rusqlite::params![task_id],
            |r| r.get::<_, String>(0),
        ) {
        Ok(t) => t,
        Err(rusqlite::Error::QueryReturnedNoRows) => {
            eprintln!("Error: task not found: {task_id}");
            std::process::exit(1);
        }
        Err(e) => return Err(e.into()),
    };

    let meta = tj_core::db::task_metadata(&conn, task_id)?.unwrap_or_default();
    let summary = meta.goal.unwrap_or_else(|| title.clone());

    // Pull all events ordered ASC so the PR description reads like a
    // narrative (oldest decision first → newest).
    let mut stmt = conn.prepare(
        "SELECT ei.type, sf.text FROM events_index ei
         LEFT JOIN search_fts sf ON sf.event_id = ei.event_id
         WHERE ei.task_id = ?1 ORDER BY ei.timestamp ASC",
    )?;
    let rows = stmt.query_map(rusqlite::params![task_id], |r| {
        let ty: String = r.get(0)?;
        let txt: Option<String> = r.get(1)?;
        Ok((ty, txt.unwrap_or_default()))
    })?;
    let mut decisions: Vec<String> = Vec::new();
    let mut rejections: Vec<String> = Vec::new();
    let mut evidence: Vec<String> = Vec::new();
    for row in rows {
        let (ty, text) = row?;
        let one_line: String = text
            .lines()
            .next()
            .unwrap_or("")
            .trim()
            .to_string();
        if one_line.is_empty() {
            continue;
        }
        match ty.as_str() {
            "decision" => decisions.push(one_line),
            "rejection" => rejections.push(one_line),
            "evidence" => evidence.push(one_line),
            _ => {}
        }
    }

    let arts = tj_core::db::task_artifacts(&conn, task_id)?;

    let mut out = String::new();
    out.push_str("## Summary\n");
    out.push_str(&summary);
    out.push_str("\n\n");

    out.push_str("## Changes\n");
    if decisions.is_empty() {
        out.push_str("- (no decision events recorded)\n");
    } else {
        for d in &decisions {
            out.push_str(&format!("- {d}\n"));
        }
    }
    out.push('\n');

    if !rejections.is_empty() {
        out.push_str("## Why this approach (vs alternatives)\n");
        for r in &rejections {
            out.push_str(&format!("- {r}\n"));
        }
        out.push('\n');
    }

    if !evidence.is_empty() {
        out.push_str("## Verification\n");
        for e in &evidence {
            out.push_str(&format!("- {e}\n"));
        }
        out.push('\n');
    }

    let any_arts = !arts.files.is_empty()
        || !arts.commit_hashes.is_empty()
        || !arts.linked_issues.is_empty()
        || !arts.branch_names.is_empty()
        || !arts.pr_urls.is_empty();
    if any_arts {
        out.push_str("## Affected\n");
        if !arts.files.is_empty() {
            out.push_str(&format!("- Files: {}\n", arts.files.join(", ")));
        }
        if !arts.commit_hashes.is_empty() {
            out.push_str(&format!(
                "- Commits: {}\n",
                arts.commit_hashes.join(", ")
            ));
        }
        if !arts.linked_issues.is_empty() {
            out.push_str(&format!(
                "- Issues: {}\n",
                arts.linked_issues.join(", ")
            ));
        }
        if !arts.branch_names.is_empty() {
            out.push_str(&format!(
                "- Branches: {}\n",
                arts.branch_names.join(", ")
            ));
        }
        if !arts.pr_urls.is_empty() {
            out.push_str(&format!("- PRs: {}\n", arts.pr_urls.join(", ")));
        }
        out.push('\n');
    }

    print!("{}", out);
    Ok(())
}

fn recent_task_contexts(
    conn: &rusqlite::Connection,
    limit: usize,
) -> anyhow::Result<Vec<tj_core::classifier::TaskContext>> {
    let mut stmt = conn.prepare(
        "SELECT task_id, title FROM tasks WHERE status='open' ORDER BY last_event_at DESC LIMIT ?1",
    )?;
    let task_rows: Vec<(String, String)> = stmt
        .query_map(rusqlite::params![limit as i64], |r| {
            Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
        })?
        .collect::<Result<_, _>>()?;

    let mut out = Vec::with_capacity(task_rows.len());
    for (task_id, title) in task_rows {
        let mut e_stmt = conn.prepare(
            "SELECT ei.type, sf.text FROM events_index ei
             LEFT JOIN search_fts sf ON sf.event_id = ei.event_id
             WHERE ei.task_id=?1 ORDER BY ei.timestamp DESC LIMIT 3",
        )?;
        let last_events: Vec<String> = e_stmt
            .query_map(rusqlite::params![task_id], |r| {
                let ty: String = r.get(0)?;
                let txt: Option<String> = r.get(1)?;
                Ok(format!(
                    "[{ty}] {}",
                    txt.unwrap_or_default().chars().take(80).collect::<String>()
                ))
            })?
            .collect::<Result<_, _>>()?;
        out.push(tj_core::classifier::TaskContext {
            task_id,
            title,
            last_events,
        });
    }
    Ok(out)
}

/// v0.5.0 Phase A: when ingest-hook fires UserPromptSubmit and there
/// are no open tasks, synthesize one from the prompt itself. Title is
/// the first line trimmed to 80 chars; goal is the prompt trimmed to
/// 200 chars. Returns a TaskContext so the classifier has somewhere
/// to attach the same prompt as the first real event.
fn auto_open_task_from_prompt(
    events_path: &std::path::Path,
    project_hash: &str,
    conn: &rusqlite::Connection,
    prompt: &str,
) -> anyhow::Result<tj_core::classifier::TaskContext> {
    let cleaned = prompt.trim();
    // Title: first non-empty line, ≤80 chars. Falls back to "(empty
    // prompt)" so we never write a NULL title — the classifier and
    // the TUI both display titles directly.
    let title: String = cleaned
        .lines()
        .map(|l| l.trim())
        .find(|l| !l.is_empty())
        .map(|l| l.chars().take(80).collect())
        .unwrap_or_else(|| "(auto-opened: empty prompt)".to_string());
    let goal: String = cleaned.chars().take(200).collect();

    let task_id = tj_core::new_task_id();
    let mut event = tj_core::event::Event::new(
        task_id.clone(),
        tj_core::event::EventType::Open,
        tj_core::event::Author::User,
        tj_core::event::Source::Cli,
        title.clone(),
    );
    event.meta = serde_json::json!({ "title": title, "auto_opened": true });

    let mut writer = tj_core::storage::JsonlWriter::open(events_path)?;
    writer.append(&event)?;
    writer.flush_durable()?;

    tj_core::db::ingest_new_events(conn, events_path, project_hash)?;
    if !goal.is_empty() {
        tj_core::db::set_task_goal(conn, &task_id, &goal)?;
    }

    // v0.5.0 Phase C / v0.6.0: score-based linking. Pull artifacts
    // from the prompt — ticket ids, commit hashes, file paths — then
    // ask the journal which prior tasks share enough signal to be a
    // probable continuation. Anything with score > 0 gets linked via
    // External; the strongest closed match also triggers a stderr
    // hint so the user can reopen instead of accumulating duplicates.
    let prompt_arts = tj_core::artifacts::extract(prompt);
    if !prompt_arts.is_empty() {
        let related = tj_core::db::find_related_tasks(conn, &prompt_arts)?;
        let mut warned = false;
        for r in related.iter().take(5) {
            if r.task_id == task_id {
                continue;
            }
            let _ =
                tj_core::db::add_task_external(conn, &task_id, &format!("linked:{}", r.task_id));
            if !warned && r.status == "closed" {
                eprintln!(
                    "task-journal: this prompt looks like a continuation of closed task {} \
                     (score {:.1}) — run `task-journal reopen {}` if it is.",
                    r.task_id, r.score, r.task_id
                );
                warned = true;
            }
        }
    }

    Ok(tj_core::classifier::TaskContext {
        task_id,
        title,
        last_events: vec![],
    })
}

fn persist_pending(events_path: &std::path::Path, text: &str, err: &str) -> anyhow::Result<()> {
    let pending_dir = events_path
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("pending");
    std::fs::create_dir_all(&pending_dir)?;
    let id = ulid::Ulid::new().to_string();
    let payload = serde_json::json!({"text": text, "error": err, "queued_at": chrono::Utc::now().to_rfc3339()});
    std::fs::write(
        pending_dir.join(format!("{id}.json")),
        serde_json::to_string_pretty(&payload)?,
    )?;
    Ok(())
}

/// v0.6.2: queue an ingest event for the detached classify-worker. The
/// hook returns immediately after writing this entry so it does not
/// block Claude Code's hook timeout (was 5-30s, now <100ms). Schema "v2"
/// distinguishes async-ingest entries from legacy v1 (text+error) ones
/// the `pending retry` path knows how to handle.
fn persist_pending_v2(
    events_path: &std::path::Path,
    kind: &str,
    text: &str,
    project_hash: &str,
    backend: &str,
) -> anyhow::Result<std::path::PathBuf> {
    let pending_dir = events_path
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("pending");
    std::fs::create_dir_all(&pending_dir)?;
    let id = ulid::Ulid::new().to_string();
    let payload = serde_json::json!({
        "schema": "v2",
        "kind": kind,
        "text": text,
        "project_hash": project_hash,
        "events_path": events_path.to_string_lossy(),
        "backend": backend,
        "queued_at": chrono::Utc::now().to_rfc3339(),
    });
    let path = pending_dir.join(format!("{id}.json"));
    std::fs::write(&path, serde_json::to_string_pretty(&payload)?)?;
    Ok(path)
}

/// Spawn the classify-worker as a detached child. We deliberately drop
/// the `Child` handle so the parent (the actual Claude Code hook child)
/// can exit without waiting; the worker re-parents to init on Linux.
/// stdin/stdout/stderr are nulled so the worker doesn't keep the hook's
/// pipes open. TJ_CLASSIFIER_BUMP marks the spawn for telemetry; clear
/// TJ_IN_CLASSIFIER because the worker NEEDS to call the classifier.
fn spawn_classify_worker(backend: &str) -> anyhow::Result<()> {
    let exe = std::env::current_exe().context("locate current task-journal exe")?;
    let mut cmd = std::process::Command::new(exe);
    cmd.arg("classify-worker")
        .arg("--backend")
        .arg(backend)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .env("TJ_CLASSIFIER_BUMP", "1")
        .env_remove("TJ_IN_CLASSIFIER");
    let _child = cmd.spawn().context("spawn classify-worker")?;
    // Drop child intentionally — Linux init reaps when parent exits.
    Ok(())
}

/// File-lock guard for the classify-worker. Holds the lockfile until
/// dropped; ensures cleanup on panic. One worker per project_hash.
struct WorkerLock {
    path: std::path::PathBuf,
}

impl WorkerLock {
    /// Try to acquire the lock. Returns Ok(Some(_)) on success, Ok(None)
    /// if another live worker holds it, Err on filesystem failure.
    fn try_acquire(project_hash: &str) -> anyhow::Result<Option<Self>> {
        let dir = tj_core::paths::state_dir()?;
        std::fs::create_dir_all(&dir)?;
        let path = dir.join(format!("classifier-{project_hash}.lock"));

        loop {
            match std::fs::OpenOptions::new()
                .write(true)
                .create_new(true)
                .open(&path)
            {
                Ok(mut f) => {
                    use std::io::Write;
                    let _ = writeln!(f, "{}", std::process::id());
                    return Ok(Some(Self { path }));
                }
                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
                    // Inspect existing lockfile. If PID is alive → another
                    // worker is running; back off. If dead/missing →
                    // remove stale file and retry.
                    let body = std::fs::read_to_string(&path).unwrap_or_default();
                    let pid: Option<u32> = body.trim().parse().ok();
                    if let Some(pid) = pid {
                        if pid_is_alive(pid) {
                            return Ok(None);
                        }
                    }
                    // Stale (no PID, or dead PID) — remove and retry.
                    let _ = std::fs::remove_file(&path);
                    continue;
                }
                Err(e) => return Err(e.into()),
            }
        }
    }
}

impl Drop for WorkerLock {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(&self.path);
    }
}

#[cfg(unix)]
fn pid_is_alive(pid: u32) -> bool {
    // kill(pid, 0) probes existence without sending a signal.
    // SAFETY: libc::kill is a thin syscall wrapper, no aliasing concerns.
    unsafe { libc::kill(pid as libc::pid_t, 0) == 0 }
}

#[cfg(not(unix))]
fn pid_is_alive(_pid: u32) -> bool {
    // Conservative on non-Unix: assume alive so we don't double-spawn.
    // The lockfile gets cleaned up on Drop in the normal exit path.
    true
}

/// classify-worker: drain pending v2 entries by running the real
/// classifier. v1 entries (legacy text+error shape) are left for
/// `pending retry`. Holds a project-scoped file lock so only one
/// worker per project runs at a time.
fn run_classify_worker(backend: &str) -> Result<()> {
    let cwd = std::env::current_dir()?;
    let project_hash = tj_core::project_hash::from_path(&cwd)?;

    let lock = match WorkerLock::try_acquire(&project_hash)? {
        Some(l) => l,
        None => return Ok(()), // another worker is running
    };

    let events_path = tj_core::paths::events_dir()?.join(format!("{project_hash}.jsonl"));
    let pending = events_path
        .parent()
        .and_then(|p| p.parent())
        .ok_or_else(|| anyhow::anyhow!("events_dir has no grandparent"))?
        .join("pending");
    if !pending.exists() {
        drop(lock);
        return Ok(());
    }

    // Snapshot entries up front so concurrent re-queues don't loop us.
    let mut entries: Vec<std::path::PathBuf> = Vec::new();
    for e in std::fs::read_dir(&pending)? {
        let e = e?;
        let p = e.path();
        if p.extension().and_then(|s| s.to_str()) == Some("json") {
            entries.push(p);
        }
    }

    for path in entries {
        if let Err(err) = process_pending_entry(&path, &events_path, &project_hash, backend) {
            // Non-fatal: leave the file in place; pending-retry / next
            // worker invocation can re-attempt. Avoid writing to stderr
            // since stderr is nulled — but in tests stderr is captured.
            eprintln!("classify-worker: {} failed: {err:#}", path.display());
        }
    }

    drop(lock);
    Ok(())
}

/// Process one pending entry. Routes by schema:
/// - "v2" → real-classifier path (auto_open + classify + persist event)
/// - anything else (legacy "v1" with text/error) → leave for `pending retry`
fn process_pending_entry(
    path: &std::path::Path,
    events_path: &std::path::Path,
    project_hash: &str,
    backend: &str,
) -> anyhow::Result<()> {
    let body = std::fs::read_to_string(path)?;
    let v: serde_json::Value = serde_json::from_str(&body)?;
    let schema = v.get("schema").and_then(|x| x.as_str()).unwrap_or("v1");
    if schema != "v2" {
        return Ok(()); // legacy entry, handled by `pending retry`
    }

    let kind = v
        .get("kind")
        .and_then(|x| x.as_str())
        .unwrap_or("Stop")
        .to_string();
    let text = v
        .get("text")
        .and_then(|x| x.as_str())
        .unwrap_or("")
        .to_string();

    // Mirror the synchronous flow that used to live in IngestHook —
    // see commit history of v0.6.1 for the original. Auto-open, run
    // classifier, apply integrity safeguards, persist event, telemetry.
    let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
    let conn = tj_core::db::open(&state_path)?;
    if events_path.exists() {
        tj_core::db::ingest_new_events(&conn, events_path, project_hash)?;
    }

    let mut recent = recent_task_contexts(&conn, 5)?;
    if recent.is_empty() {
        let auto_open_disabled = std::env::var("TJ_AUTO_OPEN_TASKS")
            .ok()
            .map(|v| v == "0" || v.eq_ignore_ascii_case("false"))
            .unwrap_or(false);
        if auto_open_disabled || !kind.contains("UserPrompt") {
            // Nothing to do — drop the entry silently.
            std::fs::remove_file(path)?;
            return Ok(());
        }
        let new_task = auto_open_task_from_prompt(events_path, project_hash, &conn, &text)?;
        recent.push(new_task);
    }

    let author_hint = if kind.contains("UserPrompt") {
        "user"
    } else {
        "assistant"
    };

    use tj_core::classifier::Classifier;
    let classifier: Box<dyn Classifier> = match backend {
        "cli" => Box::new(tj_core::classifier::cli::ClaudeCliClassifier::default()),
        "api" => Box::new(tj_core::classifier::http::AnthropicClassifier::from_env()?),
        other => anyhow::bail!("unknown backend: {other}"),
    };
    let input = tj_core::classifier::ClassifyInput {
        text: text.clone(),
        author_hint: author_hint.into(),
        recent_tasks: recent,
    };
    let out = match classifier.classify(&input) {
        Ok(o) => o,
        Err(e) => {
            // Persist as legacy v1 pending entry so `pending retry`
            // surfaces it; remove the v2 source.
            persist_pending(events_path, &text, &e.to_string())?;
            std::fs::remove_file(path)?;
            return Ok(());
        }
    };

    let Some(tid) = out.task_id_guess else {
        std::fs::remove_file(path)?;
        return Ok(());
    };

    use tj_core::event::EventType;
    if matches!(out.event_type, EventType::Close) && kind == "Stop" {
        std::fs::remove_file(path)?;
        return Ok(());
    }
    match tj_core::db::task_status(&conn, &tid)? {
        None => {
            persist_pending(
                events_path,
                &text,
                &format!("task_id_guess `{tid}` not found"),
            )?;
            std::fs::remove_file(path)?;
            return Ok(());
        }
        Some(s) if s == "closed" => {
            persist_pending(
                events_path,
                &text,
                &format!("task_id_guess `{tid}` is closed"),
            )?;
            std::fs::remove_file(path)?;
            return Ok(());
        }
        _ => {}
    }

    let confidence = out.confidence;
    let evidence_strength = out.evidence_strength;
    let etype = out.event_type;
    let event_text = out.suggested_text;

    let mut event = tj_core::event::Event::new(
        &tid,
        etype,
        tj_core::event::Author::Classifier,
        tj_core::event::Source::Hook,
        event_text,
    );
    event.confidence = Some(confidence);
    event.status = tj_core::classifier::decide_status(confidence);
    event.evidence_strength = evidence_strength;

    let mut writer = tj_core::storage::JsonlWriter::open(events_path)?;
    writer.append(&event)?;
    writer.flush_durable()?;

    let metrics_path = tj_core::paths::metrics_dir()?.join(format!("{project_hash}.jsonl"));
    let etype_str = serde_json::to_value(etype)?
        .as_str()
        .unwrap_or("?")
        .to_string();
    let status_str = serde_json::to_value(event.status)?
        .as_str()
        .unwrap_or("?")
        .to_string();
    let _ = tj_core::classifier::telemetry::append(
        &metrics_path,
        &tj_core::classifier::telemetry::TelemetryRecord {
            timestamp: chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true),
            project_hash: project_hash.to_string(),
            task_id_guess: Some(tid.clone()),
            event_type: etype_str,
            confidence,
            status: status_str,
            error: None,
        },
    );

    std::fs::remove_file(path)?;
    Ok(())
}

fn drain_pending(
    events_path: &std::path::Path,
    mock_etype: Option<&str>,
    mock_tid: Option<&str>,
    mock_conf: Option<f64>,
) -> anyhow::Result<()> {
    let pending_dir = events_path
        .parent()
        .unwrap()
        .parent()
        .unwrap()
        .join("pending");
    if !pending_dir.exists() {
        return Ok(());
    }

    for entry in std::fs::read_dir(&pending_dir)? {
        let entry = entry?;
        if entry.path().extension().and_then(|e| e.to_str()) != Some("json") {
            continue;
        }

        let body = std::fs::read_to_string(entry.path())?;
        let v: serde_json::Value = serde_json::from_str(&body)?;
        // v0.6.2: skip v2 entries — those are owned by classify-worker.
        // Removing them here would silently drop async-queued events.
        if v.get("schema").and_then(|x| x.as_str()) == Some("v2") {
            continue;
        }
        let text = v
            .get("text")
            .and_then(|x| x.as_str())
            .unwrap_or("")
            .to_string();
        if !text.is_empty() {
            if let (Some(t), Some(tid)) = (mock_etype, mock_tid) {
                let mut event = tj_core::event::Event::new(
                    tid,
                    parse_event_type(t)?,
                    tj_core::event::Author::Classifier,
                    tj_core::event::Source::Hook,
                    text,
                );
                event.confidence = mock_conf;
                event.status = tj_core::classifier::decide_status(mock_conf.unwrap_or(1.0));
                let mut writer = tj_core::storage::JsonlWriter::open(events_path)?;
                writer.append(&event)?;
                writer.flush_durable()?;
            }
        }
        std::fs::remove_file(entry.path())?;
    }
    Ok(())
}

/// Read a Claude Code hook payload from stdin and project it down to
/// the (kind, text) pair the rest of `ingest-hook` operates on.
///
/// Claude Code passes hook input as a JSON object on stdin. The fields
/// we care about (per the public hooks spec):
///
/// - common: `hook_event_name`
/// - UserPromptSubmit: `prompt`
/// - PreToolUse / PostToolUse: `tool_name`, `tool_input`, `tool_response`
/// - Stop / SessionStart: nothing extra worth ingesting (SessionStart
///   takes a separate fast path further up)
///
/// If stdin is empty (someone runs the command interactively without
/// piping), we silently return ("Stop", "") so the hook becomes a no-op
/// instead of erroring — matches the `|| true` safety net in the
/// installed hook command.
fn parse_hook_stdin() -> anyhow::Result<(String, String)> {
    let mut buf = String::new();
    std::io::Read::read_to_string(&mut std::io::stdin(), &mut buf)
        .context("read hook payload from stdin")?;
    let buf = buf.trim();
    if buf.is_empty() {
        return Ok(("Stop".into(), String::new()));
    }
    let v: serde_json::Value =
        serde_json::from_str(buf).with_context(|| format!("parse hook payload JSON: {buf}"))?;

    let kind = v
        .get("hook_event_name")
        .and_then(|s| s.as_str())
        .unwrap_or("Stop")
        .to_string();

    let text = match kind.as_str() {
        "UserPromptSubmit" => v
            .get("prompt")
            .and_then(|s| s.as_str())
            .unwrap_or("")
            .to_string(),
        "PreToolUse" | "PostToolUse" => {
            let tool = v
                .get("tool_name")
                .and_then(|s| s.as_str())
                .unwrap_or("tool");
            let input = v
                .get("tool_input")
                .map(|x| x.to_string())
                .unwrap_or_default();
            let response = v
                .get("tool_response")
                .map(|x| x.to_string())
                .unwrap_or_default();
            if response.is_empty() {
                format!("{tool}: {input}")
            } else {
                format!("{tool}: {input}{response}")
            }
        }
        _ => String::new(),
    };

    Ok((kind, text))
}

fn parse_event_type(s: &str) -> anyhow::Result<tj_core::event::EventType> {
    use tj_core::event::EventType::*;
    Ok(match s {
        "open" => Open,
        "hypothesis" => Hypothesis,
        "finding" => Finding,
        "evidence" => Evidence,
        "decision" => Decision,
        "rejection" => Rejection,
        "constraint" => Constraint,
        "correction" => Correction,
        "reopen" => Reopen,
        "supersede" => Supersede,
        "close" => Close,
        "redirect" => Redirect,
        other => anyhow::bail!("unknown event type: {other}"),
    })
}

#[cfg(test)]
mod inline_tests {
    // Sits at the bottom of the file to satisfy
    // `clippy::items_after_test_module` — every other free fn must be
    // declared before this module begins.
    use super::*;

    #[test]
    fn is_rewind_prompt_simple() {
        assert!(is_rewind_prompt("/rewind"));
        assert!(is_rewind_prompt("/rewind back to plan A"));
        assert!(is_rewind_prompt("  /rewind"));
        assert!(is_rewind_prompt("\t/rewind"));
    }

    #[test]
    fn is_rewind_prompt_case_insensitive() {
        assert!(is_rewind_prompt("/Rewind"));
        assert!(is_rewind_prompt("/REWIND"));
    }

    #[test]
    fn is_rewind_prompt_rejects_non_match() {
        assert!(!is_rewind_prompt("rewind"));
        assert!(!is_rewind_prompt("hello /rewind"));
        assert!(!is_rewind_prompt(""));
        assert!(!is_rewind_prompt("/rewinder"));
    }

    #[test]
    fn topic_is_fts_safe_basic() {
        assert!(topic_is_fts_safe("oauth"));
        assert!(topic_is_fts_safe("foo bar"));
        assert!(!topic_is_fts_safe("foo-bar"));
        assert!(!topic_is_fts_safe("\"quote\""));
        assert!(!topic_is_fts_safe("col:name"));
    }
}