task-journal-cli 0.20.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
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
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 `agent-sdk` backend (no API key; \
                 uses your Claude login, drawing the Agent SDK credit pool since \
                 2026-06-15), 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>,
        /// Parent task id — makes this a subtask of the given id.
        #[arg(long)]
        parent: Option<String>,
    },
    /// List tasks for the current project.
    List {
        /// Render tasks as a tree, children indented under parents.
        #[arg(long)]
        tree: bool,
    },
    /// Inspect events for a project.
    Events {
        #[command(subcommand)]
        action: EventsCmd,
    },
    /// Rebuild SQLite state from the JSONL log.
    RebuildState,
    /// Embed events for semantic search (Pillar A). Computes a vector per event
    /// and stores it in the v008 `embeddings` table. `--backfill` drains the
    /// whole project; without it, only newly-unembedded events are processed.
    /// Uses the dependency-free hash embedder by default — fully offline.
    Embed {
        /// Vectorise the entire project history, not just new events.
        #[arg(long)]
        backfill: bool,
    },
    /// Semantic search over this project's journal (Pillar A). Embeds the query
    /// and returns the most relevant events by meaning, not keyword. New events
    /// are embedded on the fly, so the index stays current with zero setup.
    Ask {
        /// The question or topic to search for.
        query: String,
        /// Maximum number of results.
        #[arg(long, default_value_t = 5)]
        k: usize,
    },
    /// Cross-project recall (Pillar B): search EVERY project's decisions,
    /// rejections and constraints for reasoning relevant to the query —
    /// prior choices and dead-ends from your whole history, not just this repo.
    Recall {
        /// The topic / approach to check against prior reasoning.
        query: String,
        /// Maximum number of results.
        #[arg(long, default_value_t = 5)]
        k: usize,
    },
    /// Record a durable user preference (Pillar C) — e.g. "prefer terse output",
    /// "respond in Russian", "always run the full test suite before tagging".
    /// Stored user-level (across all projects) and injected into every session
    /// so the agent remembers how you work without being re-told.
    Remember {
        /// The preference text to remember.
        text: String,
    },
    /// List your stored user preferences.
    Preferences,
    /// Distil this project's recurring decisions and constraints into durable
    /// semantic/procedural facts (Pillar C). MANUAL and opt-in — it makes ONE
    /// direct Haiku API call per run (needs ANTHROPIC_API_KEY; ~1c/run) and is
    /// never wired to a hook, so it can't spend automatically. Facts are stored
    /// as events in a per-project "conventions" task and surface in ask/recall.
    Consolidate {
        /// Maximum number of facts to produce.
        #[arg(long, default_value_t = 8)]
        max_facts: usize,
    },
    /// 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,
        /// v0.10.3+: restrict matches to a single event type
        /// (`decision`, `evidence`, `finding`, `rejection`, ...).
        #[arg(long = "type", value_name = "TYPE")]
        event_type: Option<String>,
    },
    /// 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,
        /// 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,
        /// Classifier backend baked into the installed hook command:
        /// "hybrid" (default), "agent-sdk", "api", or "heuristic". Use
        /// "agent-sdk" to classify via the local `claude` login without an
        /// ANTHROPIC_API_KEY (see `ingest-hook --help` for the credit note).
        #[arg(long, default_value = "hybrid")]
        backend: String,
        /// v0.14.0: opt in to realtime auto-capture. Without it, install-hooks
        /// wires ONLY the cheap, read-only SessionStart resume hook — no
        /// per-message classifier, no `claude -p`, no cost. Primary capture is
        /// the agent self-tagging via the MCP tools. With `--auto-capture` the
        /// per-message + PreCompact ingest hooks are installed too (they spawn
        /// the classifier, honoring `--backend`).
        #[arg(long)]
        auto_capture: bool,
        /// Opt in to proactive cross-project recall (Pillar B). Adds a
        /// UserPromptSubmit hook that injects relevant prior decisions/
        /// rejections/constraints from any project before you act. Off by
        /// default (it surfaces extra context on every prompt). Fast keyword
        /// path, no model; gated at runtime by TJ_PROACTIVE_RECALL=0.
        #[arg(long)]
        proactive_recall: 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>,
    },
    /// Offline memory backfill: re-read session transcripts and append
    /// significant events the realtime classifier missed (dream Pass A).
    Dream {
        /// Only sessions in the last N days (overrides the watermark).
        #[arg(long)]
        since: Option<i64>,
        /// Only this task's sessions.
        #[arg(long)]
        task: Option<String>,
        /// Show scope without calling the API or writing anything.
        #[arg(long)]
        dry_run: bool,
        /// Cap sessions processed this run.
        #[arg(long)]
        limit: Option<usize>,
    },
    /// 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:
        ///   - "hybrid" (default) — keyword heuristic first (free, offline),
        ///     then the configured LLM fallback chain (agent-sdk, then api;
        ///     reorder with TJ_HYBRID_LLM_ORDER). Only available backends run.
        ///   - "agent-sdk" — classify via the local, already-logged-in `claude`
        ///     binary; no ANTHROPIC_API_KEY needed. Pinned to Haiku (override
        ///     with TJ_AGENT_SDK_MODEL). NOTE: since 2026-06-15 a headless
        ///     `claude -p` draws from the separate Agent SDK monthly credit
        ///     pool (~$20 Pro / $100 Max 5x / $200 Max 20x at API rates), not
        ///     the interactive pool. Classification is tiny, so it lasts.
        ///   - "api" — always call the Anthropic API. Needs ANTHROPIC_API_KEY.
        ///   - "heuristic" — heuristic only, no LLM. Fastest, lowest coverage.
        ///   - "cli" — removed in v0.8.0; use "agent-sdk" (its resurrection).
        #[arg(long, default_value = "hybrid")]
        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: "hybrid", "agent-sdk", "api", or "heuristic".
        /// Defaults to hybrid.
        #[arg(long, default_value = "hybrid")]
        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,
    /// Read-only reminder hook (no model, never spawns `claude -p`). Emits a
    /// UserPromptSubmit additionalContext line nudging the agent to record
    /// reasoning via the MCP tools as it goes. Wired by `install-hooks` by
    /// default. Hidden from --help; not a human command.
    #[command(hide = true)]
    Nudge,
    /// Opt-in proactive recall hook (Pillar B). On UserPromptSubmit, injects a
    /// budgeted additionalContext block of prior decisions/rejections/
    /// constraints from ANY project relevant to the prompt — a guardrail
    /// against re-deciding or repeating a dead-end. Fast keyword path, no
    /// model. Wired only by `install-hooks --proactive-recall`. Gated by
    /// TJ_PROACTIVE_RECALL=0. Hidden from --help; not a human command.
    #[command(hide = true)]
    RecallHook,
    /// 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 },
    /// Export task knowledge as Claude-memory frontmatter files (feeds native dream).
    ExportMemory {
        /// Export a single task by id.
        #[arg(long, conflicts_with = "all_closed")]
        task: Option<String>,
        /// Export all closed tasks (default scope when no flag is given).
        #[arg(long)]
        all_closed: bool,
        /// Print target paths + content without writing.
        #[arg(long)]
        dry_run: bool,
    },
}

#[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,
            parent,
        } => {
            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();

            // Validate --parent before writing the open event: the parent must
            // already exist and the link must not introduce a cycle. Needs the
            // derived SQLite state, so ingest the JSONL tail first.
            if let Some(ref parent_id) = parent {
                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)?;
                if !tj_core::db::task_exists(&conn, parent_id)? {
                    anyhow::bail!("parent task {parent_id} does not exist");
                }
                if tj_core::db::would_create_cycle(&conn, &task_id, parent_id)? {
                    anyhow::bail!("setting parent {parent_id} would create a cycle");
                }
            }

            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()),
            );
            let mut meta = serde_json::json!({ "title": title });
            if let Some(ref parent_id) = parent {
                meta["parent_id"] = serde_json::Value::String(parent_id.clone());
            }
            event.meta = meta;

            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::List { tree } => {
            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 tree {
                for t in tj_core::db::top_level_tasks(&conn, &project_hash)? {
                    println!("{} [{}] {}", t.task_id, t.status, t.title);
                    for c in tj_core::db::children_of(&conn, &t.task_id)? {
                        println!("  {} [{}] {}", c.task_id, c.status, c.title);
                    }
                }
            } else {
                for t in tj_core::db::list_tasks_by_project(&conn, &project_hash)? {
                    println!("{} [{}] {}", t.task_id, t.status, t.title);
                }
            }
        }
        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::Embed { backfill } => {
            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)?;
            // search_fts must be current before we embed from it.
            tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;

            let embedder = tj_core::embed::default_embedder();
            let now = chrono::Utc::now().to_rfc3339();
            let batch = if backfill { 256 } else { 64 };
            let mut total = 0usize;
            loop {
                let n = tj_core::db::embed_pending(
                    &conn,
                    &project_hash,
                    embedder.as_ref(),
                    &now,
                    batch,
                )?;
                total += n;
                // Without --backfill, one batch of newly-unembedded events is enough.
                if n == 0 || !backfill {
                    break;
                }
            }
            sync_global_memory(&conn, &project_hash);
            println!(
                "embedded {total} event(s) with model {} ({} dim)",
                embedder.model_id(),
                embedder.dim()
            );
        }
        Commands::Ask { query, k } => {
            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)?;
            tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;

            let embedder = tj_core::embed::default_embedder();
            // Embed-on-ask: vectorise anything new so the answer reflects the
            // latest events without the user running `embed` first.
            let now = chrono::Utc::now().to_rfc3339();
            tj_core::db::embed_pending(&conn, &project_hash, embedder.as_ref(), &now, 512)?;
            sync_global_memory(&conn, &project_hash);

            let qv = embedder.embed_one(&query)?;
            let hits =
                tj_core::db::semantic_search(&conn, &project_hash, &qv, embedder.model_id(), k)?;
            if hits.is_empty() {
                println!("no matches");
            } else {
                for h in hits {
                    let snippet: String = h.text.chars().take(100).collect();
                    println!(
                        "{:.3}  [{}] {}  ({})",
                        h.score, h.event_type, snippet, h.task_id
                    );
                }
            }
        }
        Commands::Recall { query, k } => {
            let global_path = tj_core::paths::memory_db()?;
            if !global_path.exists() {
                println!("global memory is empty — run `ask` or `embed` in a project first");
                return Ok(());
            }
            let global = tj_core::memory::open(&global_path)?;
            let embedder = tj_core::embed::default_embedder();
            let qv = embedder.embed_one(&query)?;
            let hits = tj_core::memory::search(&global, &qv, embedder.model_id(), k)?;
            if hits.is_empty() {
                println!("no relevant prior reasoning found");
            } else {
                for h in hits {
                    let snippet: String = h.text.chars().take(100).collect();
                    let proj: String = h.project_hash.chars().take(8).collect();
                    println!(
                        "{:.3}  [{}] {}  ({}/{})",
                        h.score, h.event_type, snippet, proj, h.task_id
                    );
                }
            }
        }
        Commands::Remember { text } => {
            let global = tj_core::memory::open(tj_core::paths::memory_db()?)?;
            let now = chrono::Utc::now().to_rfc3339();
            if tj_core::memory::add_preference(&global, &text, &now)? {
                println!("remembered: {}", text.trim());
            } else {
                println!("already remembered");
            }
        }
        Commands::Preferences => {
            let path = tj_core::paths::memory_db()?;
            let prefs = if path.exists() {
                tj_core::memory::list_preferences(&tj_core::memory::open(&path)?)?
            } else {
                Vec::new()
            };
            if prefs.is_empty() {
                println!("no preferences yet — add one with `task-journal remember \"...\"`");
            } else {
                for p in prefs {
                    println!("- {p}");
                }
            }
        }
        Commands::Consolidate { max_facts } => {
            run_consolidate(max_facts)?;
        }
        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())?;
            }
            let open_kids = tj_core::db::count_open_children(&conn, &task_id)?;
            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()?;
            if open_kids > 0 {
                eprintln!("note: {open_kids} open subtask(s) under {task_id}");
            }

            // Non-blocking completeness warning. The close above already
            // succeeded; re-open, apply the close event to the index, then
            // assess. Any error here must NOT fail the close — handle
            // locally, never `?`-propagate.
            if let Ok(conn) = tj_core::db::open(&state_path) {
                let _ = tj_core::db::ingest_new_events(&conn, &events_path, &project_hash);
                if let Ok(report) = tj_core::completeness::assess(
                    &conn,
                    &task_id,
                    tj_core::completeness::pending_count(),
                ) {
                    if !report.is_complete() {
                        eprintln!(
                            "note: task {task_id} closed with {} completeness gap(s):",
                            report.gaps.len()
                        );
                        for g in &report.gaps {
                            eprintln!("  âš  {}", g.detail);
                        }
                    }
                }
            }

            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,
            backfill,
            backend,
            auto_capture,
            proactive_recall,
        } => {
            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")
                                            || c.contains("task-journal nudge"))
                                    })
                                    .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).
                // Bake the selected backend into the hook command. Default
                // "hybrid" stays flag-free (heuristic first, then the agent-sdk
                // → api fallback chain). A non-default backend — e.g.
                // `--backend=agent-sdk` for subscription users with no API key
                // — is passed through so the spawned classify-worker honors it.
                if !matches!(
                    backend.as_str(),
                    "hybrid" | "agent-sdk" | "api" | "heuristic"
                ) {
                    anyhow::bail!(
                        "unknown --backend: {backend} (expected `hybrid`, `agent-sdk`, `api`, or `heuristic`)"
                    );
                }
                let cmd_string = if backend == "hybrid" {
                    "task-journal ingest-hook || true".to_string()
                } else {
                    format!("task-journal ingest-hook --backend={backend} || true")
                };
                let cmd = cmd_string.as_str();
                let nudge_cmd = "task-journal nudge || true";
                // v0.14.x — self-tagging-first. The DEFAULT wires only no-model
                // hooks: SessionStart → ingest-hook short-circuits to inject the
                // read-only resume pack (no classifier); UserPromptSubmit → `nudge`
                // prints a reminder to keep recording (no model, no spawn). The
                // per-message classifier (`claude -p`) is opt-in via
                // `--auto-capture`, which appends `ingest-hook` to the message
                // events. Primary capture is the agent self-tagging via the MCP
                // tools.
                let mut entries = serde_json::json!({
                    "SessionStart":     [{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }],
                    "UserPromptSubmit": [{ "matcher": "", "hooks": [{ "type": "command", "command": nudge_cmd }] }],
                });
                if auto_capture {
                    let obj = entries.as_object_mut().expect("entries is an object");
                    // UserPromptSubmit keeps the nudge AND gains the classifier.
                    obj.insert(
                        "UserPromptSubmit".into(),
                        serde_json::json!([{ "matcher": "", "hooks": [
                            { "type": "command", "command": nudge_cmd },
                            { "type": "command", "command": cmd },
                        ]}]),
                    );
                    for ev in ["PostToolUse", "Stop", "PreCompact"] {
                        obj.insert(
                            ev.to_string(),
                            serde_json::json!([{ "matcher": "", "hooks": [{ "type": "command", "command": cmd }] }]),
                        );
                    }
                }
                if proactive_recall {
                    // Append the recall injector to the UserPromptSubmit hooks,
                    // keeping whatever is already there (nudge, and ingest when
                    // --auto-capture is also set).
                    let obj = entries.as_object_mut().expect("entries is an object");
                    let ups = obj
                        .entry("UserPromptSubmit")
                        .or_insert_with(|| serde_json::json!([{ "matcher": "", "hooks": [] }]));
                    if let Some(hooks) = ups
                        .as_array_mut()
                        .and_then(|a| a.get_mut(0))
                        .and_then(|e| e.get_mut("hooks"))
                        .and_then(|h| h.as_array_mut())
                    {
                        hooks.push(serde_json::json!({
                            "type": "command",
                            "command": "task-journal recall-hook || true",
                        }));
                    }
                }
                // MERGE our entries into the existing `hooks` block — touch ONLY
                // task-journal hooks, never clobber other plugins' hooks. For each
                // event we (a) strip any prior task-journal entry (idempotent
                // re-install) then (b) append ours, leaving foreign hooks and
                // untouched events intact.
                let is_tj = |c: &str| {
                    c.contains("task-journal ingest-hook")
                        || c.contains("task-journal nudge")
                        || c.contains("task-journal recall-hook")
                };
                let hooks_block = hooks_obj
                    .entry("hooks".to_string())
                    .or_insert_with(|| serde_json::json!({}));
                let hooks_block = hooks_block
                    .as_object_mut()
                    .ok_or_else(|| anyhow::anyhow!("settings `hooks` is not an object"))?;
                for (event, our_arr) in entries.as_object().expect("entries is an object") {
                    let existing = hooks_block
                        .entry(event.clone())
                        .or_insert_with(|| serde_json::json!([]));
                    let existing = existing
                        .as_array_mut()
                        .ok_or_else(|| anyhow::anyhow!("hooks.{event} is not an array"))?;
                    for entry in existing.iter_mut() {
                        if let Some(inner) = entry.get_mut("hooks").and_then(|v| v.as_array_mut()) {
                            inner.retain(|h| {
                                h.get("command")
                                    .and_then(|c| c.as_str())
                                    .map(|c| !is_tj(c))
                                    .unwrap_or(true)
                            });
                        }
                    }
                    existing.retain(|e| {
                        e.get("hooks")
                            .and_then(|v| v.as_array())
                            .map(|a| !a.is_empty())
                            .unwrap_or(true)
                    });
                    for our_entry in our_arr.as_array().expect("event entry is an array") {
                        existing.push(our_entry.clone());
                    }
                }
            }
            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}%");
            }
            // Memory platform (Pillars A/B/C): the global cross-project index.
            let mem_path = tj_core::paths::memory_db()?;
            if mem_path.exists() {
                if let Ok(g) = tj_core::memory::open(&mem_path) {
                    let entries = tj_core::memory::count(&g).unwrap_or(0);
                    let prefs = tj_core::memory::list_preferences(&g)
                        .map(|p| p.len())
                        .unwrap_or(0);
                    println!("memory (global cross-project recall index):");
                    println!("  recall entries: {entries}");
                    println!("  preferences: {prefs}");
                }
            }
        }
        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_core::classifier::agent_sdk::IN_CLASSIFIER_ENV).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, payload) = match (kind, text) {
                (Some(k), Some(t)) => (k, t, serde_json::Value::Null),
                _ => 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())?;

            // Live Claude Code session id (hook payload → env fallback),
            // stamped additively onto the live events this hook emits so
            // consumers can correlate them with the session. None when
            // neither source is present (standalone behaviour unchanged).
            let live_session_id = tj_core::session_id::live_session_id(Some(&payload));

            // Push-recall (claude-memory-60m). Best-effort, fail-open, read-only.
            // After a (non-MCP) tool call, surface a relevant prior
            // rejection/decision via an additionalContext envelope so the agent
            // doesn't re-walk a ruled-out path. Gated by TJ_PUSH_RECALL=0.
            //
            // Dedup vs claude-memory-7km: skip MCP-tool turns — those are
            // handled by 7km's updatedMCPToolOutput path, so emitting
            // additionalContext here too would double-surface the same recall.
            // The two paths are mutually exclusive by tool type (this =
            // non-mcp tools; 7km = mcp__ tools). The block only adds a stdout
            // envelope; it never touches the JSONL log or the pending flow
            // below, and any error is swallowed so the hook can't break.
            let tool_is_mcp = payload
                .get("tool_name")
                .and_then(|v| v.as_str())
                .map(|n| n.starts_with("mcp__"))
                .unwrap_or(false);
            if kind == "PostToolUse"
                && !tool_is_mcp
                && std::env::var("TJ_PUSH_RECALL").as_deref() != Ok("0")
                && events_path.exists()
            {
                let state_path =
                    tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
                if let Ok(conn) = tj_core::db::open(&state_path) {
                    let _ = tj_core::db::ingest_new_events(&conn, &events_path, &project_hash);
                    if let Ok(hits) = tj_core::recall::relevant_recall(
                        &conn,
                        &text,
                        tj_core::recall::DEFAULT_MAX_HITS,
                    ) {
                        if !hits.is_empty() {
                            let mut ctx = String::new();
                            for h in &hits {
                                let verb = match h.event_type {
                                    tj_core::event::EventType::Rejection => "previously rejected",
                                    _ => "previously decided",
                                };
                                ctx.push_str(&format!(
                                    "âš  recall: in task {} you {}: {}\n",
                                    h.task_id, verb, h.text
                                ));
                            }
                            let envelope = serde_json::json!({
                                "hookSpecificOutput": {
                                    "hookEventName": "PostToolUse",
                                    "additionalContext": ctx.trim_end(),
                                }
                            });
                            println!("{}", serde_json::to_string(&envelope)?);
                        }
                    }
                }
            }

            // Push-recall via updatedMCPToolOutput (claude-memory-7km). For an
            // MCP PostToolUse turn whose input echoes a prior rejection/decision,
            // prepend a recall banner to what Claude sees of that tool's output.
            // Best-effort, read-only: any miss or error emits nothing and the
            // real output passes through unchanged. Complements 60m (which skips
            // mcp__ tools) — gated MCP-only, falls through to the queue path so
            // event capture is unaffected. Disabled by TJ_PUSH_RECALL=0.
            if kind == "PostToolUse" && std::env::var("TJ_PUSH_RECALL").as_deref() != Ok("0") {
                if let Some(envelope) = push_recall_envelope(&payload, &events_path, &project_hash)
                {
                    println!("{}", serde_json::to_string(&envelope)?);
                }
            }

            // 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" {
                // User preferences are global, so they surface even in a fresh
                // project with no events of its own (Pillar C "remember me").
                let prefs_block = session_preferences_block();
                // 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. Preferences still go
                // out if there are any.
                if !events_path.exists() {
                    if !prefs_block.is_empty() {
                        emit_session_context(&prefs_block);
                    }
                    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() {
                    if !prefs_block.is_empty() {
                        emit_session_context(&prefs_block);
                    }
                    return Ok(());
                }
                // After a compaction (source=="compact"), re-inject the
                // active task + its in-force constraints so the rebuilt
                // context doesn't lose what it was doing. Best-effort:
                // any error → no reminder, never abort SessionStart.
                let source = payload.get("source").and_then(|v| v.as_str()).unwrap_or("");
                let mut bundle = String::new();
                // Preferences lead the bundle — they're the smallest, most
                // durable signal about how the user wants to be worked with.
                if !prefs_block.is_empty() {
                    bundle.push_str(&prefs_block);
                    bundle.push_str("\n\n");
                }
                if source == "compact" {
                    if let Ok(Some(reminder)) = tj_core::reminder::active_task_reminder(&conn) {
                        bundle.push_str(&reminder);
                        bundle.push_str("\n\n");
                    }
                }
                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");
                }

                // v0.10.2 X4: emit `watchPaths` so Claude Code starts
                // monitoring our marker files (CLAUDE.md, README.md,
                // .docs/plans). When any of them changes, Claude Code
                // fires a FileChanged hook event — our ingest-hook
                // handler below treats those as `evidence` entries on
                // the active task so the journal captures
                // "instructions were updated mid-session" without the
                // user manually logging it. Only paths that exist at
                // SessionStart time are emitted (no point watching a
                // non-existent file — Claude Code logs `watcher error`
                // and gives up on it). Gated by TJ_WATCH_PATHS=0.
                let allow_watch_paths = std::env::var("TJ_WATCH_PATHS").as_deref() != Ok("0");
                let watch_candidates = [
                    cwd.join("CLAUDE.md"),
                    cwd.join("README.md"),
                    cwd.join(".docs").join("plans"),
                ];
                let watch_paths: Vec<String> = if allow_watch_paths {
                    watch_candidates
                        .iter()
                        .filter(|p| p.exists())
                        .map(|p| p.to_string_lossy().to_string())
                        .collect()
                } else {
                    Vec::new()
                };

                // We deliberately DO NOT emit `sessionTitle` or
                // `initialUserMessage` here. The v0.10.1 X2 experiment set
                // `sessionTitle` to "TJ — <task_id> (<n> open)", which
                // OVERRODE Claude Code's native session name with our task id
                // — users saw "TJ — tj-qqay98cpc2" instead of a name derived
                // from their own prompt. `initialUserMessage` injected a
                // "[Task Journal resumed: …]" banner into the next prompt,
                // which the auto-open path then captured as a garbage task
                // title. The resume context the model actually needs already
                // rides in `additionalContext`; the tab label belongs to
                // Claude Code, not to us. (0.14.3)
                let mut hook_specific = serde_json::json!({
                    "hookEventName": "SessionStart",
                    "additionalContext": bundle.trim_end(),
                });
                if !watch_paths.is_empty() {
                    hook_specific["watchPaths"] = serde_json::Value::Array(
                        watch_paths
                            .into_iter()
                            .map(serde_json::Value::String)
                            .collect(),
                    );
                }
                let envelope = serde_json::json!({
                    "hookSpecificOutput": hook_specific,
                });
                println!("{}", serde_json::to_string(&envelope)?);
                return Ok(());
            }

            // v0.10.2 X4: FileChanged. Claude Code 2.1.x fires this
            // event whenever a path in `watchPaths` (emitted on
            // SessionStart) changes. Payload: { file_path, event:
            // "change"|"add"|"unlink" }. We translate it into an
            // `evidence` event on the active task — captures
            // "the user/agent edited CLAUDE.md mid-session" without
            // anyone typing anything. Schema verified in 2.1.160:
            // `literal("FileChanged"), file_path: y.string(), event:
            // y.enum(["change","add","unlink"])`.
            //
            // No active task → drop silently (we're not opening a
            // task just because a watched file moved). No events_path
            // → ditto, fresh project.
            if kind == "FileChanged" {
                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 file_path = payload
                    .get("file_path")
                    .and_then(|v| v.as_str())
                    .unwrap_or("(unknown)");
                let change = payload
                    .get("event")
                    .and_then(|v| v.as_str())
                    .unwrap_or("change");
                // Trim noisy absolute paths to project-relative when
                // possible — the journal is per-project so the prefix
                // is redundant and just steals tokens from the pack.
                let display_path = cwd
                    .to_str()
                    .and_then(|c| file_path.strip_prefix(c))
                    .map(|s| s.trim_start_matches('/').to_string())
                    .unwrap_or_else(|| file_path.to_string());
                let evidence_text = format!("FileChanged ({change}): {display_path}");
                let mut event = tj_core::event::Event::new(
                    &tc.task_id,
                    tj_core::event::EventType::Evidence,
                    tj_core::event::Author::Classifier,
                    tj_core::event::Source::Hook,
                    evidence_text,
                );
                event.confidence = Some(0.9);
                event.status = tj_core::event::EventStatus::Confirmed;
                tj_core::session_id::stamp_session_id(&mut event.meta, live_session_id.as_deref());
                let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
                writer.append(&event)?;
                writer.flush_durable()?;
                println!("{}", event.event_id);
                return Ok(());
            }

            // PreCompact: Claude Code is about to compact the conversation.
            // Two responsibilities:
            //   1. Catch-up ingest — read the transcript JSONL tail (entries
            //      newer than the active task's last event timestamp) and
            //      enqueue them as pending v2 chunks for the classify-worker.
            //      Closes the gap between the last PostToolUse hook and the
            //      compaction event, where chunks would otherwise be lost.
            //   2. Boundary marker — synthetic decision event so the
            //      post-compact agent sees a clear cut in the journal.
            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(());
                };

                // (1) Catch-up ingest. Best-effort: missing transcript_path
                // or unreadable JSONL falls through to the marker only.
                let last_event_ts: Option<String> = conn
                    .query_row(
                        "SELECT timestamp FROM events_index WHERE task_id=?1 \
                         ORDER BY timestamp DESC LIMIT 1",
                        rusqlite::params![&tc.task_id],
                        |r| r.get::<_, String>(0),
                    )
                    .ok();
                let transcript_path = payload
                    .get("transcript_path")
                    .and_then(|x| x.as_str())
                    .map(std::path::PathBuf::from);
                if let Some(tp) = transcript_path.as_ref() {
                    if tp.exists() {
                        let enq = enqueue_transcript_chunks_since_last_event(
                            tp,
                            &events_path,
                            &project_hash,
                            &backend,
                            last_event_ts.as_deref(),
                            "PreCompactChunk",
                            live_session_id.as_deref(),
                        )
                        .unwrap_or(0);
                        if enq > 0 && std::env::var("TJ_DISABLE_CLASSIFY_SPAWN").is_err() {
                            let _ = spawn_classify_worker(&backend);
                        }
                    }
                }

                // (2) Boundary marker.
                let now = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true);

                // v0.10.3: dedupe near-duplicate markers. Two PreCompact
                // hook firings within DEDUP_WINDOW_SECS — caused by
                // multi-plugin race, rapid compact-then-restore, or a
                // retried hook — both append "Conversation compacted at
                // T" events with the same wall-clock second. Skip if
                // the most recent decision event already carries this
                // marker text and was written under a minute ago.
                const DEDUP_WINDOW_SECS: i64 = 60;
                let last_marker: Option<(String, String)> = conn
                    .query_row(
                        "SELECT ei.timestamp, COALESCE(sf.text, '') \
                         FROM events_index ei \
                         LEFT JOIN search_fts sf ON sf.event_id = ei.event_id \
                         WHERE ei.task_id = ?1 AND ei.type = 'decision' \
                         ORDER BY ei.timestamp DESC LIMIT 1",
                        rusqlite::params![&tc.task_id],
                        |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)),
                    )
                    .ok();
                if let Some((ts, text)) = last_marker {
                    if text.starts_with("Conversation compacted at") {
                        if let Ok(prev) = chrono::DateTime::parse_from_rfc3339(&ts) {
                            let delta = (chrono::Utc::now()
                                .signed_duration_since(prev.with_timezone(&chrono::Utc)))
                            .num_seconds();
                            if delta.abs() < DEDUP_WINDOW_SECS {
                                // Marker recently appended — skip the
                                // second one. Still print SOMETHING so
                                // hook callers see a stable exit shape;
                                // emit the previous event_id we'd have
                                // duplicated would not be available here
                                // without an extra query, so emit empty.
                                return Ok(());
                            }
                        }
                    }
                }

                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;
                tj_core::session_id::stamp_session_id(&mut event.meta, live_session_id.as_deref());
                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(());
            }

            // Stop: Claude Code is about to end the session. Same
            // catch-up logic as PreCompact (read transcript tail,
            // enqueue chunks newer than the active task's last
            // event timestamp), but no boundary marker — a session
            // end isn't a reasoning boundary, the task is just
            // pausing. The v0.7.0-era Stop hook fired with hardcoded
            // text="Session ended" which carried no signal and just
            // littered the pending queue with noise; v0.9.3 replaces
            // that with a real catch-up.
            //
            // Skip the catch-up when running through the mock test
            // path (mock_event_type + mock_task_id) — those tests
            // expect their explicit `--kind=Stop` invocation to fall
            // through to the mock-classifier dispatch below, not be
            // intercepted by the new transcript-tail logic.
            let is_mock_stop = mock_event_type.is_some() && mock_task_id.is_some();
            if !is_mock_stop && kind == "Stop" {
                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 last_event_ts: Option<String> = conn
                    .query_row(
                        "SELECT timestamp FROM events_index WHERE task_id=?1 \
                         ORDER BY timestamp DESC LIMIT 1",
                        rusqlite::params![&tc.task_id],
                        |r| r.get::<_, String>(0),
                    )
                    .ok();
                let transcript_path = payload
                    .get("transcript_path")
                    .and_then(|x| x.as_str())
                    .map(std::path::PathBuf::from);
                if let Some(tp) = transcript_path.as_ref() {
                    if tp.exists() {
                        let enq = enqueue_transcript_chunks_since_last_event(
                            tp,
                            &events_path,
                            &project_hash,
                            &backend,
                            last_event_ts.as_deref(),
                            "StopChunk",
                            live_session_id.as_deref(),
                        )
                        .unwrap_or(0);
                        if enq > 0 && std::env::var("TJ_DISABLE_CLASSIFY_SPAWN").is_err() {
                            let _ = spawn_classify_worker(&backend);
                        }
                    }
                }
                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,
                    live_session_id.as_deref(),
                )?;
                // 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);

                // v0.10.0 asyncRewake backlog signal. Only the PostToolUse
                // hook runs as asyncRewake (hooks.json sets TJ_ASYNC_REWAKE=1
                // there), so other kinds — and direct CLI invocations —
                // never exit 2 even on overflow. Exit code 2 from a sync
                // hook would BLOCK the operation; only asyncRewake hooks
                // treat code 2 as "wake the model with rewakeMessage". stdout
                // is appended to the wake message, so the user sees the
                // drain command without us reaching into stderr.
                let allow_wake = std::env::var("TJ_ASYNC_REWAKE").as_deref() == Ok("1");
                if allow_wake && kind == "PostToolUse" {
                    let pending_count = count_pending_entries(&events_path).unwrap_or(0);
                    if pending_count > PENDING_OVERFLOW_THRESHOLD {
                        println!(
                            "Task Journal pending queue: {pending_count} entries. Classifier behind — run `task-journal pending-gc --days 0` to drain.",
                        );
                        std::process::exit(2);
                    }
                }
                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 Some(new_task) =
                        auto_open_task_from_prompt(&events_path, &project_hash, &conn, &text)?
                    else {
                        // Prompt was only machine noise — nothing worth a task.
                        return Ok(());
                    };
                    recent.push(new_task);
                }

                use tj_core::classifier::Classifier;
                let classifier: Box<dyn Classifier> = match backend.as_str() {
                    // v0.8.0: hybrid is the new default. Heuristic
                    // pattern-matching first (free), Anthropic API
                    // fallback when uncertain (requires ANTHROPIC_API_KEY).
                    // No background spawn of `claude -p` — that subprocess
                    // now bills tokens separately from Pro/Max.
                    "hybrid" | "" => {
                        Box::new(tj_core::classifier::hybrid::HybridClassifier::from_env())
                    }
                    "api" => Box::new(tj_core::classifier::http::AnthropicClassifier::from_env()?),
                    "agent-sdk" => Box::new(
                        tj_core::classifier::agent_sdk::ClaudeCliClassifier::from_env()
                            .ok_or_else(|| {
                                anyhow::anyhow!(
                                    "agent-sdk backend selected but no `claude` binary on PATH — \
                                     install Claude Code (https://claude.com/claude-code) or pick another --backend"
                                )
                            })?,
                    ),
                    "heuristic" => {
                        // Heuristic-only: no LLM at all. Trades coverage
                        // for absolute zero-cost / offline operation.
                        use tj_core::classifier::heuristic::try_heuristic;
                        use tj_core::classifier::{ClassifyInput, ClassifyOutput};
                        struct HeuristicOnly;
                        impl Classifier for HeuristicOnly {
                            fn classify(
                                &self,
                                input: &ClassifyInput,
                            ) -> anyhow::Result<ClassifyOutput> {
                                try_heuristic(input).ok_or_else(|| {
                                        anyhow::anyhow!(
                                            "heuristic uncertain (heuristic-only mode has no LLM fallback)"
                                        )
                                    })
                            }
                        }
                        Box::new(HeuristicOnly)
                    }
                    other => anyhow::bail!(
                        "unknown backend: {other} (expected `hybrid`, `agent-sdk`, `api`, or `heuristic`)"
                    ),
                };
                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::Dream {
            since,
            task,
            dry_run,
            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"));
            let state_path = tj_core::paths::state_dir()?.join(format!("{project_hash}.sqlite"));
            let conn = tj_core::db::open(&state_path)?;

            // 1. Resolve session files in scope.
            let project_dir = tj_core::session::discovery::find_project_dir(&cwd)?;
            let Some(project_dir) = project_dir else {
                println!("dream: no Claude Code sessions found for this project");
                return Ok(());
            };
            let session_paths = tj_core::session::discovery::list_sessions(&project_dir)?;

            let since_time = if let Some(days) = since {
                Some(
                    std::time::SystemTime::now()
                        - std::time::Duration::from_secs((days.max(0) as u64) * 86_400),
                )
            } else {
                // Watermark → SystemTime. Absent watermark = all sessions.
                match tj_core::dream::state::last_dream_at(&conn, &project_hash)? {
                    Some(ts) => chrono::DateTime::parse_from_rfc3339(&ts)
                        .ok()
                        .map(std::time::SystemTime::from),
                    None => None,
                }
            };

            let scoped: Vec<tj_core::dream::scope::SessionFile> = session_paths
                .into_iter()
                .filter_map(|p| {
                    let mtime = std::fs::metadata(&p).ok()?.modified().ok()?;
                    Some(tj_core::dream::scope::SessionFile { path: p, mtime })
                })
                .collect();
            let in_scope = tj_core::dream::scope::in_scope(scoped, since_time, limit);

            // 2. Assemble (session_id, BackfillInput) per session.
            let run_id = ulid::Ulid::new().to_string();
            let sessions = build_dream_inputs(&events_path, &in_scope, task.as_deref())?;

            // 3. Run.
            let opts = tj_core::dream::DreamOptions {
                project_hash: project_hash.clone(),
                dry_run,
            };
            if dry_run {
                println!("dream (dry-run): {} session(s) in scope", sessions.len());
                return Ok(());
            }
            // Prefer the subscription-native agent-sdk backend (local `claude`
            // CLI, pinned to Haiku — cheap, no ANTHROPIC_API_KEY). Fall back to
            // the Anthropic API backend only when no `claude` is on PATH.
            let backend: Box<dyn tj_core::dream::backend::DreamBackend> =
                match tj_core::dream::agent_sdk::ClaudeCliDreamBackend::from_env() {
                    Some(b) => {
                        eprintln!("dream: backend=agent-sdk (claude CLI, Haiku)");
                        Box::new(b)
                    }
                    None => {
                        eprintln!(
                            "dream: no `claude` on PATH — backend=api (needs ANTHROPIC_API_KEY)"
                        );
                        Box::new(tj_core::dream::http::AnthropicDreamBackend::from_env()?)
                    }
                };
            let report = tj_core::dream::run_dream(
                &conn,
                &events_path,
                &opts,
                backend.as_ref(),
                sessions,
                &run_id,
            )?;

            // 4. Advance watermark to now (only reached on success).
            tj_core::dream::state::set_last_dream_at(
                &conn,
                &project_hash,
                &chrono::Utc::now().to_rfc3339(),
            )?;
            println!(
                "dream: {} session(s) processed, {} event(s) backfilled",
                report.sessions_processed, report.events_backfilled
            );
        }
        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,
            event_type,
        } => {
            // v0.10.3: sanitize FTS5 query so hyphenated IDs / paths /
            // colons no longer crash with "no such column" mid-search.
            let fts_query = tj_core::fts::sanitize_query(&query);
            let like_query = tj_core::fts::like_pattern(&query);
            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 ids = match run_search(
                        &conn,
                        &fts_query,
                        &like_query,
                        event_type.as_deref(),
                        limit,
                    ) {
                        Ok(v) => v,
                        Err(_) => continue,
                    };
                    for id in ids {
                        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 ids = run_search(&conn, &fts_query, &like_query, event_type.as_deref(), limit)?;
                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::Nudge => {
            // No model, no spawn, never touches the classifier — just prints a
            // UserPromptSubmit additionalContext reminder so the agent keeps
            // recording via the MCP tools deep into a session.
            let env = serde_json::json!({
                "hookSpecificOutput": {
                    "hookEventName": "UserPromptSubmit",
                    "additionalContext": "📓 task-journal — record as you go: the moment you commit to a decision, rule an approach out, or verify a fact, call event_add (open or resume a task first). Don't batch it to the end. This memory only works if you log it now."
                }
            });
            print!("{env}");
        }
        Commands::RecallHook => {
            run_recall_hook()?;
        }
        Commands::Rejected {
            topic,
            all_projects,
            limit,
            since,
        } => {
            run_rejected(&topic, all_projects, limit, since)?;
        }
        Commands::ExportPr { task_id } => {
            run_export_pr(&task_id)?;
        }
        Commands::ExportMemory {
            task,
            all_closed,
            dry_run,
        } => {
            run_export_memory(task.as_deref(), all_closed, dry_run)?;
        }
    }
    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, '-' | '"' | '*' | ':' | '(' | ')'))
}

/// v0.10.3: shared search helper used by `Commands::Search` for both
/// the cwd and `--all-projects` paths. Runs the sanitized FTS5 MATCH
/// first; on zero hits, scans `search_fts.text` via `LIKE` so
/// hyphenated identifiers (e.g. `OPS-306`) and substrings missed by
/// the unicode61 tokenizer still surface.
fn run_search(
    conn: &rusqlite::Connection,
    fts_query: &str,
    like_query: &str,
    event_type: Option<&str>,
    limit: usize,
) -> Result<Vec<String>> {
    let (fts_sql, fts_uses_type) = match event_type {
        Some(_) => (
            "SELECT DISTINCT task_id FROM search_fts \
             WHERE search_fts MATCH ?1 AND type = ?2 LIMIT ?3",
            true,
        ),
        None => (
            "SELECT DISTINCT task_id FROM search_fts \
             WHERE search_fts MATCH ?1 LIMIT ?2",
            false,
        ),
    };
    let mut stmt = conn.prepare(fts_sql)?;
    let ids: Vec<String> = if fts_uses_type {
        let ty = event_type.unwrap();
        stmt.query_map(rusqlite::params![fts_query, ty, limit as i64], |r| {
            r.get::<_, String>(0)
        })?
        .collect::<rusqlite::Result<_>>()?
    } else {
        stmt.query_map(rusqlite::params![fts_query, limit as i64], |r| {
            r.get::<_, String>(0)
        })?
        .collect::<rusqlite::Result<_>>()?
    };
    if !ids.is_empty() {
        return Ok(ids);
    }

    let (like_sql, like_uses_type) = match event_type {
        Some(_) => (
            "SELECT DISTINCT task_id FROM search_fts \
             WHERE text LIKE ?1 AND type = ?2 LIMIT ?3",
            true,
        ),
        None => (
            "SELECT DISTINCT task_id FROM search_fts \
             WHERE text LIKE ?1 LIMIT ?2",
            false,
        ),
    };
    let mut stmt_like = conn.prepare(like_sql)?;
    let ids_like: Vec<String> = if like_uses_type {
        let ty = event_type.unwrap();
        stmt_like
            .query_map(rusqlite::params![like_query, ty, limit as i64], |r| {
                r.get::<_, String>(0)
            })?
            .collect::<rusqlite::Result<_>>()?
    } else {
        stmt_like
            .query_map(rusqlite::params![like_query, limit as i64], |r| {
                r.get::<_, String>(0)
            })?
            .collect::<rusqlite::Result<_>>()?
    };
    Ok(ids_like)
}

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 run_export_memory(task: Option<&str>, _all_closed: bool, dry_run: bool) -> Result<()> {
    const MAX_ITEMS: usize = 10;

    let cwd = std::env::current_dir()?;
    let cwd_str = cwd.to_string_lossy().to_string();
    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)?;
    }

    // Resolve scope.
    let task_ids: Vec<String> = match task {
        Some(id) => {
            let exists: bool = conn
                .query_row(
                    "SELECT 1 FROM tasks WHERE task_id = ?1",
                    rusqlite::params![id],
                    |_| Ok(true),
                )
                .unwrap_or(false);
            if !exists {
                eprintln!("Error: task not found: {id}");
                std::process::exit(1);
            }
            vec![id.to_string()]
        }
        None => {
            // default + --all-closed → all closed tasks
            let mut stmt =
                conn.prepare("SELECT task_id FROM tasks WHERE status='closed' ORDER BY task_id")?;
            let ids = stmt
                .query_map([], |r| r.get::<_, String>(0))?
                .collect::<std::result::Result<Vec<_>, _>>()?;
            ids
        }
    };

    if task_ids.is_empty() {
        eprintln!("note: no closed tasks to export");
        return Ok(());
    }

    // Memory dir: ~/.claude/projects/<encoded-cwd>/memory/
    let memory_dir = tj_core::session::discovery::projects_dir()?
        .join(tj_core::session::discovery::encode_project_path(&cwd_str))
        .join("memory");

    for id in &task_ids {
        let title: String = conn.query_row(
            "SELECT title FROM tasks WHERE task_id = ?1",
            rusqlite::params![id],
            |r| r.get(0),
        )?;
        let meta = tj_core::db::task_metadata(&conn, id)?.unwrap_or_default();

        // decision + constraint one-liners, oldest-first (== run_export_pr style).
        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 AND ei.type IN ('decision','constraint')
             ORDER BY ei.timestamp ASC",
        )?;
        let rows = stmt.query_map(rusqlite::params![id], |r| {
            Ok((
                r.get::<_, String>(0)?,
                r.get::<_, Option<String>>(1)?.unwrap_or_default(),
            ))
        })?;
        let mut decisions = Vec::new();
        let mut constraints = Vec::new();
        for row in rows {
            let (ty, text) = row?;
            let line = text.lines().next().unwrap_or("").trim().to_string();
            if line.is_empty() {
                continue;
            }
            match ty.as_str() {
                "decision" if decisions.len() < MAX_ITEMS => decisions.push(line),
                "constraint" if constraints.len() < MAX_ITEMS => constraints.push(line),
                _ => {}
            }
        }

        let slug = tj_core::frontmatter::slugify(&title);
        let content = tj_core::frontmatter::render_memory(&tj_core::frontmatter::MemoryInput {
            title: &title,
            meta: &meta,
            decisions: &decisions,
            constraints: &constraints,
        });
        let file_path = memory_dir.join(format!("tj-{id}-{slug}.md"));

        if dry_run {
            println!("# would write: {}", file_path.display());
            println!("{content}");
        } else {
            std::fs::create_dir_all(&memory_dir)?;
            std::fs::write(&file_path, content)?;
            println!("wrote {}", file_path.display());
        }
    }
    Ok(())
}

/// How many of a task's most-recent `constraint` events to surface in
/// the classifier prompt. Kept small so the prompt stays bounded.
const CONSTRAINT_CONTEXT_LIMIT: i64 = 5;

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<_, _>>()?;

        // Gather the task's most-recent `constraint` events so the
        // classifier can recognise chunks that violate a known limit.
        // Mirrors the last_events join, filtered to constraints and
        // bounded to keep the prompt small.
        let mut c_stmt = conn.prepare(
            "SELECT sf.text FROM events_index ei
             LEFT JOIN search_fts sf ON sf.event_id = ei.event_id
             WHERE ei.task_id = ?1 AND ei.type = 'constraint'
             ORDER BY ei.timestamp DESC LIMIT ?2",
        )?;
        let constraints: Vec<String> = c_stmt
            .query_map(rusqlite::params![task_id, CONSTRAINT_CONTEXT_LIMIT], |r| {
                let txt: Option<String> = r.get(0)?;
                Ok(txt
                    .unwrap_or_default()
                    .chars()
                    .take(120)
                    .collect::<String>())
            })?
            .collect::<Result<Vec<String>, _>>()?
            .into_iter()
            .filter(|s| !s.is_empty())
            .collect();

        out.push(tj_core::classifier::TaskContext {
            task_id,
            title,
            last_events,
            constraints,
        });
    }
    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.
/// Best-effort sync of a project's high-signal events into the global
/// cross-project memory index. Never fails the caller — a slightly stale recall
/// index is fine; a broken `ask`/`embed` is not.
fn sync_global_memory(project_conn: &rusqlite::Connection, project_hash: &str) {
    let result = tj_core::paths::memory_db()
        .and_then(tj_core::memory::open)
        .and_then(|g| tj_core::memory::sync_from_project(&g, project_conn, project_hash));
    if let Err(e) = result {
        tracing::debug!("global memory sync skipped: {e:#}");
    }
}

/// Proactive recall injector (opt-in hook). Reads the UserPromptSubmit payload
/// from stdin, keyword-searches the global index for relevant prior
/// decisions/rejections/constraints across all projects, and emits a budgeted
/// `additionalContext` block. Never blocks the prompt: any miss, empty result,
/// or error exits silently with no output.
fn run_recall_hook() -> anyhow::Result<()> {
    // Opt-out and recursion guard (never inject into our own classifier spawn).
    if std::env::var("TJ_PROACTIVE_RECALL").as_deref() == Ok("0") {
        return Ok(());
    }
    if std::env::var(tj_core::classifier::agent_sdk::IN_CLASSIFIER_ENV).is_ok() {
        return Ok(());
    }
    let global_path = tj_core::paths::memory_db()?;
    if !global_path.exists() {
        return Ok(());
    }

    use std::io::Read;
    let mut buf = String::new();
    if std::io::stdin().read_to_string(&mut buf).is_err() || buf.trim().is_empty() {
        return Ok(());
    }
    // The UserPromptSubmit payload carries the prompt under `prompt`; fall back
    // to the raw stdin if it isn't JSON.
    let prompt = serde_json::from_str::<serde_json::Value>(&buf)
        .ok()
        .and_then(|v| {
            v.get("prompt")
                .and_then(|p| p.as_str())
                .map(|s| s.to_string())
        })
        .unwrap_or(buf);
    if prompt.trim().is_empty() {
        return Ok(());
    }

    let conn = tj_core::memory::open(&global_path)?;
    let k: usize = std::env::var("TJ_RECALL_K")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(3);
    let hits = tj_core::memory::keyword_search(&conn, &prompt, k)?;
    if hits.is_empty() {
        return Ok(());
    }

    let budget: usize = std::env::var("TJ_RECALL_BUDGET_CHARS")
        .ok()
        .and_then(|s| s.parse().ok())
        .unwrap_or(900);
    let mut ctx = String::from(
        "📓 task-journal — relevant prior reasoning from your history (you may have decided this before):\n",
    );
    for h in &hits {
        let snippet: String = h.text.chars().take(160).collect();
        let proj: String = h.project_hash.chars().take(8).collect();
        let line = format!(
            "âš  [{}] {} (project {proj}, {})\n",
            h.event_type, snippet, h.task_id
        );
        if ctx.len() + line.len() > budget {
            break;
        }
        ctx.push_str(&line);
    }
    let env = serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "UserPromptSubmit",
            "additionalContext": ctx.trim_end(),
        }
    });
    print!("{env}");
    Ok(())
}

/// Render the user's standing preferences as a SessionStart context block, or
/// "" when there are none. Capped so it never floods the system prompt.
fn session_preferences_block() -> String {
    let prefs = match tj_core::paths::memory_db()
        .and_then(tj_core::memory::open)
        .and_then(|c| tj_core::memory::list_preferences(&c))
    {
        Ok(p) if !p.is_empty() => p,
        _ => return String::new(),
    };
    let mut s = String::from("## Your standing preferences (remember these across sessions):\n");
    for p in prefs {
        let line = format!("- {p}\n");
        if s.len() + line.len() > 800 {
            break;
        }
        s.push_str(&line);
    }
    s.trim_end().to_string()
}

/// Emit a SessionStart `additionalContext` envelope and nothing else.
fn emit_session_context(ctx: &str) {
    let env = serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "SessionStart",
            "additionalContext": ctx.trim_end(),
        }
    });
    println!("{env}");
}

const CONSOLIDATE_TASK_TITLE: &str = "Project conventions (consolidated)";

/// Manual consolidation: read this project's recurring decisions/constraints,
/// distil them into durable facts via one direct Haiku API call, and store the
/// facts as events in a per-project conventions task. Skips cleanly (no spend)
/// when ANTHROPIC_API_KEY is absent.
fn run_consolidate(max_facts: usize) -> anyhow::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"));
    if !events_path.exists() {
        anyhow::bail!("no events file at {events_path:?}");
    }
    let conn = tj_core::db::open(&state_path)?;
    tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;

    let sources = tj_core::db::high_signal_events(&conn, 200)?;
    if sources.is_empty() {
        println!("nothing to consolidate — no decisions/constraints/rejections recorded yet");
        return Ok(());
    }
    let texts: Vec<String> = sources.iter().map(|(_, t)| t.clone()).collect();
    let source_ids: Vec<String> = sources.iter().map(|(id, _)| id.clone()).collect();

    let (backend, facts) = match tj_core::consolidate::summarize(&texts, max_facts)? {
        Some(x) => x,
        None => {
            println!(
                "skipped: no consolidation backend. Either set ANTHROPIC_API_KEY \
(direct Haiku API, ~1c/run) or install Claude Code so `claude` is on PATH \
(uses your subscription login, no API key needed)."
            );
            return Ok(());
        }
    };
    eprintln!(
        "consolidating {} high-signal event(s) via {backend} …",
        texts.len()
    );
    if facts.is_empty() {
        println!("no durable facts found");
        return Ok(());
    }

    // Reuse the per-project conventions task, or create it.
    let task_id = match tj_core::db::find_task_by_title(&conn, CONSOLIDATE_TASK_TITLE)? {
        Some(id) => id,
        None => {
            let id = tj_core::new_task_id();
            let mut ev = tj_core::event::Event::new(
                id.clone(),
                tj_core::event::EventType::Open,
                tj_core::event::Author::User,
                tj_core::event::Source::Cli,
                CONSOLIDATE_TASK_TITLE.to_string(),
            );
            ev.meta = serde_json::json!({ "title": CONSOLIDATE_TASK_TITLE });
            let mut w = tj_core::storage::JsonlWriter::open(&events_path)?;
            w.append(&ev)?;
            w.flush_durable()?;
            tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
            id
        }
    };

    // De-dup against facts already stored in the conventions task.
    let existing: std::collections::HashSet<String> =
        tj_core::db::task_event_texts(&conn, &task_id)?
            .into_iter()
            .collect();

    let mut writer = tj_core::storage::JsonlWriter::open(&events_path)?;
    let mut written = 0usize;
    for f in &facts {
        if existing.contains(&f.text) {
            continue;
        }
        let mut ev = tj_core::event::Event::new(
            task_id.clone(),
            tj_core::event::EventType::Finding,
            tj_core::event::Author::Agent,
            tj_core::event::Source::Cli,
            f.text.clone(),
        );
        ev.meta = serde_json::json!({
            "memory_tier": f.tier,
            "consolidated": true,
            "derived_from": source_ids,
        });
        writer.append(&ev)?;
        written += 1;
    }
    writer.flush_durable()?;

    // Index the new facts and push them to the global recall index.
    tj_core::db::ingest_new_events(&conn, &events_path, &project_hash)?;
    let embedder = tj_core::embed::default_embedder();
    let now = chrono::Utc::now().to_rfc3339();
    tj_core::db::embed_pending(&conn, &project_hash, embedder.as_ref(), &now, 512)?;
    sync_global_memory(&conn, &project_hash);

    println!(
        "consolidated {written} new fact(s) into task {task_id} (\"{CONSOLIDATE_TASK_TITLE}\")"
    );
    Ok(())
}

fn auto_open_task_from_prompt(
    events_path: &std::path::Path,
    project_hash: &str,
    conn: &rusqlite::Connection,
    prompt: &str,
) -> anyhow::Result<Option<tj_core::classifier::TaskContext>> {
    // Title/goal must read like a human wrote them on purpose. When the
    // prompt is only machine noise — session-start scrollback
    // (`685] INFO: Mapped {…}`), a shell prompt, the journal's own resume
    // banner — `humanize_title` returns None and we decline to auto-open.
    // Better no task than a task labelled with a log line that then leaks
    // into the task list and the Claude Code session name.
    let Some(title) = tj_core::title::humanize_title(prompt) else {
        return Ok(None);
    };
    let goal: String = tj_core::title::humanize_goal(prompt, 200).unwrap_or_else(|| title.clone());

    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(Some(tj_core::classifier::TaskContext {
        task_id,
        title,
        last_events: vec![],
        constraints: 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"
/// Threshold for the v0.10.0 asyncRewake backlog signal. When the
/// PostToolUse hook (configured with `asyncRewake: true` in
/// `hooks.json`) finds more than this many entries already queued
/// in `pending/`, it exits with code 2 to wake the model with a
/// system reminder pointing at `task-journal pending-gc`. Tuned so
/// that normal load (<5 in-flight at any moment) never trips, but
/// a stuck classifier surfaces visibly before the queue grows into
/// the hundreds (the v0.6.2 fork-bomb era saw 515 entries before a
/// user noticed).
const PENDING_OVERFLOW_THRESHOLD: usize = 25;

/// Count `.json` (and `.json.dead`) entries currently sitting in
/// `pending/` next to `events_path`. Best-effort: any IO error
/// returns 0 so a borked filesystem never wakes the model with
/// noise. Used by the asyncRewake backlog signal.
fn count_pending_entries(events_path: &std::path::Path) -> anyhow::Result<usize> {
    let dir = events_path
        .parent()
        .and_then(|p| p.parent())
        .ok_or_else(|| anyhow::anyhow!("events_path has no grandparent"))?
        .join("pending");
    if !dir.exists() {
        return Ok(0);
    }
    let mut count = 0usize;
    for entry in std::fs::read_dir(&dir)? {
        let entry = entry?;
        let path = entry.path();
        if let Some("json") = path.extension().and_then(|e| e.to_str()) {
            count += 1;
        }
    }
    Ok(count)
}

/// 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,
    session_id: Option<&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 mut 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(),
    });
    if let Some(sid) = session_id {
        payload["session_id"] = serde_json::Value::String(sid.to_string());
    }
    let path = pending_dir.join(format!("{id}.json"));
    std::fs::write(&path, serde_json::to_string_pretty(&payload)?)?;
    Ok(path)
}

/// Transcript catch-up: parse the JSONL session log and enqueue user
/// and assistant text entries newer than `last_event_ts` as pending v2
/// chunks. The classify-worker picks them up afterwards. Returns the
/// number of chunks queued. Errors are absorbed — best-effort, never
/// fatal. Used by both PreCompact (before compaction) and Stop (end
/// of session) hooks to recover events the synchronous PostToolUse
/// hook didn't see (internal classifier calls, MCP responses with
/// thinking-only assistant turns, or the final assistant message
/// before a session ends).
///
/// `assistant_chunk_kind` tags assistant-side entries so the source
/// hook is visible in the pending queue (e.g. "PreCompactChunk"
/// vs "StopChunk"). User entries always tag as "UserPromptSubmit"
/// to trigger `process_pending_entry`'s auto-open behavior.
fn enqueue_transcript_chunks_since_last_event(
    transcript_path: &std::path::Path,
    events_path: &std::path::Path,
    project_hash: &str,
    backend: &str,
    last_event_ts: Option<&str>,
    assistant_chunk_kind: &str,
    session_id: Option<&str>,
) -> anyhow::Result<usize> {
    use tj_core::session::parser::{
        extract_assistant_texts, extract_user_text, parse_session, SessionEntry,
    };
    let parsed = match parse_session(transcript_path) {
        Ok(p) => p,
        Err(_) => return Ok(0),
    };
    let mut count = 0usize;
    for entry in &parsed.entries {
        let (ts, text, kind) = match entry {
            SessionEntry::User(u) => {
                let text = extract_user_text(u).unwrap_or_default();
                (u.timestamp.clone(), text, "UserPromptSubmit")
            }
            SessionEntry::Assistant(a) => {
                let texts = extract_assistant_texts(a);
                if texts.is_empty() {
                    continue;
                }
                (a.timestamp.clone(), texts.join("\n"), assistant_chunk_kind)
            }
            _ => continue,
        };
        if text.trim().len() < 20 {
            continue;
        }
        if let Some(last) = last_event_ts {
            if ts.as_str() <= last {
                continue;
            }
        }
        persist_pending_v2(events_path, kind, &text, project_hash, backend, session_id)?;
        count += 1;
    }
    Ok(count)
}

/// 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_core::classifier::agent_sdk::IN_CLASSIFIER_ENV);
    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();

    // Inherit the session id queued on the v2 chunk (additive; absent → None).
    let chunk_session_id = tj_core::session_id::session_id_from_payload(&v);

    // 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 Some(new_task) = auto_open_task_from_prompt(events_path, project_hash, &conn, &text)?
        else {
            // Prompt was only machine noise — drop the entry silently.
            std::fs::remove_file(path)?;
            return Ok(());
        };
        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 {
        "hybrid" | "" => Box::new(tj_core::classifier::hybrid::HybridClassifier::from_env()),
        "api" => Box::new(tj_core::classifier::http::AnthropicClassifier::from_env()?),
        "agent-sdk" => Box::new(
            tj_core::classifier::agent_sdk::ClaudeCliClassifier::from_env().ok_or_else(|| {
                anyhow::anyhow!(
                    "agent-sdk backend selected but no `claude` binary on PATH — \
                     install Claude Code (https://claude.com/claude-code) or pick another --backend"
                )
            })?,
        ),
        "heuristic" => {
            use tj_core::classifier::heuristic::try_heuristic;
            use tj_core::classifier::{ClassifyInput, ClassifyOutput};
            struct HeuristicOnly;
            impl Classifier for HeuristicOnly {
                fn classify(&self, input: &ClassifyInput) -> anyhow::Result<ClassifyOutput> {
                    try_heuristic(input).ok_or_else(|| {
                        anyhow::anyhow!(
                            "heuristic uncertain (heuristic-only mode has no LLM fallback)"
                        )
                    })
                }
            }
            Box::new(HeuristicOnly)
        }
        other => anyhow::bail!(
            "unknown backend: {other} (expected `hybrid`, `agent-sdk`, `api`, or `heuristic`)"
        ),
    };
    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;
    tj_core::session_id::stamp_session_id(&mut event.meta, chunk_session_id.as_deref());

    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.
/// Build a PostToolUse `updatedMCPToolOutput` envelope when an MCP tool call
/// echoes a prior rejection/decision (claude-memory-7km). Returns None
/// (pass through, emit nothing) for non-MCP tools, no hits, or any error.
/// Never panics, never mutates the journal.
///
/// Dedup vs claude-memory-60m: this fires ONLY for `mcp__` tools; 60m's
/// `additionalContext` path skips those. The two are mutually exclusive by
/// tool type so a single recall is never double-surfaced.
fn push_recall_envelope(
    payload: &serde_json::Value,
    events_path: &std::path::Path,
    project_hash: &str,
) -> Option<serde_json::Value> {
    // MCP-only gate: Claude Code prefixes MCP tools `mcp__<server>__<tool>`.
    let tool_name = payload.get("tool_name").and_then(|v| v.as_str())?;
    if !tool_name.starts_with("mcp__") {
        return None;
    }
    if !events_path.exists() {
        return None;
    }
    let query_text = payload
        .get("tool_input")
        .map(|v| v.to_string())
        .unwrap_or_default();
    if query_text.trim().is_empty() {
        return None;
    }
    let original = payload
        .get("tool_response")
        .map(render_tool_response)
        .unwrap_or_default();

    let state_path = tj_core::paths::state_dir()
        .ok()?
        .join(format!("{project_hash}.sqlite"));
    let conn = tj_core::db::open(&state_path).ok()?;
    let _ = tj_core::db::ingest_new_events(&conn, events_path, project_hash);
    // Reuse 60m's recall engine + threshold — no recall logic lives here.
    let hits =
        tj_core::recall::relevant_recall(&conn, &query_text, tj_core::recall::DEFAULT_MAX_HITS)
            .ok()?;
    if hits.is_empty() {
        return None;
    }
    let updated = format!("{}\n\n{}", render_recall_banner(&hits), original);
    Some(serde_json::json!({
        "hookSpecificOutput": {
            "hookEventName": "PostToolUse",
            "updatedMCPToolOutput": updated,
        }
    }))
}

/// One âš  line per recall hit (mirrors the close-gate / SessionStart convention).
fn render_recall_banner(hits: &[tj_core::recall::RecallHit]) -> String {
    let mut s = String::from("\u{26a0} Task Journal recall — you may be repeating a prior path:");
    for h in hits {
        let verb = match h.event_type {
            tj_core::event::EventType::Rejection => "rejected",
            _ => "decided on",
        };
        s.push_str(&format!(
            "\n  \u{26a0} in task {} you previously {} this: {}",
            h.task_id, verb, h.text
        ));
    }
    s
}

/// Collapse a `tool_response` JSON value to the text Claude would have seen.
/// A bare string is used as-is; any other JSON is stringified (mirrors how
/// `parse_hook_stdin` stringifies `tool_response`).
fn render_tool_response(v: &serde_json::Value) -> String {
    match v {
        serde_json::Value::String(s) => s.clone(),
        other => other.to_string(),
    }
}

fn parse_hook_stdin() -> anyhow::Result<(String, String, serde_json::Value)> {
    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(), serde_json::Value::Null));
    }
    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, v))
}

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}"),
    })
}

/// Flatten a parsed session transcript into role-tagged turns, in order.
fn flatten_transcript(parsed: &tj_core::session::parser::ParsedSession) -> String {
    use tj_core::session::parser::{extract_assistant_texts, extract_user_text, SessionEntry};
    let mut s = String::new();
    for entry in &parsed.entries {
        match entry {
            SessionEntry::User(u) => {
                if let Some(text) = extract_user_text(u) {
                    s.push_str("user: ");
                    s.push_str(&text);
                    s.push('\n');
                }
            }
            SessionEntry::Assistant(a) => {
                for text in extract_assistant_texts(a) {
                    s.push_str("assistant: ");
                    s.push_str(&text);
                    s.push('\n');
                }
            }
            _ => {}
        }
    }
    s
}

/// True when any of `events` ties this task to the session: precise match
/// on `meta.session_id`, or (for legacy events with no session_id) a
/// timestamp falling inside the session's `[first_ts, last_ts]` window.
fn task_matches_session(
    events: &[tj_core::event::Event],
    session_id: &str,
    first_ts: Option<&str>,
    last_ts: Option<&str>,
) -> bool {
    events.iter().any(|e| {
        // Precise: event tagged with this session.
        if e.meta.get("session_id").and_then(|v| v.as_str()) == Some(session_id) {
            return true;
        }
        // Legacy fallback: timestamp inside the session window.
        if e.meta.get("session_id").is_none() {
            if let (Some(f), Some(l)) = (first_ts, last_ts) {
                return e.timestamp.as_str() >= f && e.timestamp.as_str() <= l;
            }
        }
        false
    })
}

/// Read the project's events from `events_path`, group by `task_id`, and
/// return candidate task contexts for sessions whose events match this
/// session (precise session_id, or legacy time-window). Each context
/// carries the task title and up to the last ~20 event texts (dedup
/// context for the backend).
fn candidate_tasks_for_session(
    events_path: &std::path::Path,
    session_id: &str,
    first_ts: Option<&str>,
    last_ts: Option<&str>,
) -> anyhow::Result<Vec<tj_core::dream::backend::BackfillTaskContext>> {
    use std::collections::BTreeMap;
    use tj_core::dream::backend::BackfillTaskContext;
    use tj_core::event::{Event, EventType};

    if !events_path.exists() {
        return Ok(Vec::new());
    }
    let body = std::fs::read_to_string(events_path)?;
    let mut by_task: BTreeMap<String, Vec<Event>> = BTreeMap::new();
    for line in body.lines() {
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(e) = serde_json::from_str::<Event>(line) {
            by_task.entry(e.task_id.clone()).or_default().push(e);
        }
    }

    let mut out = Vec::new();
    for (task_id, events) in by_task {
        if !task_matches_session(&events, session_id, first_ts, last_ts) {
            continue;
        }
        // Title from the Open event when present, else the first event's text.
        let title = events
            .iter()
            .find(|e| e.event_type == EventType::Open)
            .or_else(|| events.first())
            .map(|e| e.text.clone())
            .unwrap_or_default();
        let existing_events: Vec<String> = events
            .iter()
            .rev()
            .take(20)
            .rev()
            .map(|e| e.text.clone())
            .collect();
        out.push(BackfillTaskContext {
            task_id,
            title,
            existing_events,
        });
    }
    Ok(out)
}

/// Assemble per-session `(session_id, BackfillInput)` from the in-scope
/// session transcripts and the project's existing events.
fn build_dream_inputs(
    events_path: &std::path::Path,
    sessions: &[std::path::PathBuf],
    task_filter: Option<&str>,
) -> anyhow::Result<Vec<(String, tj_core::dream::backend::BackfillInput)>> {
    use tj_core::dream::backend::BackfillInput;
    use tj_core::session::parser::parse_session;

    let mut out = Vec::new();
    for path in sessions {
        let session_id = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("")
            .to_string();
        let parsed = parse_session(path)?;

        let candidates = candidate_tasks_for_session(
            events_path,
            &session_id,
            parsed.first_timestamp.as_deref(),
            parsed.last_timestamp.as_deref(),
        )?;
        let tasks: Vec<_> = candidates
            .into_iter()
            .filter(|t| task_filter.is_none_or(|f| f == t.task_id))
            .collect();
        if tasks.is_empty() {
            continue;
        }

        let transcript = flatten_transcript(&parsed);
        out.push((session_id, BackfillInput { tasks, transcript }));
    }
    Ok(out)
}

#[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 flatten_transcript_tags_roles_in_order() {
        use tj_core::session::parser::parse_session;
        let dir = tempfile::tempdir().unwrap();
        let p = dir.path().join("sess-1.jsonl");
        std::fs::write(&p,
            "{\"type\":\"user\",\"uuid\":\"u1\",\"timestamp\":\"2026-01-01T00:00:00Z\",\"message\":{\"content\":\"why?\"}}\n\
             {\"type\":\"assistant\",\"uuid\":\"a1\",\"timestamp\":\"2026-01-01T00:00:01Z\",\"message\":{\"content\":[{\"type\":\"text\",\"text\":\"because X\"}]}}\n").unwrap();
        let parsed = parse_session(&p).unwrap();
        let t = flatten_transcript(&parsed);
        let u = t.find("why?").unwrap();
        let a = t.find("because X").unwrap();
        assert!(u < a, "user turn should precede assistant turn");
    }

    #[test]
    fn task_matches_by_session_id_or_time_window() {
        use tj_core::event::{Author, Event, EventType, Source};
        let mut tagged = Event::new(
            "tj-1",
            EventType::Finding,
            Author::Agent,
            Source::Hook,
            "x".into(),
        );
        tagged.meta = serde_json::json!({"session_id": "sess-1"});
        assert!(task_matches_session(&[tagged], "sess-1", None, None));

        let mut legacy = Event::new(
            "tj-2",
            EventType::Finding,
            Author::Agent,
            Source::Hook,
            "y".into(),
        );
        legacy.timestamp = "2026-01-01T00:00:30Z".into();
        legacy.meta = serde_json::json!({}); // no session_id
        assert!(task_matches_session(
            &[legacy.clone()],
            "sess-1",
            Some("2026-01-01T00:00:00Z"),
            Some("2026-01-01T00:01:00Z"),
        ));
        // Outside the window and no session id → no match.
        assert!(!task_matches_session(
            &[legacy],
            "sess-1",
            Some("2026-02-01T00:00:00Z"),
            Some("2026-02-01T00:01:00Z"),
        ));
    }

    #[test]
    fn persist_pending_v2_includes_session_id_when_present() {
        let dir = tempfile::tempdir().unwrap();
        let events_path = dir.path().join("events").join("h.jsonl");
        std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();
        let p = persist_pending_v2(
            &events_path,
            "PostToolUse",
            "txt",
            "h",
            "hybrid",
            Some("sess-9"),
        )
        .unwrap();
        let body = std::fs::read_to_string(&p).unwrap();
        let v: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(v["session_id"], serde_json::json!("sess-9"));
        assert_eq!(
            tj_core::session_id::session_id_from_payload(&v).as_deref(),
            Some("sess-9")
        );
    }

    #[test]
    fn persist_pending_v2_omits_session_id_when_none() {
        let dir = tempfile::tempdir().unwrap();
        let events_path = dir.path().join("events").join("h.jsonl");
        std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();
        let p =
            persist_pending_v2(&events_path, "PostToolUse", "txt", "h", "hybrid", None).unwrap();
        let body = std::fs::read_to_string(&p).unwrap();
        let v: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert!(v.get("session_id").is_none());
    }

    #[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 recent_task_contexts_gathers_constraints() {
        use tj_core::event::{Author, Event, EventType, Source};
        let dir = tempfile::tempdir().unwrap();
        let events_path = dir.path().join("events").join("h.jsonl");
        std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();
        let state_path = dir.path().join("h.sqlite");
        let project_hash = "h";

        let mut writer = tj_core::storage::JsonlWriter::open(&events_path).unwrap();
        let mut open = Event::new(
            "tj-1",
            EventType::Open,
            Author::User,
            Source::Cli,
            "task one".into(),
        );
        open.meta = serde_json::json!({ "title": "task one" });
        open.timestamp = "2026-01-01T00:00:00Z".into();
        writer.append(&open).unwrap();
        let mut cons = Event::new(
            "tj-1",
            EventType::Constraint,
            Author::Agent,
            Source::Hook,
            "API limit 100/min".into(),
        );
        cons.timestamp = "2026-01-01T00:00:01Z".into();
        writer.append(&cons).unwrap();
        let mut find = Event::new(
            "tj-1",
            EventType::Finding,
            Author::Agent,
            Source::Hook,
            "read http.rs".into(),
        );
        find.timestamp = "2026-01-01T00:00:02Z".into();
        writer.append(&find).unwrap();
        writer.flush_durable().unwrap();

        let conn = tj_core::db::open(&state_path).unwrap();
        tj_core::db::ingest_new_events(&conn, &events_path, project_hash).unwrap();

        let ctxs = recent_task_contexts(&conn, 5).unwrap();
        let ctx = ctxs.iter().find(|c| c.task_id == "tj-1").unwrap();
        assert!(
            ctx.constraints
                .iter()
                .any(|s| s.contains("API limit 100/min")),
            "constraints should include the constraint event, got {:?}",
            ctx.constraints
        );
        assert!(
            !ctx.constraints.iter().any(|s| s.contains("read http.rs")),
            "constraints must exclude non-constraint events, got {:?}",
            ctx.constraints
        );
    }

    #[test]
    fn recent_task_contexts_bounds_constraints_to_n() {
        use tj_core::event::{Author, Event, EventType, Source};
        let dir = tempfile::tempdir().unwrap();
        let events_path = dir.path().join("events").join("h.jsonl");
        std::fs::create_dir_all(events_path.parent().unwrap()).unwrap();
        let state_path = dir.path().join("h.sqlite");
        let project_hash = "h";

        let mut writer = tj_core::storage::JsonlWriter::open(&events_path).unwrap();
        let mut open = Event::new(
            "tj-1",
            EventType::Open,
            Author::User,
            Source::Cli,
            "task one".into(),
        );
        open.meta = serde_json::json!({ "title": "task one" });
        open.timestamp = "2026-01-01T00:00:00Z".into();
        writer.append(&open).unwrap();
        for i in 0..7 {
            let mut cons = Event::new(
                "tj-1",
                EventType::Constraint,
                Author::Agent,
                Source::Hook,
                format!("constraint number {i}"),
            );
            // Increasing timestamps so DESC ordering keeps the most recent.
            cons.timestamp = format!("2026-01-01T00:00:1{i}Z");
            writer.append(&cons).unwrap();
        }
        writer.flush_durable().unwrap();

        let conn = tj_core::db::open(&state_path).unwrap();
        tj_core::db::ingest_new_events(&conn, &events_path, project_hash).unwrap();

        let ctxs = recent_task_contexts(&conn, 5).unwrap();
        let ctx = ctxs.iter().find(|c| c.task_id == "tj-1").unwrap();
        assert_eq!(
            ctx.constraints.len(),
            5,
            "bounded to CONSTRAINT_CONTEXT_LIMIT"
        );
        // The 5 most recent are numbers 2..=6.
        assert!(ctx
            .constraints
            .iter()
            .any(|s| s.contains("constraint number 6")));
        assert!(!ctx
            .constraints
            .iter()
            .any(|s| s.contains("constraint number 0")));
        assert!(!ctx
            .constraints
            .iter()
            .any(|s| s.contains("constraint number 1")));
    }

    #[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"));
    }
}