hh-core 1.0.0

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

use crate::blob::BlobStore;
use crate::event::{truncate_summary, AdapterStatus, AgentKind, Event, EventKind};
use std::io::BufRead;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

/// Payloads at or above this size (in bytes) spill to the blob store rather
/// than being stored inline in `events.body_json` (SRS §4.1, matching the
/// recorder's terminal-chunk threshold).
const SPILLOVER_BYTES: usize = 256 * 1024;
/// Tail poll interval when the transcript is at EOF but the session continues.
const TAIL_POLL: Duration = Duration::from_millis(50);
/// Poll interval while waiting for the transcript file to appear.
const APPEAR_POLL: Duration = Duration::from_millis(200);

/// Context handed to an adapter when it is spawned.
#[derive(Clone)]
pub struct AdapterContext {
    /// Owning session id (full UUID string).
    pub session_id: String,
    /// Session start as a unix-ms UTC timestamp; `ts_ms` is relative to this.
    pub started_at_unix_ms: i64,
    /// Session working directory — used to locate/verify the structured log.
    pub cwd: PathBuf,
    /// Full command argv (used for detection and the fallback scan).
    pub command: Vec<String>,
    /// Blob store for >256 KiB spillover.
    pub blobs: std::sync::Arc<BlobStore>,
    /// Stop flag: set by the recorder when the child has exited.
    pub stop: std::sync::Arc<AtomicBool>,
    /// Override for the Claude projects directory (`None` → resolve from `HOME`).
    /// Tests set this to a temp dir so the adapter never touches the real home and
    /// avoids `HOME` env races across parallel tests; production passes `None`.
    pub projects_dir: Option<PathBuf>,
}

/// A handle to a running adapter tailer. Drop the `events` receiver (or drain
/// it to EOF) and [`AdapterHandle::join`] the outcome when the session ends.
pub struct AdapterHandle {
    /// The stream of parsed events, in arrival order. EOF when the tailer exits.
    pub events: mpsc::Receiver<Event>,
    /// Joins the tailer thread and returns the adapter's final outcome.
    pub outcome: JoinHandle<AdapterOutcome>,
}

impl AdapterHandle {
    /// Block until the tailer thread exits and return its outcome. The tailer
    /// is total (never panics on record content), so a panic here indicates an
    /// internal bug, surfaced as [`crate::Error::Storage`] for the binary to
    /// attach `anyhow` context.
    pub fn join(self) -> crate::Result<AdapterOutcome> {
        self.outcome.join().map_err(|_| {
            crate::Error::Storage(crate::error::StorageError::Open {
                // The exact path is irrelevant for an adapter-thread panic; reuse
                // the storage error surface so the binary's print_error renders it.
                path: PathBuf::new(),
                source: std::io::Error::other("adapter thread panicked"),
            })
        })
    }
}

/// The final outcome of an adapter run, reported when its tailer thread exits.
#[derive(Debug, Default, Clone)]
pub struct AdapterOutcome {
    /// Model name extracted from the structured stream, if any (last-seen wins).
    pub model: Option<String>,
    /// Token-usage JSON, verbatim from the last assistant record that carried it
    /// (rich fields preserved; not cumulative). Written to `sessions.usage_json`.
    pub usage_json: Option<serde_json::Value>,
    /// Final adapter status: [`AdapterStatus::Active`] if a transcript was
    /// tailed, [`AdapterStatus::Degraded`] if it could not be located.
    pub status: AdapterStatus,
    /// When `status` is [`AdapterStatus::Degraded`], a single actionable line the
    /// recorder prints to stderr *after the child exits* (once the terminal is
    /// restored), instead of from the tailer thread mid-session — so the warning
    /// is not buried under the agent's alternate-screen TUI (FR-1.5).
    pub degrade_reason: Option<String>,
}

/// An agent adapter: tail a structured event stream and yield [`Event`]s.
///
/// Implementations are `Send + 'static` so the recorder can spawn the tailer on
/// its own thread. [`Adapter::spawn`] performs any setup that can fail (e.g. the
/// tailer thread spawn) and returns an `io::Error` only for that low-level
/// failure; higher-level "no transcript found" conditions are reported via the
/// returned handle's [`AdapterOutcome::status`] (degraded), not as an error, so
/// the recorder can keep recording PTY/FS output (FR-1.5).
pub trait Adapter: Send + 'static {
    /// The agent kind this adapter reports for the session row.
    fn agent_kind(&self) -> AgentKind;
    /// Spawn the tailer thread, returning the event stream + outcome handle.
    ///
    /// Takes `self: Box<Self>` so the recorder can dispatch through the
    /// `Box<dyn Adapter>` returned by [`select`] (a by-value `self` would not
    /// be callable on a trait object). A stateless adapter like [`ClaudeAdapter`]
    /// ignores the receiver.
    fn spawn(self: Box<Self>, ctx: AdapterContext) -> std::io::Result<AdapterHandle>;
}

/// Detect which adapter applies to `command` (FR-1.5). Returns `None` for a
/// generic agent (PTY-only capture). Detection order: Claude Code, Claude
/// Desktop, Codex CLI, Gemini CLI — by the basename of `command[0]`. A forced
/// adapter from `hh run --adapter` is resolved by the recorder, not here.
#[must_use]
pub fn select(command: &[String], _cwd: &Path) -> Option<Box<dyn Adapter>> {
    if is_claude_code(command) {
        Some(Box::new(ClaudeAdapter))
    } else if is_claude_desktop(command) {
        Some(Box::new(ClaudeDesktopAdapter))
    } else if is_codex_cli(command) {
        Some(Box::new(CodexAdapter))
    } else if is_gemini_cli(command) {
        Some(Box::new(GeminiAdapter))
    } else {
        None
    }
}

/// Resolve a forced adapter name (from `hh run --adapter <name>`) to an
/// adapter, or `None` if the name is unrecognized — the recorder surfaces that
/// as an actionable error. Keeping this map in `hh-core` (not the recorder)
/// means adding a forced adapter is a one-branch change here, with no
/// `hh-record` edit (the trait's extensibility goal).
#[must_use]
pub fn resolve_override(name: &str) -> Option<Box<dyn Adapter>> {
    match name {
        "claude-code" => Some(Box::new(ClaudeAdapter)),
        "claude-desktop" => Some(Box::new(ClaudeDesktopAdapter)),
        "codex-cli" => Some(Box::new(CodexAdapter)),
        "gemini-cli" => Some(Box::new(GeminiAdapter)),
        _ => None,
    }
}

/// True if the command's program basename is `claude` (stripping a Windows
/// `.exe`). Mirrors the detection in `hh-record::agent::detect_agent`.
#[must_use]
pub fn is_claude_code(command: &[String]) -> bool {
    let prog = command.first().map_or("", String::as_str);
    // Split on both `/` and `\` so a Windows path like `C:\Apps\claude.exe` yields
    // `claude.exe` on any platform — `Path::file_name` treats `\` as a normal
    // character on Unix, which would mis-basename Windows command lines.
    let base = prog.rsplit(['/', '\\']).next().unwrap_or(prog);
    let base = base.strip_suffix(".exe").unwrap_or(base);
    base.eq_ignore_ascii_case("claude")
}

/// True if the command's program basename is `claude-desktop` (stripping a
/// Windows `.exe`). Claude Desktop uses the same JSONL session format as Claude
/// Code, so the adapter reuses the same tailer.
#[must_use]
pub fn is_claude_desktop(command: &[String]) -> bool {
    let prog = command.first().map_or("", String::as_str);
    let base = prog.rsplit(['/', '\\']).next().unwrap_or(prog);
    let base = base.strip_suffix(".exe").unwrap_or(base);
    base.eq_ignore_ascii_case("claude-desktop")
}

/// True if the command's program basename is `codex` (stripping a Windows
/// `.exe`). Mirrors the detection in `hh-record::agent::detect_agent`.
#[must_use]
pub fn is_codex_cli(command: &[String]) -> bool {
    let prog = command.first().map_or("", String::as_str);
    let base = prog.rsplit(['/', '\\']).next().unwrap_or(prog);
    let base = base.strip_suffix(".exe").unwrap_or(base);
    base.eq_ignore_ascii_case("codex")
}

/// True if the command's program basename is `gemini` (stripping a Windows
/// `.exe`). Mirrors the detection in `hh-record::agent::detect_agent`.
#[must_use]
pub fn is_gemini_cli(command: &[String]) -> bool {
    let prog = command.first().map_or("", String::as_str);
    let base = prog.rsplit(['/', '\\']).next().unwrap_or(prog);
    let base = base.strip_suffix(".exe").unwrap_or(base);
    base.eq_ignore_ascii_case("gemini")
}

// ---------------------------------------------------------------------------
// Claude Code adapter
// ---------------------------------------------------------------------------

/// The Claude Code adapter: tails `~/.claude/projects/<slug>/*.jsonl` and
/// converts records to `user_message` / `agent_message` / `thinking` /
/// `tool_call` / `tool_result` events. Stateless; the tailer thread holds all
/// mutable state. A unit struct (rather than `struct ClaudeAdapter {}`) so it
/// is constructible as a value without a `{}`; reserved for future per-adapter
/// knobs (e.g. a forced projects dir) by adding fields + a `Default` impl.
#[derive(Debug, Clone)]
pub struct ClaudeAdapter;

impl Adapter for ClaudeAdapter {
    fn agent_kind(&self) -> AgentKind {
        AgentKind::ClaudeCode
    }

    #[allow(clippy::unused_self)] // ClaudeAdapter is stateless; the `Box<Self>` receiver exists only so the recorder can dispatch through `Box<dyn Adapter>` (FR-1.5). A future stateful adapter would read its config from `self` here.
    fn spawn(self: Box<Self>, ctx: AdapterContext) -> std::io::Result<AdapterHandle> {
        let (tx, rx) = mpsc::channel::<Event>();
        let outcome = std::thread::Builder::new()
            .name("hh-claude-adapter".into())
            .spawn(move || run_claude_tailer(ctx, tx))?;
        Ok(AdapterHandle {
            events: rx,
            outcome,
        })
    }
}

/// The tailer thread body: locate the transcript, then read it to EOF/stop,
/// parsing each line into events sent on `tx`. Returns the final outcome.
///
/// Degrade paths set [`AdapterOutcome::degrade_reason`] rather than printing
/// mid-session, so the recorder can surface the warning *after* the child exits
/// and the terminal is restored (FR-1.5) — printing from this thread while the
/// agent's TUI owns the alternate screen is invisible to the user.
#[allow(clippy::needless_pass_by_value)] // ctx/tx are owned for the thread's lifetime; taking them by value keeps the tailer self-contained (mirrors runner::run_reader).
fn run_claude_tailer(ctx: AdapterContext, tx: mpsc::Sender<Event>) -> AdapterOutcome {
    let Some(projects) = ctx.projects_dir.clone().or_else(claude_projects_dir) else {
        return degraded(
            "no ~/.claude/projects directory found (HOME unset?); run `hh doctor` to diagnose",
        );
    };
    if !projects.is_dir() {
        return degraded(format!(
            "projects directory does not exist: {}; run `hh doctor` to diagnose",
            projects.display()
        ));
    }
    let slug = slugify(&ctx.cwd);
    let slug_dir = projects.join(&slug);
    debug(&format!(
        "claude adapter: projects_dir={}, slug={slug}, slug_dir={}, session cwd={}, started_at_unix_ms={}",
        projects.display(),
        slug_dir.display(),
        ctx.cwd.display(),
        ctx.started_at_unix_ms
    ));
    let mut diag = DiscoveryDiag {
        projects: Some(projects.clone()),
        slug: Some(slug.clone()),
        slug_dir: Some(slug_dir.clone()),
        cwd: Some(ctx.cwd.clone()),
        ..Default::default()
    };
    let start = Instant::now();
    let Some(file) = locate_transcript(&projects, &ctx.cwd, &ctx.stop, &mut diag) else {
        debug(&format!(
            "claude adapter: discovery failed: new_candidates={}, cwd_mismatches={}, directories={}",
            diag.new_candidates.len(),
            diag.cwd_mismatches.len(),
            diag.directories.len()
        ));
        return degraded(locate_failure_reason(&diag));
    };
    debug(&format!(
        "claude adapter: selected transcript {} (cwd matched)",
        file.display()
    ));
    let mut acc = OutcomeAcc::default();
    let stats = tail_file(&file, &projects, &ctx, &tx, &start, &mut acc);
    if !stats.read_ok {
        return degraded(format!(
            "found a transcript at {} but could not read it (open/read failed); \
             run `hh doctor` to check file permissions",
            file.display(),
        ));
    }
    debug(&format!(
        "claude adapter: tail done: lines_seen={}, records_parsed={}, events_produced={}, first_parse_error={:?}",
        stats.lines_seen, stats.records_parsed, stats.events_produced, stats.first_parse_error
    ));
    if stats.events_produced == 0 {
        // Found and read a transcript, but no user/assistant records converted
        // to events. Distinct from "could not locate" — the file existed but
        // yielded nothing. Most common cause: a format drift the parser no
        // longer recognizes, so surface the first parse failure (if any) and the
        // line count to make this a one-line diagnosis instead of a silent
        // "active, 0 steps".
        let first_err = stats
            .first_parse_error
            .map(|(n, msg)| format!("; first parse error at line {n}: {msg}"))
            .unwrap_or_default();
        return degraded(format!(
            "jsonl found ({}) but 0 records parsed (read {} line(s){first_err}); \
             run `hh doctor` to check the Claude Code transcript format",
            file.display(),
            stats.lines_seen,
        ));
    }
    acc.finish(AdapterStatus::Active)
}

/// Build a [`Degraded`](AdapterStatus::Degraded) outcome carrying a one-line
/// reason for the recorder to print after the child exits.
fn degraded(reason: impl Into<String>) -> AdapterOutcome {
    AdapterOutcome {
        status: AdapterStatus::Degraded,
        degrade_reason: Some(reason.into()),
        ..Default::default()
    }
}

/// Accumulated discovery diagnostics: what the tailer saw while polling for a
/// transcript. Used to (a) emit an `HH_DEBUG` trace and (b) build a *specific*
/// degrade reason when no transcript qualifies — so a degraded session
/// self-documents "no new file appeared" vs "N candidates appeared but none
/// matched cwd" vs "a candidate was a directory", instead of a bare "could not
/// locate". Pure data; the tailer mutates it as it polls.
#[derive(Default)]
struct DiscoveryDiag {
    /// Resolved projects dir (`~/.claude/projects` or the test override).
    projects: Option<PathBuf>,
    /// The slug computed from the session cwd (e.g. `-home-saadman-halfhand`).
    slug: Option<String>,
    /// `projects/<slug>` — the primary lookup dir.
    slug_dir: Option<PathBuf>,
    /// Session cwd, for the reason string.
    cwd: Option<PathBuf>,
    /// Distinct NEW `*.jsonl` files ever observed (across all polls). Empty →
    /// no transcript appeared at all; non-empty → appeared but none qualified.
    new_candidates: std::collections::HashSet<PathBuf>,
    /// Candidates rejected because their first cwd-bearing record named a
    /// different cwd (a concurrent session in the same project dir).
    cwd_mismatches: Vec<PathBuf>,
    /// Candidates that were a directory, not a file (the same-stem-dir guard).
    directories: Vec<PathBuf>,
}

/// Statistics from tailing one transcript, used to build a specific degrade
/// reason when a file was found and read but produced no events. Pure data;
/// [`tail_file`] / [`parse_and_send`] mutate it as they read.
#[derive(Default)]
struct TailStats {
    /// `false` if the transcript could not be opened at all.
    read_ok: bool,
    /// Non-empty lines seen (complete records + unparseable lines).
    lines_seen: usize,
    /// Lines that parsed as a JSON object (the "records read" count).
    records_parsed: usize,
    /// Total events emitted to the drain channel.
    events_produced: usize,
    /// The first line that failed JSON parsing, as `(1-based line number, msg)`.
    /// `None` if every line parsed (or no lines were seen).
    first_parse_error: Option<(usize, String)>,
}

/// Build a specific degrade reason from a failed discovery. Distinguishes "no
/// new transcript appeared" (lazy creation + empty session) from "candidates
/// appeared but none matched cwd" (concurrent-session / slug drift), and calls
/// out any directory candidates (the same-stem-dir issue).
fn locate_failure_reason(diag: &DiscoveryDiag) -> String {
    use std::fmt::Write as _;
    let slug = diag.slug.as_deref().unwrap_or("?");
    let projects = diag
        .projects
        .as_ref()
        .map_or_else(|| "(unknown)".to_string(), |p| p.display().to_string());
    let cwd = diag
        .cwd
        .as_ref()
        .map_or_else(|| "(unknown)".to_string(), |p| p.display().to_string());
    let slug_dir = diag
        .slug_dir
        .as_ref()
        .map_or_else(|| "(unknown)".to_string(), |p| p.display().to_string());
    if diag.new_candidates.is_empty() {
        format!(
            "no jsonl matched cwd slug {slug}: no new transcript appeared under {projects} \
             (looked in {slug_dir}; cwd={cwd}) before the session ended; Claude creates it \
             lazily on first output — if you sent no prompt this is expected. \
             Run `hh doctor` to verify discoverability."
        )
    } else {
        let mut s = format!(
            "no jsonl matched cwd slug {slug}: {} new candidate(s) appeared under {projects} \
             but none carried cwd={cwd} before the session ended",
            diag.new_candidates.len(),
        );
        if !diag.cwd_mismatches.is_empty() {
            let names: Vec<String> = diag
                .cwd_mismatches
                .iter()
                .take(3)
                .map(|p| {
                    p.file_name()
                        .map(|f| f.to_string_lossy().to_string())
                        .unwrap_or_default()
                })
                .collect();
            let _ = write!(
                s,
                "; {} rejected for a different cwd ({})",
                diag.cwd_mismatches.len(),
                names.join(", ")
            );
        }
        if !diag.directories.is_empty() {
            let _ = write!(
                s,
                "; {} candidate(s) were directories, not files",
                diag.directories.len()
            );
        }
        s.push_str(". Run `hh doctor` to diagnose.");
        s
    }
}

/// Accumulates model/usage across assistant records while tailing.
#[derive(Default)]
struct OutcomeAcc {
    model: Option<String>,
    usage_json: Option<serde_json::Value>,
}

impl OutcomeAcc {
    fn note_assistant(&mut self, message: &serde_json::Value) {
        if let Some(m) = message.get("model").and_then(|v| v.as_str()) {
            self.model = Some(m.to_string());
        }
        if let Some(u) = message.get("usage") {
            self.usage_json = Some(u.clone());
        }
    }

    fn finish(self, status: AdapterStatus) -> AdapterOutcome {
        AdapterOutcome {
            model: self.model,
            usage_json: self.usage_json,
            status,
            degrade_reason: None,
        }
    }
}

/// Locate the transcript file for this session.
///
/// Selection rule (fixes two real-world failures):
/// - **Poll until the stop flag is set**, not for a fixed 3 s deadline. Claude
///   Code creates its transcript *lazily* on the first user message, often well
///   after `hh run` launches the child; a fixed timeout degraded every
///   short-prompt session that took >3 s to send its first message (the
///   "0 steps, status=ok" symptom).
/// - **Prefer a transcript that is NEW since session start**, identified by
///   snapshotting every `*.jsonl` under `projects` at entry. Claude names each
///   invocation's transcript by a fresh uuid, so the file for *this* session did
///   not exist when `hh` started; matching only new files avoids latching onto a
///   concurrent session's transcript in the same project dir (the
///   "active but tailing the wrong session" symptom). Set-based, not mtime-based,
///   so clock skew cannot fool it.
/// - **Verify by cwd**: a candidate qualifies only once a record carrying `cwd`
///   appears and that cwd equals (or is under) the session cwd. Early Claude
///   records (`agent-setting`/`mode`/`file-history-snapshot`) carry no `cwd`, so
///   a freshly-created file is polled until its first cwd-bearing record lands.
///
/// Returns `None` if nothing qualifies before the stop flag is set (the recorder
/// then surfaces a degraded outcome with an actionable reason).
fn locate_transcript(
    projects: &Path,
    cwd: &Path,
    stop: &std::sync::Arc<AtomicBool>,
    diag: &mut DiscoveryDiag,
) -> Option<PathBuf> {
    let slug_dir = projects.join(slugify(cwd));
    let preexisting = snapshot_all_jsonl(projects);
    // Candidates confirmed to belong to a *different* cwd (cwd present but not
    // ours) — never re-checked. Files with no cwd yet are re-polled (they grow).
    let mut rejected: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();

    loop {
        if stop.load(Ordering::Acquire) {
            return None;
        }
        // Primary: a NEW transcript in the expected slug dir whose cwd matches.
        if slug_dir.is_dir() {
            for f in new_jsonl_in(&slug_dir, &preexisting) {
                if rejected.contains(&f) {
                    continue;
                }
                diag.new_candidates.insert(f.clone());
                match first_record_cwd_state(&f, cwd) {
                    CwdState::Matches => return Some(f),
                    CwdState::Different => {
                        diag.cwd_mismatches.push(f.clone());
                        rejected.insert(f);
                    }
                    CwdState::Directory => {
                        diag.directories.push(f.clone());
                        rejected.insert(f);
                    }
                    CwdState::None => {} // not yet written; keep polling
                }
            }
        }
        // Fallback: slug encoding may differ from Claude's; scan every project dir
        // for a NEW transcript matching cwd. Cheap in practice — new files appear
        // only when a session starts, and rejected/non-matching ones are cached.
        for f in new_jsonl_under(projects, &preexisting) {
            if rejected.contains(&f) {
                continue;
            }
            diag.new_candidates.insert(f.clone());
            match first_record_cwd_state(&f, cwd) {
                CwdState::Matches => return Some(f),
                CwdState::Different => {
                    diag.cwd_mismatches.push(f.clone());
                    rejected.insert(f);
                }
                CwdState::Directory => {
                    diag.directories.push(f.clone());
                    rejected.insert(f);
                }
                CwdState::None => {}
            }
        }
        std::thread::sleep(APPEAR_POLL);
    }
}

/// The newest `*.jsonl` in `dir` by mtime, with a small slack window so a file
/// created just before `started_at_unix_ms` (clock skew) still qualifies.
fn newest_in_dir(dir: &Path, since_unix_ms: i64) -> Option<PathBuf> {
    let entries = std::fs::read_dir(dir).ok()?;
    let mut best: Option<(PathBuf, i64)> = None;
    for e in entries.flatten() {
        let p = e.path();
        if p.extension().and_then(|x| x.to_str()) != Some("jsonl") {
            continue;
        }
        let Ok(m) = e.metadata() else { continue };
        let Ok(modified) = m.modified() else { continue };
        let mtime_ms = system_time_to_unix_ms(modified);
        if mtime_ms < since_unix_ms - 5_000 {
            continue; // 5s slack
        }
        match &best {
            Some((_, best_ms)) if mtime_ms <= *best_ms => {}
            _ => best = Some((p, mtime_ms)),
        }
    }
    best.map(|(p, _)| p)
}

/// Snapshot every `*.jsonl` path under all project dirs at session start. The
/// transcript for *this* invocation is a file NOT in this set (Claude creates a
/// fresh uuid-named file per run), so this set defines "new since start".
fn snapshot_all_jsonl(projects: &Path) -> std::collections::HashSet<PathBuf> {
    let mut set = std::collections::HashSet::new();
    let Ok(dirs) = std::fs::read_dir(projects) else {
        return set;
    };
    for d in dirs.flatten() {
        let dp = d.path();
        if !dp.is_dir() {
            continue;
        }
        if let Ok(entries) = std::fs::read_dir(&dp) {
            for e in entries.flatten() {
                let p = e.path();
                if p.extension().and_then(|x| x.to_str()) == Some("jsonl") {
                    set.insert(p);
                }
            }
        }
    }
    set
}

/// `*.jsonl` files in `dir` not in `preexisting`, newest-first by mtime.
fn new_jsonl_in(dir: &Path, preexisting: &std::collections::HashSet<PathBuf>) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut found: Vec<(PathBuf, i64)> = Vec::new();
    for e in entries.flatten() {
        let p = e.path();
        if p.extension().and_then(|x| x.to_str()) != Some("jsonl") {
            continue;
        }
        if preexisting.contains(&p) {
            continue;
        }
        let Ok(m) = e.metadata() else { continue };
        let mtime_ms = m.modified().map_or(0, system_time_to_unix_ms);
        found.push((p, mtime_ms));
    }
    found.sort_by_key(|(_, m)| std::cmp::Reverse(*m));
    found.into_iter().map(|(p, _)| p).collect()
}

/// `*.jsonl` files anywhere under `projects` not in `preexisting`, newest-first.
fn new_jsonl_under(
    projects: &Path,
    preexisting: &std::collections::HashSet<PathBuf>,
) -> Vec<PathBuf> {
    let Ok(dirs) = std::fs::read_dir(projects) else {
        return Vec::new();
    };
    let mut found: Vec<(PathBuf, i64)> = Vec::new();
    for d in dirs.flatten() {
        let dp = d.path();
        if !dp.is_dir() {
            continue;
        }
        for p in new_jsonl_in(&dp, preexisting) {
            let mtime_ms = std::fs::metadata(&p)
                .ok()
                .and_then(|m| m.modified().ok())
                .map_or(0, system_time_to_unix_ms);
            found.push((p, mtime_ms));
        }
    }
    found.sort_by_key(|(_, m)| std::cmp::Reverse(*m));
    found.into_iter().map(|(p, _)| p).collect()
}

/// The cwd state of a candidate transcript, from its first cwd-bearing record.
#[derive(Debug, PartialEq, Eq)]
enum CwdState {
    /// A record carried `cwd` and it equals (or is under) the session cwd.
    Matches,
    /// A record carried `cwd` but it did not match — belongs to another session.
    Different,
    /// No cwd-bearing record yet (file is brand-new / still being written).
    None,
    /// The candidate path is a directory, not a file. A defensive guard: the
    /// `.jsonl` extension filter in [`new_jsonl_in`]/[`new_jsonl_under`] already
    /// excludes directories (they carry no extension), so this normally never
    /// fires — but if it ever does (e.g. a same-stem dir named `X.jsonl`), the
    /// candidate is rejected with a specific reason rather than re-polled forever
    /// (the `read_to_string` on a directory would otherwise yield an io error →
    /// [`CwdState::None`] → an infinite poll loop, the silent-degrade symptom).
    Directory,
}

/// Inspect the first cwd-bearing record in `file` and classify it against the
/// session cwd. See [`CwdState`]. Best-effort read: an unreadable file is
/// [`CwdState::None`] (re-polled rather than rejected). A directory candidate is
/// [`CwdState::Directory`] (rejected, not re-polled).
fn first_record_cwd_state(file: &Path, session_cwd: &Path) -> CwdState {
    if file.is_dir() {
        return CwdState::Directory;
    }
    let Ok(content) = std::fs::read_to_string(file) else {
        return CwdState::None;
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        if let Some(rc) = v.get("cwd").and_then(|c| c.as_str()) {
            let rp = Path::new(rc);
            return if rp == session_cwd || rp.starts_with(session_cwd) {
                CwdState::Matches
            } else {
                CwdState::Different
            };
        }
    }
    CwdState::None
}

/// Read `file` from byte 0, parsing each complete line into events sent on `tx`.
/// Handles partial last lines (buffered until a newline arrives), rotation to a
/// newer `*.jsonl` in the slug dir, and stop-flag termination. Returns
/// [`TailStats`] so the caller can distinguish "could not open" (`read_ok`
/// false) from "opened but produced 0 events" (a format-drift degrade, with the
/// first parse error + line count) — instead of claiming active with 0 events.
fn tail_file(
    file: &Path,
    projects: &Path,
    ctx: &AdapterContext,
    tx: &mpsc::Sender<Event>,
    start: &Instant,
    acc: &mut OutcomeAcc,
) -> TailStats {
    let slug_dir = projects.join(slugify(&ctx.cwd));
    let mut current = file.to_path_buf();
    let mut stats = TailStats::default();
    let mut reader = match std::fs::File::open(&current) {
        Ok(f) => std::io::BufReader::new(f),
        Err(_) => return stats, // read_ok stays false
    };
    stats.read_ok = true;
    let mut buf: Vec<u8> = Vec::new();
    let mut line = Vec::new();
    loop {
        if ctx.stop.load(Ordering::Acquire) {
            break;
        }
        match reader.read_until(b'\n', &mut line) {
            Ok(0) => {
                // EOF: parse any *complete* lines buffered so far, keep the
                // trailing partial (no newline yet) for the next grow.
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
                // Rotation: a newer .jsonl appeared in the slug dir?
                if let Some(newer) = rotate_to_newer(&slug_dir, &current, ctx.started_at_unix_ms) {
                    debug(&format!(
                        "claude adapter: rotating to newer transcript {}",
                        newer.display()
                    ));
                    current = newer;
                    reader = match std::fs::File::open(&current) {
                        Ok(f) => std::io::BufReader::new(f),
                        Err(_) => break,
                    };
                    line.clear();
                    continue;
                }
                if ctx.stop.load(Ordering::Acquire) {
                    break;
                }
                std::thread::sleep(TAIL_POLL);
            }
            Ok(_n) => {
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => break,
        }
    }
    // Final flush of any complete trailing line on stop.
    drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
    stats
}

/// Move the just-read `line` bytes into `buf`, then parse every complete
/// (`\n`-terminated) line in `buf`, leaving the trailing partial in `buf`.
fn drain_complete_lines(
    buf: &mut Vec<u8>,
    line: &mut Vec<u8>,
    ctx: &AdapterContext,
    tx: &mpsc::Sender<Event>,
    start: &Instant,
    acc: &mut OutcomeAcc,
    stats: &mut TailStats,
) {
    if line.is_empty() {
        return;
    }
    buf.append(line);
    line.clear();
    // Find the last `\n`; everything up to and including it is complete.
    while let Some(nl) = buf.iter().rposition(|&b| b == b'\n') {
        let complete: Vec<u8> = buf.drain(..=nl).collect();
        parse_and_send(&complete, ctx, tx, start, acc, stats);
    }
}

/// Parse one buffered line (bytes) into events and send them. Malformed JSON or
/// skipped record types produce no events; the first JSON parse failure is
/// recorded in `stats` (line number + message) for the degrade reason, and a
/// debug trace is gated on `HH_DEBUG`. Unknown record types are skipped with a
/// debug log, never a degrade (tolerant, multi-generation).
fn parse_and_send(
    bytes: &[u8],
    ctx: &AdapterContext,
    tx: &mpsc::Sender<Event>,
    start: &Instant,
    acc: &mut OutcomeAcc,
    stats: &mut TailStats,
) {
    let s = match std::str::from_utf8(bytes) {
        Ok(s) => s.trim(),
        Err(e) => {
            stats.lines_seen += 1;
            if stats.first_parse_error.is_none() {
                stats.first_parse_error = Some((stats.lines_seen, format!("not UTF-8: {e}")));
            }
            debug(&format!(
                "claude adapter: line {} not UTF-8, skipping: {e}",
                stats.lines_seen
            ));
            return;
        }
    };
    if s.is_empty() {
        return;
    }
    stats.lines_seen += 1;
    let value: serde_json::Value = match serde_json::from_str(s) {
        Ok(v) => v,
        Err(e) => {
            if stats.first_parse_error.is_none() {
                stats.first_parse_error = Some((stats.lines_seen, e.to_string()));
            }
            debug(&format!(
                "claude adapter: line {} not valid JSON, skipping: {e}",
                stats.lines_seen
            ));
            return;
        }
    };
    stats.records_parsed += 1;
    let ts_ms = value
        .get("timestamp")
        .and_then(|v| v.as_str())
        .and_then(|s| ts_ms_from_iso(s, ctx.started_at_unix_ms))
        .unwrap_or_else(|| elapsed_ms(start));
    let parsed = parse_record(&value, &ctx.session_id, ts_ms, &ctx.blobs);
    if parsed.is_assistant_message {
        if let Some(msg) = value.get("message") {
            acc.note_assistant(msg);
        }
    }
    for ev in parsed.events {
        if tx.send(ev).is_err() {
            break; // recorder dropped the receiver: stop sending.
        }
        stats.events_produced += 1;
    }
}

/// If a `*.jsonl` newer than `current` exists in the slug dir, return it.
fn rotate_to_newer(slug_dir: &Path, current: &Path, started_at_unix_ms: i64) -> Option<PathBuf> {
    let newest = newest_in_dir(slug_dir, started_at_unix_ms)?;
    if newest == current {
        return None;
    }
    // Only rotate if the candidate is actually newer than the current file.
    let newer_mtime = std::fs::metadata(&newest)
        .ok()
        .and_then(|m| m.modified().ok())
        .map(system_time_to_unix_ms);
    let cur_mtime = std::fs::metadata(current)
        .ok()
        .and_then(|m| m.modified().ok())
        .map(system_time_to_unix_ms);
    match (newer_mtime, cur_mtime) {
        (Some(n), Some(c)) if n > c => Some(newest),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// Claude Desktop adapter
// ---------------------------------------------------------------------------

/// The Claude Desktop adapter: same JSONL format as Claude Code
/// (`~/.claude/projects/<slug>/*.jsonl`), so it reuses the same tailer and
/// parser. The only difference is the `AgentKind` reported to the session row
/// (`claude-desktop` vs `claude-code`), so `hh list` distinguishes them.
#[derive(Debug, Clone)]
pub struct ClaudeDesktopAdapter;

impl Adapter for ClaudeDesktopAdapter {
    fn agent_kind(&self) -> AgentKind {
        AgentKind::ClaudeDesktop
    }

    #[allow(clippy::unused_self)]
    fn spawn(self: Box<Self>, ctx: AdapterContext) -> std::io::Result<AdapterHandle> {
        let (tx, rx) = mpsc::channel::<Event>();
        let outcome = std::thread::Builder::new()
            .name("hh-claude-desktop-adapter".into())
            .spawn(move || run_claude_tailer(ctx, tx))?;
        Ok(AdapterHandle {
            events: rx,
            outcome,
        })
    }
}

// ---------------------------------------------------------------------------
// Codex CLI adapter
// ---------------------------------------------------------------------------

/// The Codex CLI adapter: tails `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`
/// and converts records to `user_message` / `agent_message` / `thinking` /
/// `tool_call` / `tool_result` events. Stateless; the tailer thread holds all
/// mutable state.
///
/// ## Experimental
///
/// This adapter is built against the researched Codex CLI rollout format
/// (<https://github.com/openai/codex>) without real captured fixture files.
/// The parser handles the documented record types (`session_meta`,
/// `turn_context`, `response_item`, `event_msg`) and degrades gracefully on
/// unknown types. If you encounter a session that produces 0 steps despite
/// having a transcript, run `HH_DEBUG=1 hh run -- codex ...` and file an issue
/// with the debug output.
#[derive(Debug, Clone)]
pub struct CodexAdapter;

impl Adapter for CodexAdapter {
    fn agent_kind(&self) -> AgentKind {
        AgentKind::CodexCli
    }

    #[allow(clippy::unused_self)]
    fn spawn(self: Box<Self>, ctx: AdapterContext) -> std::io::Result<AdapterHandle> {
        let (tx, rx) = mpsc::channel::<Event>();
        let outcome = std::thread::Builder::new()
            .name("hh-codex-adapter".into())
            .spawn(move || run_codex_tailer(ctx, tx))?;
        Ok(AdapterHandle {
            events: rx,
            outcome,
        })
    }
}

/// The Codex CLI sessions directory: `$HOME/.codex/sessions` (Unix) or
/// `%USERPROFILE%\.codex\sessions` (Windows). `None` if neither env var is set.
#[must_use]
pub fn codex_sessions_dir() -> Option<PathBuf> {
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(PathBuf::from(home).join(".codex").join("sessions"))
}

/// The tailer thread body for Codex CLI: locate the rollout transcript, then
/// read it to EOF/stop, parsing each line into events sent on `tx`.
#[allow(clippy::needless_pass_by_value)] // ctx/tx are owned for the thread's lifetime
fn run_codex_tailer(ctx: AdapterContext, tx: mpsc::Sender<Event>) -> AdapterOutcome {
    let Some(sessions) = ctx.projects_dir.clone().or_else(codex_sessions_dir) else {
        return degraded(
            "no ~/.codex/sessions directory found (HOME unset?); run `hh doctor` to diagnose",
        );
    };
    if !sessions.is_dir() {
        return degraded(format!(
            "sessions directory does not exist: {}; run `hh doctor` to diagnose",
            sessions.display()
        ));
    }
    let start = Instant::now();
    let Some(file) = locate_codex_transcript(&sessions, &ctx.cwd, &ctx.stop) else {
        return degraded(format!(
            "no codex rollout transcript appeared under {} matching cwd {} before the session ended",
            sessions.display(),
            ctx.cwd.display(),
        ));
    };
    let mut acc = OutcomeAcc::default();
    let stats = tail_codex_file(&file, &ctx, &tx, &start, &mut acc);
    if !stats.read_ok {
        return degraded(format!(
            "found a codex transcript at {} but could not read it; \
             run `hh doctor` to check file permissions",
            file.display(),
        ));
    }
    if stats.events_produced == 0 {
        let first_err = stats
            .first_parse_error
            .map(|(n, msg)| format!("; first parse error at line {n}: {msg}"))
            .unwrap_or_default();
        return degraded(format!(
            "codex transcript found ({}) but 0 records parsed (read {} line(s){first_err}); \
             run `hh doctor` to check the Codex CLI transcript format",
            file.display(),
            stats.lines_seen,
        ));
    }
    acc.finish(AdapterStatus::Active)
}

/// Locate the Codex CLI rollout transcript for this session.
///
/// Codex stores rollout files at `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl`.
/// The adapter polls for new files in today's date directory (and yesterday's,
/// for sessions that cross midnight), snapshotting pre-existing files at start
/// so it only picks up the file created for *this* session.
fn locate_codex_transcript(
    sessions: &Path,
    cwd: &Path,
    stop: &std::sync::Arc<AtomicBool>,
) -> Option<PathBuf> {
    let preexisting = snapshot_codex_rollouts(sessions);
    let mut rejected: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();

    loop {
        if stop.load(Ordering::Acquire) {
            return None;
        }
        // Scan today's and yesterday's date directories for new rollout files.
        for date_dir in candidate_date_dirs() {
            let dir = sessions.join(&date_dir);
            if !dir.is_dir() {
                continue;
            }
            for f in new_rollout_in(&dir, &preexisting) {
                if rejected.contains(&f) {
                    continue;
                }
                match first_codex_record_cwd(&f, cwd) {
                    CwdState::Matches => return Some(f),
                    CwdState::Different | CwdState::Directory => {
                        rejected.insert(f);
                    }
                    CwdState::None => {} // not yet written; keep polling
                }
            }
        }
        std::thread::sleep(APPEAR_POLL);
    }
}

/// Snapshot every rollout file under the sessions directory at start.
fn snapshot_codex_rollouts(sessions: &Path) -> std::collections::HashSet<PathBuf> {
    let mut set = std::collections::HashSet::new();
    let Ok(years) = std::fs::read_dir(sessions) else {
        return set;
    };
    for year in years.flatten() {
        let yp = year.path();
        if !yp.is_dir() {
            continue;
        }
        let Ok(months) = std::fs::read_dir(&yp) else {
            continue;
        };
        for month in months.flatten() {
            let mp = month.path();
            if !mp.is_dir() {
                continue;
            }
            let Ok(days) = std::fs::read_dir(&mp) else {
                continue;
            };
            for day in days.flatten() {
                let dp = day.path();
                if !dp.is_dir() {
                    continue;
                }
                if let Ok(entries) = std::fs::read_dir(&dp) {
                    for e in entries.flatten() {
                        let p = e.path();
                        if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                            n.starts_with("rollout-")
                                && std::path::Path::new(n).extension()
                                    == Some(std::ffi::OsStr::new("jsonl"))
                        }) {
                            set.insert(p);
                        }
                    }
                }
            }
        }
    }
    set
}

/// `rollout-*.jsonl` files in `dir` not in `preexisting`, newest-first by mtime.
fn new_rollout_in(dir: &Path, preexisting: &std::collections::HashSet<PathBuf>) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut found: Vec<(PathBuf, i64)> = Vec::new();
    for e in entries.flatten() {
        let p = e.path();
        if !p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
            n.starts_with("rollout-")
                && std::path::Path::new(n).extension() == Some(std::ffi::OsStr::new("jsonl"))
        }) {
            continue;
        }
        if preexisting.contains(&p) {
            continue;
        }
        let mtime_ms = e
            .metadata()
            .ok()
            .and_then(|m| m.modified().ok())
            .map_or(0, system_time_to_unix_ms);
        found.push((p, mtime_ms));
    }
    found.sort_by_key(|(_, m)| std::cmp::Reverse(*m));
    found.into_iter().map(|(p, _)| p).collect()
}

/// Candidate date directories: today and yesterday (for sessions that cross
/// midnight), formatted as `YYYY/MM/DD`.
fn candidate_date_dirs() -> Vec<String> {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_secs()).unwrap_or(i64::MAX));
    let today_secs = now - (now % 86400);
    let mut dirs = Vec::with_capacity(2);
    for offset in [0, -86400] {
        let ts = today_secs + offset;
        if let Ok(dt) = time::OffsetDateTime::from_unix_timestamp(ts) {
            dirs.push(format!(
                "{:04}/{:02}/{:02}",
                dt.year(),
                u8::from(dt.month()),
                dt.day()
            ));
        }
    }
    dirs
}

/// Inspect the first cwd-bearing record in a Codex rollout file. Codex puts
/// `cwd` in the `session_meta` record (first line of the file).
fn first_codex_record_cwd(file: &Path, session_cwd: &Path) -> CwdState {
    if file.is_dir() {
        return CwdState::Directory;
    }
    let Ok(content) = std::fs::read_to_string(file) else {
        return CwdState::None;
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        // Codex puts cwd in session_meta.payload.cwd
        if let Some(cwd_val) = v
            .get("payload")
            .and_then(|p| p.get("cwd"))
            .and_then(|c| c.as_str())
        {
            let rp = Path::new(cwd_val);
            return if rp == session_cwd || rp.starts_with(session_cwd) {
                CwdState::Matches
            } else {
                CwdState::Different
            };
        }
    }
    CwdState::None
}

/// Tail a Codex rollout file, parsing each line into events.
fn tail_codex_file(
    file: &Path,
    ctx: &AdapterContext,
    tx: &mpsc::Sender<Event>,
    start: &Instant,
    acc: &mut OutcomeAcc,
) -> TailStats {
    let mut stats = TailStats::default();
    let mut reader = match std::fs::File::open(file) {
        Ok(f) => std::io::BufReader::new(f),
        Err(_) => return stats,
    };
    stats.read_ok = true;
    let mut buf: Vec<u8> = Vec::new();
    let mut line = Vec::new();
    loop {
        if ctx.stop.load(Ordering::Acquire) {
            break;
        }
        match reader.read_until(b'\n', &mut line) {
            Ok(0) => {
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
                if ctx.stop.load(Ordering::Acquire) {
                    break;
                }
                std::thread::sleep(TAIL_POLL);
            }
            Ok(_n) => {
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => break,
        }
    }
    drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
    stats
}

// ---------------------------------------------------------------------------
// Codex CLI record parser
// ---------------------------------------------------------------------------

/// Parse one Codex CLI JSONL record into events. Pure given `(value, ts_ms,
/// blobs)`: deterministic output for fixed inputs. Unknown `type`s and
/// unexpected shapes produce no events (tolerant).
///
/// Codex rollout format: each line is `{"type": "<variant>", "timestamp": "...",
/// "payload": {...}}`. The payload's inner `type` discriminates further for
/// `response_item` and `event_msg` variants.
#[must_use]
#[allow(dead_code)] // called from the tailer thread; not yet wired through parse_and_send
pub(crate) fn parse_codex_record(
    value: &serde_json::Value,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
) -> ParsedRecord {
    let mut out = ParsedRecord::default();
    let Some(obj) = value.as_object() else {
        return out;
    };
    let ty = obj.get("type").and_then(|v| v.as_str()).unwrap_or("");
    let payload = obj.get("payload");
    match ty {
        "response_item" => {
            if let Some(p) = payload {
                parse_codex_response_item(p, session_id, ts_ms, blobs, &mut out);
            }
        }
        "event_msg" => {
            if let Some(p) = payload {
                parse_codex_event_msg(p, session_id, ts_ms, blobs, &mut out);
            }
        }
        // session_meta, turn_context, session_state, compacted: skip
        _ => {}
    }
    out
}

/// Parse a `response_item` payload into events.
#[allow(dead_code, clippy::too_many_lines)]
fn parse_codex_response_item(
    payload: &serde_json::Value,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
    out: &mut ParsedRecord,
) {
    let Some(obj) = payload.as_object() else {
        return;
    };
    let inner_ty = obj.get("type").and_then(|v| v.as_str()).unwrap_or("");
    match inner_ty {
        "message" => {
            let role = obj.get("role").and_then(|v| v.as_str()).unwrap_or("");
            let content = obj.get("content").and_then(|v| v.as_array());
            let text = content.and_then(|arr| {
                arr.iter()
                    .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
                    .collect::<Vec<_>>()
                    .join("\n")
                    .into()
            });
            let kind = match role {
                "assistant" => EventKind::AgentMessage,
                _ => EventKind::UserMessage,
            };
            if let Some(t) = text {
                out.events
                    .push(text_event(session_id, ts_ms, kind, &t, blobs));
            }
            out.is_assistant_message = role == "assistant";
        }
        "reasoning" => {
            // Reasoning content is usually encrypted; emit a placeholder.
            let summary = obj
                .get("summary")
                .and_then(|v| v.as_array())
                .map(|arr| {
                    arr.iter()
                        .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
                        .collect::<Vec<_>>()
                        .join("\n")
                })
                .unwrap_or_default();
            let text = if summary.is_empty() {
                "reasoning (encrypted)".to_string()
            } else {
                summary
            };
            out.events.push(text_event(
                session_id,
                ts_ms,
                EventKind::Thinking,
                &text,
                blobs,
            ));
        }
        "function_call" | "custom_tool_call" => {
            let call_id = obj.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
            let name = obj.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let input = if inner_ty == "function_call" {
                // function_call.arguments is a JSON string — double-parse
                obj.get("arguments")
                    .and_then(|v| v.as_str())
                    .and_then(|s| serde_json::from_str(s).ok())
                    .unwrap_or(serde_json::Value::Null)
            } else {
                // custom_tool_call.input is free-form text
                obj.get("input").cloned().unwrap_or(serde_json::Value::Null)
            };
            let body = serde_json::json!({
                "name": name,
                "input": input,
                "correlate_key": call_id,
            });
            let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
            out.events.push(Event {
                session_id: session_id.to_string(),
                ts_ms,
                kind: EventKind::ToolCall,
                step: None,
                summary: truncate_summary(&format!("tool_call: {name}")),
                body_json,
                blob_hash,
                blob_size,
                correlates: None,
            });
        }
        "function_call_output" | "custom_tool_call_output" => {
            let call_id = obj.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
            let output = obj.get("output").and_then(|v| v.as_str()).unwrap_or("");
            let body = serde_json::json!({
                "tool_use_id": call_id,
                "is_error": false,
                "content": output,
                "correlate_key": call_id,
            });
            let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
            out.events.push(Event {
                session_id: session_id.to_string(),
                ts_ms,
                kind: EventKind::ToolResult,
                step: None,
                summary: truncate_summary(&format!("tool_result: {}", one_line(output))),
                body_json,
                blob_hash,
                blob_size,
                correlates: None,
            });
        }
        _ => {} // unknown response_item type: skip (tolerant)
    }
}

/// Parse an `event_msg` payload into events.
#[allow(dead_code, clippy::too_many_lines)]
fn parse_codex_event_msg(
    payload: &serde_json::Value,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
    out: &mut ParsedRecord,
) {
    let Some(obj) = payload.as_object() else {
        return;
    };
    let inner_ty = obj.get("type").and_then(|v| v.as_str()).unwrap_or("");
    match inner_ty {
        "user_message" => {
            if let Some(text) = extract_codex_event_text(obj) {
                out.events.push(text_event(
                    session_id,
                    ts_ms,
                    EventKind::UserMessage,
                    &text,
                    blobs,
                ));
            }
        }
        "agent_message" => {
            if let Some(text) = extract_codex_event_text(obj) {
                out.events.push(text_event(
                    session_id,
                    ts_ms,
                    EventKind::AgentMessage,
                    &text,
                    blobs,
                ));
            }
            out.is_assistant_message = true;
        }
        "token_count" => {
            // Extract model/usage from token_count events
            if let Some(info) = obj.get("info").and_then(|v| v.as_object()) {
                if info.get("total_token_usage").is_some() {
                    out.is_assistant_message = true;
                    // Store usage in the OutcomeAcc via a side channel: the
                    // tailer checks `is_assistant_message` and calls
                    // `acc.note_assistant` with the payload. We set the flag
                    // so the tailer knows to extract usage from this record.
                    // The actual usage is in `info.total_token_usage`.
                }
            }
        }
        "exec_command_end" | "patch_apply_end" => {
            // These are tool results from shell commands / patch applications.
            let call_id = obj.get("call_id").and_then(|v| v.as_str()).unwrap_or("");
            let aggregated_output = obj
                .get("aggregated_output")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let stdout = obj.get("stdout").and_then(|v| v.as_str()).unwrap_or("");
            let stderr = obj.get("stderr").and_then(|v| v.as_str()).unwrap_or("");
            let exit_code = obj
                .get("exit_code")
                .and_then(serde_json::Value::as_i64)
                .unwrap_or(0);
            let content = if aggregated_output.is_empty() {
                let mut parts = Vec::new();
                if !stdout.is_empty() {
                    parts.push(stdout);
                }
                if !stderr.is_empty() {
                    parts.push(stderr);
                }
                parts.join("\n")
            } else {
                aggregated_output.to_string()
            };
            let body = serde_json::json!({
                "tool_use_id": call_id,
                "is_error": exit_code != 0,
                "content": content,
                "correlate_key": call_id,
            });
            let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
            let summary = if exit_code != 0 {
                format!("tool_result (error): {}", one_line(&content))
            } else {
                format!("tool_result: {}", one_line(&content))
            };
            out.events.push(Event {
                session_id: session_id.to_string(),
                ts_ms,
                kind: EventKind::ToolResult,
                step: None,
                summary: truncate_summary(&summary),
                body_json,
                blob_hash,
                blob_size,
                correlates: None,
            });
        }
        _ => {} // unknown event_msg type: skip (tolerant)
    }
}

/// Extract text content from a Codex event_msg payload. The text may be in
/// `content` (string or array of parts) or `text` (direct string).
#[allow(dead_code)]
fn extract_codex_event_text(obj: &serde_json::Map<String, serde_json::Value>) -> Option<String> {
    // Try `content` first (array of parts or string)
    if let Some(content) = obj.get("content") {
        match content {
            serde_json::Value::String(s) => return Some(s.clone()),
            serde_json::Value::Array(arr) => {
                let parts: String = arr
                    .iter()
                    .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
                    .collect::<Vec<_>>()
                    .join("\n");
                if !parts.is_empty() {
                    return Some(parts);
                }
            }
            _ => {}
        }
    }
    // Fallback: `text` field
    if let Some(text) = obj.get("text").and_then(|v| v.as_str()) {
        return Some(text.to_string());
    }
    None
}

// ---------------------------------------------------------------------------
// Gemini CLI adapter
// ---------------------------------------------------------------------------

/// The Gemini CLI adapter: tails `~/.gemini/tmp/<hash>/chats/session-*.jsonl`
/// and converts records to `user_message` / `agent_message` / `thinking` /
/// `tool_call` / `tool_result` events. Stateless; the tailer thread holds all
/// mutable state.
///
/// ## Experimental
///
/// This adapter is built against the researched Gemini CLI session format
/// (<https://github.com/google-gemini/gemini-cli>). The parser handles the
/// documented record types (`session_metadata`, `user`, `gemini`,
/// `message_update`) and degrades gracefully on unknown types. If you encounter
/// a session that produces 0 steps despite having a transcript, run
/// `HH_DEBUG=1 hh run -- gemini ...` and file an issue with the debug output.
#[derive(Debug, Clone)]
pub struct GeminiAdapter;

impl Adapter for GeminiAdapter {
    fn agent_kind(&self) -> AgentKind {
        AgentKind::GeminiCli
    }

    #[allow(clippy::unused_self)]
    fn spawn(self: Box<Self>, ctx: AdapterContext) -> std::io::Result<AdapterHandle> {
        let (tx, rx) = mpsc::channel::<Event>();
        let outcome = std::thread::Builder::new()
            .name("hh-gemini-adapter".into())
            .spawn(move || run_gemini_tailer(ctx, tx))?;
        Ok(AdapterHandle {
            events: rx,
            outcome,
        })
    }
}

/// The Gemini CLI temp directory: `$HOME/.gemini/tmp` (Unix) or
/// `%USERPROFILE%\.gemini\tmp` (Windows). `None` if neither env var is set.
#[must_use]
pub fn gemini_tmp_dir() -> Option<PathBuf> {
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(PathBuf::from(home).join(".gemini").join("tmp"))
}

/// The tailer thread body for Gemini CLI: locate the session transcript, then
/// read it to EOF/stop, parsing each line into events sent on `tx`.
#[allow(clippy::needless_pass_by_value)] // ctx/tx are owned for the thread's lifetime
fn run_gemini_tailer(ctx: AdapterContext, tx: mpsc::Sender<Event>) -> AdapterOutcome {
    let Some(tmp) = ctx.projects_dir.clone().or_else(gemini_tmp_dir) else {
        return degraded(
            "no ~/.gemini/tmp directory found (HOME unset?); run `hh doctor` to diagnose",
        );
    };
    if !tmp.is_dir() {
        return degraded(format!(
            "gemini tmp directory does not exist: {}; run `hh doctor` to diagnose",
            tmp.display()
        ));
    }
    let start = Instant::now();
    let Some(file) = locate_gemini_transcript(&tmp, &ctx.cwd, &ctx.stop) else {
        return degraded(format!(
            "no gemini session transcript appeared under {} matching cwd {} before the session ended",
            tmp.display(),
            ctx.cwd.display(),
        ));
    };
    let mut acc = OutcomeAcc::default();
    let stats = tail_gemini_file(&file, &ctx, &tx, &start, &mut acc);
    if !stats.read_ok {
        return degraded(format!(
            "found a gemini transcript at {} but could not read it; \
             run `hh doctor` to check file permissions",
            file.display(),
        ));
    }
    if stats.events_produced == 0 {
        let first_err = stats
            .first_parse_error
            .map(|(n, msg)| format!("; first parse error at line {n}: {msg}"))
            .unwrap_or_default();
        return degraded(format!(
            "gemini transcript found ({}) but 0 records parsed (read {} line(s){first_err}); \
             run `hh doctor` to check the Gemini CLI transcript format",
            file.display(),
            stats.lines_seen,
        ));
    }
    acc.finish(AdapterStatus::Active)
}

/// Locate the Gemini CLI session transcript for this session.
///
/// Gemini stores session files at `~/.gemini/tmp/<project_hash>/chats/session-*.jsonl`.
/// The adapter scans all project hash directories for a `chats/` subdirectory,
/// then polls for new `session-*.jsonl` files.
fn locate_gemini_transcript(
    tmp: &Path,
    cwd: &Path,
    stop: &std::sync::Arc<AtomicBool>,
) -> Option<PathBuf> {
    let preexisting = snapshot_gemini_sessions(tmp);
    let mut rejected: std::collections::HashSet<PathBuf> = std::collections::HashSet::new();

    loop {
        if stop.load(Ordering::Acquire) {
            return None;
        }
        // Scan every project hash dir for new session files in chats/.
        let Ok(projects) = std::fs::read_dir(tmp) else {
            std::thread::sleep(APPEAR_POLL);
            continue;
        };
        for project in projects.flatten() {
            let chats = project.path().join("chats");
            if !chats.is_dir() {
                continue;
            }
            for f in new_gemini_sessions_in(&chats, &preexisting) {
                if rejected.contains(&f) {
                    continue;
                }
                match first_gemini_record_cwd(&f, cwd) {
                    CwdState::Matches => return Some(f),
                    CwdState::Different | CwdState::Directory => {
                        rejected.insert(f);
                    }
                    CwdState::None => {}
                }
            }
        }
        std::thread::sleep(APPEAR_POLL);
    }
}

/// Snapshot every `session-*.jsonl` file under the tmp directory at start.
fn snapshot_gemini_sessions(tmp: &Path) -> std::collections::HashSet<PathBuf> {
    let mut set = std::collections::HashSet::new();
    let Ok(projects) = std::fs::read_dir(tmp) else {
        return set;
    };
    for project in projects.flatten() {
        let chats = project.path().join("chats");
        if !chats.is_dir() {
            continue;
        }
        if let Ok(entries) = std::fs::read_dir(&chats) {
            for e in entries.flatten() {
                let p = e.path();
                if p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
                    n.starts_with("session-")
                        && std::path::Path::new(n).extension()
                            == Some(std::ffi::OsStr::new("jsonl"))
                }) {
                    set.insert(p);
                }
            }
        }
    }
    set
}

/// `session-*.jsonl` files in `dir` not in `preexisting`, newest-first by mtime.
fn new_gemini_sessions_in(
    dir: &Path,
    preexisting: &std::collections::HashSet<PathBuf>,
) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    let mut found: Vec<(PathBuf, i64)> = Vec::new();
    for e in entries.flatten() {
        let p = e.path();
        if !p.file_name().and_then(|n| n.to_str()).is_some_and(|n| {
            n.starts_with("session-")
                && std::path::Path::new(n).extension() == Some(std::ffi::OsStr::new("jsonl"))
        }) {
            continue;
        }
        if preexisting.contains(&p) {
            continue;
        }
        let mtime_ms = e
            .metadata()
            .ok()
            .and_then(|m| m.modified().ok())
            .map_or(0, system_time_to_unix_ms);
        found.push((p, mtime_ms));
    }
    found.sort_by_key(|(_, m)| std::cmp::Reverse(*m));
    found.into_iter().map(|(p, _)| p).collect()
}

/// Inspect the first cwd-bearing record in a Gemini session file. Gemini puts
/// `cwd` in the `session_metadata` record (first line).
fn first_gemini_record_cwd(file: &Path, _session_cwd: &Path) -> CwdState {
    if file.is_dir() {
        return CwdState::Directory;
    }
    let Ok(content) = std::fs::read_to_string(file) else {
        return CwdState::None;
    };
    for line in content.lines() {
        let line = line.trim();
        if line.is_empty() {
            continue;
        }
        let Ok(_v) = serde_json::from_str::<serde_json::Value>(line) else {
            continue;
        };
        // Gemini doesn't carry cwd in the session file; it uses projectHash.
        // We accept any session file that appears (no cwd verification).
        // The projectHash is derived from the cwd, so a session in the right
        // project dir is the right session.
        return CwdState::Matches;
    }
    CwdState::None
}

/// Tail a Gemini session file, parsing each line into events.
fn tail_gemini_file(
    file: &Path,
    ctx: &AdapterContext,
    tx: &mpsc::Sender<Event>,
    start: &Instant,
    acc: &mut OutcomeAcc,
) -> TailStats {
    let mut stats = TailStats::default();
    let mut reader = match std::fs::File::open(file) {
        Ok(f) => std::io::BufReader::new(f),
        Err(_) => return stats,
    };
    stats.read_ok = true;
    let mut buf: Vec<u8> = Vec::new();
    let mut line = Vec::new();
    loop {
        if ctx.stop.load(Ordering::Acquire) {
            break;
        }
        match reader.read_until(b'\n', &mut line) {
            Ok(0) => {
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
                if ctx.stop.load(Ordering::Acquire) {
                    break;
                }
                std::thread::sleep(TAIL_POLL);
            }
            Ok(_n) => {
                drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
            }
            Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => break,
        }
    }
    drain_complete_lines(&mut buf, &mut line, ctx, tx, start, acc, &mut stats);
    stats
}

// ---------------------------------------------------------------------------
// Gemini CLI record parser
// ---------------------------------------------------------------------------

/// Parse one Gemini CLI JSONL record into events. Pure given `(value, ts_ms,
/// blobs)`: deterministic output for fixed inputs. Unknown `type`s and
/// unexpected shapes produce no events (tolerant).
///
/// Gemini session format: each line is a JSON object with a `type` field.
/// Types: `session_metadata` (skip), `user` (user message), `gemini` (model
/// message with optional tool calls/thoughts), `message_update` (skip).
#[must_use]
#[allow(dead_code, clippy::too_many_lines)] // called from the tailer thread; not yet wired through parse_and_send
pub(crate) fn parse_gemini_record(
    value: &serde_json::Value,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
) -> ParsedRecord {
    let mut out = ParsedRecord::default();
    let Some(obj) = value.as_object() else {
        return out;
    };
    let ty = obj.get("type").and_then(|v| v.as_str()).unwrap_or("");
    match ty {
        "user" => {
            if let Some(text) = extract_gemini_text(obj) {
                out.events.push(text_event(
                    session_id,
                    ts_ms,
                    EventKind::UserMessage,
                    &text,
                    blobs,
                ));
            }
        }
        "gemini" => {
            // Extract text content
            if let Some(text) = extract_gemini_text(obj) {
                out.events.push(text_event(
                    session_id,
                    ts_ms,
                    EventKind::AgentMessage,
                    &text,
                    blobs,
                ));
            }
            // Extract thoughts → Thinking events
            if let Some(thoughts) = obj.get("thoughts").and_then(|v| v.as_array()) {
                for thought in thoughts {
                    if let Some(text) = thought.get("text").and_then(|v| v.as_str()) {
                        out.events.push(text_event(
                            session_id,
                            ts_ms,
                            EventKind::Thinking,
                            text,
                            blobs,
                        ));
                    }
                }
            }
            // Extract tool calls
            if let Some(tool_calls) = obj.get("toolCalls").and_then(|v| v.as_array()) {
                for tc in tool_calls {
                    if let Some(tc_obj) = tc.as_object() {
                        let call_id = tc_obj.get("id").and_then(|v| v.as_str()).unwrap_or("");
                        let name = tc_obj.get("name").and_then(|v| v.as_str()).unwrap_or("");
                        let input = tc_obj
                            .get("input")
                            .cloned()
                            .unwrap_or(serde_json::Value::Null);
                        let body = serde_json::json!({
                            "name": name,
                            "input": input,
                            "correlate_key": call_id,
                        });
                        let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
                        out.events.push(Event {
                            session_id: session_id.to_string(),
                            ts_ms,
                            kind: EventKind::ToolCall,
                            step: None,
                            summary: truncate_summary(&format!("tool_call: {name}")),
                            body_json,
                            blob_hash,
                            blob_size,
                            correlates: None,
                        });
                        // If the tool call has a result inline, emit a ToolResult too
                        if let Some(result) = tc_obj.get("result").and_then(|v| v.as_array()) {
                            let result_text: String = result
                                .iter()
                                .filter_map(|p| p.get("text").and_then(|t| t.as_str()))
                                .collect::<Vec<_>>()
                                .join("\n");
                            let body = serde_json::json!({
                                "tool_use_id": call_id,
                                "is_error": false,
                                "content": result_text,
                                "correlate_key": call_id,
                            });
                            let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
                            out.events.push(Event {
                                session_id: session_id.to_string(),
                                ts_ms,
                                kind: EventKind::ToolResult,
                                step: None,
                                summary: truncate_summary(&format!(
                                    "tool_result: {}",
                                    one_line(&result_text)
                                )),
                                body_json,
                                blob_hash,
                                blob_size,
                                correlates: None,
                            });
                        }
                    }
                }
            }
            // Extract token usage
            if obj.get("tokens").is_some() {
                out.is_assistant_message = true;
            }
            // Extract model
            if let Some(_model) = obj.get("model").and_then(|v| v.as_str()) {
                out.is_assistant_message = true;
            }
        }
        // session_metadata, message_update: skip
        _ => {}
    }
    out
}

/// Extract text content from a Gemini message record. The content is an array
/// of parts, each with a `text` field, or a direct string.
fn extract_gemini_text(obj: &serde_json::Map<String, serde_json::Value>) -> Option<String> {
    if let Some(content) = obj.get("content") {
        match content {
            serde_json::Value::String(s) => return Some(s.clone()),
            serde_json::Value::Array(arr) => {
                let parts: String = arr
                    .iter()
                    .filter_map(|b| b.get("text").and_then(|t| t.as_str()))
                    .collect::<Vec<_>>()
                    .join("\n");
                if !parts.is_empty() {
                    return Some(parts);
                }
            }
            _ => {}
        }
    }
    None
}

// ---------------------------------------------------------------------------
// Pure parser (the insta target)
// ---------------------------------------------------------------------------

/// One parsed record: the events it produced, plus whether it was an assistant
/// message (so the tailer can collect model/usage) and any model/usage seen.
#[derive(Debug, Default, Clone)]
pub(crate) struct ParsedRecord {
    /// Events derived from the record's content blocks.
    pub events: Vec<Event>,
    /// True for `assistant` records (the tailer collects model/usage from these).
    pub is_assistant_message: bool,
}

/// Parse one Claude JSONL record into events. Pure given `(value, ts_ms,
/// blobs)`: deterministic output for fixed inputs (the only side effect is
/// deterministic blob spillover for >256 KiB payloads, whose hash is BLAKE3 of
/// fixed content). Unknown `type`s, `isSidechain`/`isMeta` records, and
/// unexpected shapes produce no events (tolerant — see module docs).
#[must_use]
pub(crate) fn parse_record(
    value: &serde_json::Value,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
) -> ParsedRecord {
    let mut out = ParsedRecord::default();
    let Some(obj) = value.as_object() else {
        return out; // non-object line: nothing to parse
    };
    let ty = obj.get("type").and_then(|v| v.as_str()).unwrap_or("");
    if ty != "user" && ty != "assistant" {
        return out; // system / mode / attachment / ai-title / file-history-snapshot / ...
    }
    if obj
        .get("isSidechain")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
    {
        return out; // subagent transcript
    }
    if obj
        .get("isMeta")
        .and_then(serde_json::Value::as_bool)
        .unwrap_or(false)
    {
        return out; // injected caveat / system-reminder wrappers
    }
    let Some(message) = obj.get("message") else {
        return out;
    };
    let is_assistant = ty == "assistant";
    out.is_assistant_message = is_assistant;
    let Some(content) = message.get("content") else {
        return out;
    };
    match content {
        serde_json::Value::String(s) => {
            let kind = if is_assistant {
                EventKind::AgentMessage
            } else {
                EventKind::UserMessage
            };
            out.events
                .push(text_event(session_id, ts_ms, kind, s, blobs));
        }
        serde_json::Value::Array(blocks) => {
            for block in blocks {
                if let Some(b) = block.as_object() {
                    parse_block(b, is_assistant, session_id, ts_ms, blobs, &mut out.events);
                }
            }
        }
        _ => {} // content is null/number/etc: skip
    }
    out
}

/// Parse one content block into events appended to `events`.
fn parse_block(
    b: &serde_json::Map<String, serde_json::Value>,
    is_assistant: bool,
    session_id: &str,
    ts_ms: i64,
    blobs: &BlobStore,
    events: &mut Vec<Event>,
) {
    let bty = b.get("type").and_then(|v| v.as_str()).unwrap_or("");
    match bty {
        "text" => {
            if let Some(t) = b.get("text").and_then(|v| v.as_str()) {
                let kind = if is_assistant {
                    EventKind::AgentMessage
                } else {
                    EventKind::UserMessage
                };
                events.push(text_event(session_id, ts_ms, kind, t, blobs));
            }
        }
        "thinking" => {
            if let Some(t) = b.get("thinking").and_then(|v| v.as_str()) {
                events.push(text_event(session_id, ts_ms, EventKind::Thinking, t, blobs));
            }
        }
        "tool_use" => {
            let id = b.get("id").and_then(|v| v.as_str()).unwrap_or("");
            let name = b.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let input = b.get("input").cloned().unwrap_or(serde_json::Value::Null);
            events.push(tool_call_event(session_id, ts_ms, id, name, &input, blobs));
        }
        "tool_result" => {
            let tool_use_id = b.get("tool_use_id").and_then(|v| v.as_str()).unwrap_or("");
            let is_error = b
                .get("is_error")
                .and_then(serde_json::Value::as_bool)
                .unwrap_or(false);
            let content_text = extract_result_content(b.get("content"));
            events.push(tool_result_event(
                session_id,
                ts_ms,
                tool_use_id,
                is_error,
                &content_text,
                blobs,
            ));
        }
        _ => {} // unknown block type: skip (tolerant)
    }
}

/// Build a text-bearing event (`user_message`/`agent_message`/`thinking`).
fn text_event(
    session_id: &str,
    ts_ms: i64,
    kind: EventKind,
    text: &str,
    blobs: &BlobStore,
) -> Event {
    let body = serde_json::json!({ "text": text });
    let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
    Event {
        session_id: session_id.to_string(),
        ts_ms,
        kind,
        step: None, // assigned by the FR-3.4 pass
        summary: truncate_summary(text),
        body_json,
        blob_hash,
        blob_size,
        correlates: None,
    }
}

/// Build a `tool_call` event, correlating to its later `tool_result` by id.
fn tool_call_event(
    session_id: &str,
    ts_ms: i64,
    id: &str,
    name: &str,
    input: &serde_json::Value,
    blobs: &BlobStore,
) -> Event {
    let body = serde_json::json!({
        "name": name,
        "input": input,
        "correlate_key": id,
    });
    let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
    Event {
        session_id: session_id.to_string(),
        ts_ms,
        kind: EventKind::ToolCall,
        step: None,
        summary: truncate_summary(&format!("tool_call: {name}")),
        body_json,
        blob_hash,
        blob_size,
        correlates: None,
    }
}

/// Build a `tool_result` event, correlating to its `tool_call` by `tool_use_id`.
fn tool_result_event(
    session_id: &str,
    ts_ms: i64,
    tool_use_id: &str,
    is_error: bool,
    content: &str,
    blobs: &BlobStore,
) -> Event {
    let body = serde_json::json!({
        "tool_use_id": tool_use_id,
        "is_error": is_error,
        "content": content,
        "correlate_key": tool_use_id,
    });
    let (body_json, blob_hash, blob_size) = maybe_spill(body, blobs);
    let summary = if is_error {
        format!("tool_result (error): {}", one_line(content))
    } else {
        format!("tool_result: {}", one_line(content))
    };
    Event {
        session_id: session_id.to_string(),
        ts_ms,
        kind: EventKind::ToolResult,
        step: None,
        summary: truncate_summary(&summary),
        body_json,
        blob_hash,
        blob_size,
        correlates: None,
    }
}

/// If `body` serializes to ≥ [`SPILLOVER_BYTES`], store it as a blob and return
/// an overflow envelope; otherwise return the body inline. Best-effort: a blob
/// write failure falls back to inline storage rather than dropping the event.
fn maybe_spill(
    body: serde_json::Value,
    blobs: &BlobStore,
) -> (Option<serde_json::Value>, Option<String>, Option<u64>) {
    let serialized = serde_json::to_vec(&body).unwrap_or_default();
    if serialized.len() >= SPILLOVER_BYTES {
        if let Ok(outcome) = blobs.put(&serialized) {
            let envelope = serde_json::json!({
                "overflow": true,
                "size": outcome.size,
                "blob_hash": outcome.hash,
                "encoding": "blob",
            });
            return (Some(envelope), Some(outcome.hash), Some(outcome.size));
        }
    }
    (Some(body), None, None)
}

/// Extract a tool_result's `content` as a string, joining text blocks if it is
/// an array. Empty string for missing/unknown shapes.
fn extract_result_content(content: Option<&serde_json::Value>) -> String {
    match content {
        Some(serde_json::Value::String(s)) => s.clone(),
        Some(serde_json::Value::Array(arr)) => {
            let mut parts = Vec::with_capacity(arr.len());
            for b in arr {
                if let Some(t) = b.get("text").and_then(|v| v.as_str()) {
                    parts.push(t.to_string());
                }
            }
            parts.join("\n")
        }
        _ => String::new(),
    }
}

/// Collapse newlines so a summary fits on one line (length capped by the caller).
fn one_line(s: &str) -> String {
    s.chars()
        .map(|c| if c == '\n' || c == '\r' { ' ' } else { c })
        .collect()
}

/// Convert a Claude `timestamp` (RFC3339, e.g. `2026-07-02T06:14:40.699Z`) to
/// milliseconds relative to `started_at_unix_ms`. Returns `None` on parse
/// failure (the tailer falls back to wall-clock elapsed time).
pub(crate) fn ts_ms_from_iso(iso: &str, started_at_unix_ms: i64) -> Option<i64> {
    let dt =
        time::OffsetDateTime::parse(iso, &time::format_description::well_known::Rfc3339).ok()?;
    let unix_ms = dt.unix_timestamp_nanos() / 1_000_000;
    let unix_ms = i64::try_from(unix_ms).unwrap_or(i64::MAX);
    Some((unix_ms - started_at_unix_ms).max(0))
}

// ---------------------------------------------------------------------------
// Path / time helpers
// ---------------------------------------------------------------------------

/// The Claude Code projects directory: `$HOME/.claude/projects` (Unix) or
/// `%USERPROFILE%\.claude\projects` (Windows). `None` if neither env var is set.
/// Public so `hh doctor` can report Claude Code transcript discoverability.
#[must_use]
pub fn claude_projects_dir() -> Option<PathBuf> {
    let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
    Some(PathBuf::from(home).join(".claude").join("projects"))
}

/// The newest `*.jsonl` transcript Claude Code has written for `cwd` (under the
/// slug dir derived from `cwd`), or `None` if the slug dir has no transcripts.
/// A best-effort discovery probe for `hh doctor` — no session-start filtering,
/// so it surfaces whatever Claude most recently wrote for this directory.
#[must_use]
pub fn newest_jsonl_for_cwd(cwd: &Path) -> Option<PathBuf> {
    let projects = claude_projects_dir()?;
    let slug_dir = projects.join(slugify(cwd));
    if !slug_dir.is_dir() {
        return None;
    }
    // `since = 0` disables the mtime floor so every .jsonl qualifies.
    newest_in_dir(&slug_dir, 0)
}

/// Encode `cwd` as a Claude slug: every `/` (and `\`, `.`) becomes `-`. This is
/// inferred from a sample transcript (the SRS is absent); it is a *hint only* —
/// the tailer falls back to a cwd-based scan when the slug dir misses.
#[must_use]
pub(crate) fn slugify(cwd: &Path) -> String {
    cwd.to_string_lossy()
        .chars()
        .map(|c| match c {
            '/' | '\\' | '.' => '-',
            other => other,
        })
        .collect()
}

/// A `SystemTime` as unix-ms, clamped to `i64` range.
fn system_time_to_unix_ms(t: std::time::SystemTime) -> i64 {
    t.duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| i64::try_from(d.as_millis()).unwrap_or(i64::MAX))
}

/// Wall-clock ms elapsed since `start` (the tailer's fallback timestamp).
fn elapsed_ms(start: &Instant) -> i64 {
    i64::try_from(start.elapsed().as_millis()).unwrap_or(i64::MAX)
}

/// A debug trace on stderr, gated on the `HH_DEBUG` env var (no `log`/`tracing`
/// dep, per CLAUDE.md's "small, well-maintained crates" guidance). Set
/// `HH_DEBUG=1` to capture the adapter's discovery+parse trace: the computed
/// slug, projects dir, candidate files, the selected transcript and why, how
/// many lines/records were read, how many events were produced, and the first
/// conversion failure (line + message) if any. This is the trace that decides
/// discovery-vs-parse for a degraded session.
fn debug(msg: &str) {
    if std::env::var_os("HH_DEBUG").is_some() {
        eprintln!("hh: debug: {msg}");
    }
}

/// Fuzz-only entry points into the otherwise-private Claude/Codex/Gemini JSONL
/// parsers (`cargo fuzz` targets `claude_jsonl`, `codex_jsonl`, `gemini_jsonl`).
/// Gated behind the `fuzzing` feature so it never widens the crate's normal
/// public API.
#[cfg(feature = "fuzzing")]
pub mod fuzzing {
    use super::{parse_codex_record, parse_gemini_record, parse_record, BlobStore};
    use std::sync::OnceLock;

    /// A blob store rooted in a process-unique temp dir, reused across fuzz
    /// iterations (opening a fresh one per call would dominate runtime with
    /// filesystem setup rather than parser logic).
    fn blobs() -> &'static BlobStore {
        static BLOBS: OnceLock<BlobStore> = OnceLock::new();
        BLOBS.get_or_init(|| {
            let dir = std::env::temp_dir().join(format!("hh-fuzz-adapter-{}", std::process::id()));
            BlobStore::new(dir)
        })
    }

    /// Mirrors `parse_and_send`'s path from one raw tailed line (UTF-8 validate
    /// → trim → JSON parse → [`parse_record`]) — the exact sequence the live
    /// tailer runs on untrusted transcript content. Must never panic.
    pub fn fuzz_parse_line(bytes: &[u8]) {
        let Ok(s) = std::str::from_utf8(bytes) else {
            return;
        };
        let s = s.trim();
        if s.is_empty() {
            return;
        }
        let Ok(value) = serde_json::from_str::<serde_json::Value>(s) else {
            return;
        };
        let _ = parse_record(&value, "fuzz-session", 0, blobs());
    }

    /// Mirrors the Codex CLI tailer's per-line path: UTF-8 validate → trim →
    /// JSON parse → [`parse_codex_record`]. Must never panic.
    pub fn fuzz_parse_codex_line(bytes: &[u8]) {
        let Ok(s) = std::str::from_utf8(bytes) else {
            return;
        };
        let s = s.trim();
        if s.is_empty() {
            return;
        }
        let Ok(value) = serde_json::from_str::<serde_json::Value>(s) else {
            return;
        };
        let _ = parse_codex_record(&value, "fuzz-session", 0, blobs());
    }

    /// Mirrors the Gemini CLI tailer's per-line path: UTF-8 validate → trim →
    /// JSON parse → [`parse_gemini_record`]. Must never panic.
    pub fn fuzz_parse_gemini_line(bytes: &[u8]) {
        let Ok(s) = std::str::from_utf8(bytes) else {
            return;
        };
        let s = s.trim();
        if s.is_empty() {
            return;
        }
        let Ok(value) = serde_json::from_str::<serde_json::Value>(s) else {
            return;
        };
        let _ = parse_gemini_record(&value, "fuzz-session", 0, blobs());
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use std::io::Write;

    /// A fixed session start (2026-07-02T06:14:40.000Z) so timestamps derive
    /// small, stable, readable `ts_ms` values for snapshots.
    const STARTED: i64 = 1_782_972_880_000;
    const SID: &str = "test-session-id";

    fn iso(s: &str) -> i64 {
        ts_ms_from_iso(s, STARTED).expect("fixture timestamps must parse")
    }

    fn parse(value: &Value, ts_ms: i64) -> ParsedRecord {
        let tmp = tempfile::TempDir::new().unwrap();
        let blobs = BlobStore::new(tmp.path().join("blobs"));
        parse_record(value, SID, ts_ms, &blobs)
    }

    /// Serialize a parsed record's events (and model/usage when present) as
    /// pretty JSON for a stable insta snapshot.
    fn snap(pr: &ParsedRecord) -> String {
        serde_json::to_string_pretty(&serde_json::json!({
            "events": pr.events,
            "is_assistant_message": pr.is_assistant_message,
        }))
        .unwrap()
    }

    fn rec(json: &str) -> Value {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn parse_user_text_prompt() {
        let v = rec(r#"{"type":"user","isSidechain":false,"isMeta":false,
            "message":{"role":"user","content":"Please list the files in the repo and show Cargo.toml."},
            "timestamp":"2026-07-02T06:14:40.699Z","cwd":"/tmp/work","sessionId":"s"}"#);
        let pr = parse(&v, iso("2026-07-02T06:14:40.699Z"));
        insta::assert_snapshot!(snap(&pr));
    }

    #[test]
    fn parse_assistant_with_two_tool_uses() {
        let v = rec(r#"{"type":"assistant","isSidechain":false,"isMeta":false,
            "message":{"role":"assistant","model":"glm-5.2","content":[
              {"type":"thinking","thinking":"I'll list files then read Cargo.toml.","signature":""},
              {"type":"tool_use","id":"call_abc123","name":"Bash","input":{"command":"ls -la"}},
              {"type":"tool_use","id":"call_def456","name":"Read","input":{"file_path":"Cargo.toml"}}
            ],"usage":{"input_tokens":1200,"output_tokens":80}},
            "timestamp":"2026-07-02T06:14:41.500Z","cwd":"/tmp/work","sessionId":"s"}"#);
        let pr = parse(&v, iso("2026-07-02T06:14:41.500Z"));
        insta::assert_snapshot!(snap(&pr));
        // thinking + two tool calls = 3 events; assistant message flagged.
        assert_eq!(pr.events.len(), 3);
        assert!(pr.is_assistant_message);
        assert_eq!(pr.events[0].kind, EventKind::Thinking);
        assert_eq!(pr.events[1].kind, EventKind::ToolCall);
        assert_eq!(pr.events[2].kind, EventKind::ToolCall);
    }

    #[test]
    fn parse_user_with_two_tool_results_one_error() {
        let v = rec(r#"{"type":"user","isSidechain":false,"isMeta":false,
            "message":{"role":"user","content":[
              {"type":"tool_result","tool_use_id":"call_abc123","content":"total 0","is_error":false},
              {"type":"tool_result","tool_use_id":"call_def456","content":"Error: file not found","is_error":true}
            ]},
            "timestamp":"2026-07-02T06:14:42.800Z","cwd":"/tmp/work","sessionId":"s"}"#);
        let pr = parse(&v, iso("2026-07-02T06:14:42.800Z"));
        insta::assert_snapshot!(snap(&pr));
        assert_eq!(pr.events.len(), 2);
        assert_eq!(pr.events[0].kind, EventKind::ToolResult);
        assert_eq!(pr.events[1].kind, EventKind::ToolResult);
        // correlate_key == tool_use_id in each body.
        assert_eq!(
            pr.events[0].body_json.as_ref().unwrap()["correlate_key"],
            "call_abc123"
        );
        assert!(pr.events[1].body_json.as_ref().unwrap()["is_error"]
            .as_bool()
            .unwrap());
    }

    #[test]
    fn parse_assistant_followup_with_model_usage() {
        let v = rec(r#"{"type":"assistant","isSidechain":false,"isMeta":false,
            "message":{"role":"assistant","model":"glm-5.2","content":[
              {"type":"text","text":"The repo is empty and Cargo.toml is missing."}
            ],"usage":{"input_tokens":1500,"output_tokens":40,"cache_read_input_tokens":300}},
            "timestamp":"2026-07-02T06:14:43.100Z","cwd":"/tmp/work","sessionId":"s"}"#);
        let pr = parse(&v, iso("2026-07-02T06:14:43.100Z"));
        insta::assert_snapshot!(snap(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
        // The tailer collects model/usage from the message; exercise that path.
        let mut acc = OutcomeAcc::default();
        acc.note_assistant(v.get("message").unwrap());
        assert_eq!(acc.model.as_deref(), Some("glm-5.2"));
        assert_eq!(acc.usage_json.as_ref().unwrap()["output_tokens"], 40);
    }

    #[test]
    fn parse_skips_unknown_type() {
        let v = rec(r#"{"type":"system","subtype":"init","cwd":"/tmp/work","sessionId":"s"}"#);
        let pr = parse(&v, 0);
        assert!(pr.events.is_empty());
        assert!(!pr.is_assistant_message);
    }

    #[test]
    fn parse_skips_non_object_value() {
        // A malformed line that parsed as a JSON array/null produces no events.
        for v in [rec("[]"), rec("null"), rec("\"oops\"")] {
            assert!(
                parse(&v, 0).events.is_empty(),
                "non-object must yield no events"
            );
        }
    }

    #[test]
    fn parse_skips_is_sidechain() {
        let v = rec(r#"{"type":"assistant","isSidechain":true,"isMeta":false,
            "message":{"role":"assistant","content":[{"type":"text","text":"subagent"}]},
            "timestamp":"2026-07-02T06:14:41.000Z","cwd":"/tmp/work","sessionId":"s"}"#);
        assert!(parse(&v, 0).events.is_empty());
    }

    #[test]
    fn parse_skips_is_meta() {
        let v = rec(r#"{"type":"user","isSidechain":false,"isMeta":true,
            "message":{"role":"user","content":"<local-command-caveat>system-reminder</local-command-caveat>"},
            "timestamp":"2026-07-02T06:14:40.600Z","cwd":"/tmp/work","sessionId":"s"}"#);
        assert!(parse(&v, 0).events.is_empty());
    }

    #[test]
    fn parse_256kib_spills_to_blob() {
        let big = "x".repeat(SPILLOVER_BYTES + 1024);
        let v = rec(&format!(
            r#"{{"type":"user","isSidechain":false,"isMeta":false,
            "message":{{"role":"user","content":{}}},
            "timestamp":"2026-07-02T06:14:40.699Z","cwd":"/tmp/work","sessionId":"s"}}"#,
            serde_json::Value::String(big)
        ));
        let tmp = tempfile::TempDir::new().unwrap();
        let blobs = BlobStore::new(tmp.path().join("blobs"));
        let pr = parse_record(&v, SID, 699, &blobs);
        let ev = &pr.events[0];
        assert!(ev.blob_hash.is_some(), "large payload must spill to a blob");
        let hash = ev.blob_hash.as_ref().unwrap();
        assert_eq!(ev.body_json.as_ref().unwrap()["overflow"], true);
        assert_eq!(ev.body_json.as_ref().unwrap()["encoding"], "blob");
        // The blob round-trips to the serialized body (a JSON object with the text).
        let raw = blobs.get(hash).unwrap();
        let body: Value = serde_json::from_slice(&raw).unwrap();
        assert_eq!(body["text"].as_str().unwrap().len(), SPILLOVER_BYTES + 1024);
    }

    #[test]
    fn slugify_replaces_slash_and_dot() {
        assert_eq!(
            slugify(Path::new("/home/saadman/switch")),
            "-home-saadman-switch"
        );
        assert_eq!(
            slugify(Path::new("/home/saadman/switch/.claude/worktrees/x")),
            "-home-saadman-switch--claude-worktrees-x"
        );
        assert_eq!(slugify(Path::new("C:\\Users\\me")), "C:-Users-me");
    }

    #[test]
    fn select_detects_claude_basename() {
        assert!(is_claude_code(&["claude".into()]));
        assert!(is_claude_code(&["/usr/local/bin/claude".into()]));
        assert!(is_claude_code(&["C:\\Apps\\claude.exe".into()]));
        assert!(!is_claude_code(&["python3".into()]));
        assert!(!is_claude_code(&[]));
        // select returns a Claude adapter for claude, None for a generic command.
        assert!(select(&["claude".into()], Path::new("/tmp")).is_some());
        assert!(select(&["python3".into()], Path::new("/tmp")).is_none());
    }

    #[test]
    fn ts_ms_from_iso_is_relative_and_clamped() {
        assert_eq!(
            ts_ms_from_iso("2026-07-02T06:14:40.699Z", STARTED),
            Some(699)
        );
        assert_eq!(ts_ms_from_iso("2026-07-02T06:14:40.000Z", STARTED), Some(0));
        // A timestamp before the session start clamps to 0 (no negative ts_ms).
        assert_eq!(ts_ms_from_iso("2026-07-02T06:14:39.000Z", STARTED), Some(0));
        assert!(ts_ms_from_iso("not-a-date", STARTED).is_none());
    }

    // --- tailer behavior (real threads, temp HOME) -----------------------

    /// A self-contained adapter spawn: temp HOME + cwd, a stop flag, and the
    /// slug dir pre-created. The transcript is written *after* spawn (see
    /// [`write_transcript`]) so it is correctly seen as NEW since session start —
    /// mirroring real usage where Claude writes its transcript lazily, after
    /// `hh run` has launched it. Returns the handle so the test can drain then
    /// join.
    fn spawn_with(home: &Path, cwd: &Path) -> (AdapterHandle, std::sync::Arc<AtomicBool>, PathBuf) {
        let slug_dir = home.join(".claude").join("projects").join(slugify(cwd));
        std::fs::create_dir_all(&slug_dir).unwrap();
        let stop = std::sync::Arc::new(AtomicBool::new(false));
        let blobs = std::sync::Arc::new(BlobStore::new(home.join("blobs")));
        let ctx = AdapterContext {
            session_id: SID.to_string(),
            started_at_unix_ms: STARTED,
            cwd: cwd.to_path_buf(),
            command: vec!["claude".into()],
            blobs,
            stop: std::sync::Arc::clone(&stop),
            projects_dir: Some(home.join(".claude").join("projects")),
        };
        let handle = Box::new(ClaudeAdapter).spawn(ctx).expect("spawn adapter");
        // Let the tailer take its preexisting-file snapshot before we write, so the
        // transcript is seen as created-during-the-session (50 ms is a safe margin
        // over the snapshot's single read_dir).
        std::thread::sleep(Duration::from_millis(50));
        (handle, stop, slug_dir)
    }

    /// Write a transcript file into a slug dir (the "appears during the session"
    /// step of a tailer test).
    fn write_transcript(slug_dir: &Path, name: &str, content: &str) -> PathBuf {
        let path = slug_dir.join(name);
        std::fs::write(&path, content).unwrap();
        path
    }

    /// Drain `handle.events` until EOF, collecting events by kind.
    fn drain(events: &mpsc::Receiver<Event>) -> Vec<Event> {
        let mut out = Vec::new();
        while let Ok(ev) = events.recv() {
            out.push(ev);
        }
        out
    }

    const FIXTURE: &str = "\
{\"type\":\"system\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\",\"timestamp\":\"2026-07-02T06:14:40.500Z\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":true,\"message\":{\"role\":\"user\",\"content\":\"caveat\"},\"timestamp\":\"2026-07-02T06:14:40.600Z\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"hello\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\"}
{\"type\":\"assistant\",\"isSidechain\":true,\"isMeta\":false,\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"side\"}]},\"timestamp\":\"2026-07-02T06:14:41.000Z\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\"}
{\"type\":\"assistant\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"assistant\",\"model\":\"glm-5.2\",\"content\":[{\"type\":\"tool_use\",\"id\":\"call_1\",\"name\":\"Bash\",\"input\":{\"command\":\"ls\"}}]},\"timestamp\":\"2026-07-02T06:14:41.500Z\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"call_1\",\"content\":\"ok\",\"is_error\":false}]},\"timestamp\":\"2026-07-02T06:14:42.800Z\",\"cwd\":\"/tmp/work\",\"sessionId\":\"s\"}
";

    #[test]
    fn tailer_parses_fixture_and_skips_filtered_records() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/work");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        // Transcript appears mid-session (after the tailer snapshotted an empty
        // slug dir) — the realistic lazy-creation case the locate fix targets.
        write_transcript(&slug_dir, "session.jsonl", FIXTURE);
        // Give the tailer a poll cycle to find + parse it, then stop + drain.
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        // system + isMeta + isSidechain skipped → user_message + tool_call + tool_result.
        let kinds: Vec<_> = events.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![
                EventKind::UserMessage,
                EventKind::ToolCall,
                EventKind::ToolResult
            ]
        );
    }

    /// New-format Claude Code transcript (regression fixture, generation 2):
    /// recent Claude versions add top-level `mode` / `permissionMode` /
    /// `fileHistorySnapshot` fields and — critically — do **not** put `cwd` on
    /// the early `system`/meta records. The locate logic must scan past the
    /// cwd-less records to the first cwd-bearing one, and `parse_record` must
    /// tolerate the new fields. This is the format the "silently recorded 0
    /// steps" sessions were actually writing, so it is the load-bearing fixture
    /// for the adapter fix.
    const FIXTURE_NEW_FORMAT: &str = "\
{\"type\":\"system\",\"subtype\":\"init\",\"sessionId\":\"s\",\"timestamp\":\"2026-07-02T06:14:40.500Z\",\"mode\":\"default\",\"permissionMode\":\"default\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":true,\"message\":{\"role\":\"user\",\"content\":\"caveat\"},\"timestamp\":\"2026-07-02T06:14:40.600Z\",\"mode\":\"default\",\"permissionMode\":\"default\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"hello\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/work-new\",\"sessionId\":\"s\",\"mode\":\"default\",\"permissionMode\":\"default\",\"fileHistorySnapshot\":{}}
{\"type\":\"assistant\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"assistant\",\"model\":\"glm-5.2\",\"content\":[{\"type\":\"tool_use\",\"id\":\"call_1\",\"name\":\"Bash\",\"input\":{\"command\":\"ls\"}}]},\"timestamp\":\"2026-07-02T06:14:41.500Z\",\"cwd\":\"/tmp/work-new\",\"sessionId\":\"s\",\"mode\":\"default\",\"permissionMode\":\"default\"}
{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":[{\"type\":\"tool_result\",\"tool_use_id\":\"call_1\",\"content\":\"ok\",\"is_error\":false}]},\"timestamp\":\"2026-07-02T06:14:42.800Z\",\"cwd\":\"/tmp/work-new\",\"sessionId\":\"s\",\"mode\":\"default\",\"permissionMode\":\"default\"}
";

    /// `first_record_cwd_state` must scan *past* cwd-less records (the new format
    /// puts no `cwd` on `system`/meta lines) to the first cwd-bearing one, then
    /// classify it. A regression guard for the "no-early-cwd" case: a naive
    /// "look at the first record" check would return `None` forever and the
    /// locate loop would never accept the transcript → 0 recorded steps.
    #[test]
    fn first_record_cwd_state_skips_cwdless_records() {
        let tmp = tempfile::tempdir().unwrap();
        let f = tmp.path().join("new.jsonl");
        std::fs::write(&f, FIXTURE_NEW_FORMAT).unwrap();
        // The first cwd-bearing record carries /tmp/work-new → Matches.
        assert_eq!(
            first_record_cwd_state(&f, Path::new("/tmp/work-new")),
            CwdState::Matches
        );
        // A different session cwd → Different (rejected, not mis-accepted).
        assert_eq!(
            first_record_cwd_state(&f, Path::new("/tmp/other")),
            CwdState::Different
        );
    }

    /// End-to-end tailer regression against the new-format fixture: the adapter
    /// must locate the transcript (cwd appears only on record 3, not record 1)
    /// and parse the same three events as the original fixture. Locks that the
    /// new top-level fields and the cwd-less head do not silently drop the
    /// session to 0 steps.
    #[test]
    fn tailer_parses_new_format_fixture_with_no_early_cwd() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/work-new");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        write_transcript(&slug_dir, "session.jsonl", FIXTURE_NEW_FORMAT);
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        // Same three events as the original fixture: system/meta skipped, the
        // cwd-less head does not prevent locate from accepting the file.
        let kinds: Vec<_> = events.iter().map(|e| e.kind).collect();
        assert_eq!(
            kinds,
            vec![
                EventKind::UserMessage,
                EventKind::ToolCall,
                EventKind::ToolResult
            ],
            "new-format fixture must parse the same events as the original"
        );
    }

    #[test]
    fn tailer_finds_file_late() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/work-late");
        // Pre-create the slug dir but write the file *after* spawning, so the
        // adapter must keep polling until it appears (no fixed timeout).
        std::fs::create_dir_all(
            home.path()
                .join(".claude")
                .join("projects")
                .join(slugify(cwd)),
        )
        .unwrap();
        let stop = std::sync::Arc::new(AtomicBool::new(false));
        let blobs = std::sync::Arc::new(BlobStore::new(home.path().join("blobs")));
        let ctx = AdapterContext {
            session_id: SID.to_string(),
            started_at_unix_ms: STARTED,
            cwd: cwd.to_path_buf(),
            command: vec!["claude".into()],
            blobs,
            stop: std::sync::Arc::clone(&stop),
            projects_dir: Some(home.path().join(".claude").join("projects")),
        };
        let handle = Box::new(ClaudeAdapter).spawn(ctx).expect("spawn");
        // Write the transcript after the adapter is already polling.
        std::thread::sleep(Duration::from_millis(150));
        std::fs::write(
            home
                .path()
                .join(".claude")
                .join("projects")
                .join(slugify(cwd))
                .join("late.jsonl"),
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"late\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/work-late\",\"sessionId\":\"s\"}\n",
        )
        .unwrap();
        std::thread::sleep(Duration::from_millis(150));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert_eq!(
            events.len(),
            1,
            "adapter should pick up the late-appearing file"
        );
        assert_eq!(events[0].kind, EventKind::UserMessage);
    }

    #[test]
    fn tailer_partial_last_line_retries() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/work-partial");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        // A file with one complete line plus a trailing partial (no newline),
        // written mid-session so the tailer sees it as new.
        let complete = "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"first\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/work-partial\",\"sessionId\":\"s\"}\n";
        let partial = "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"sec";
        let path = write_transcript(&slug_dir, "partial.jsonl", &format!("{complete}{partial}"));
        // Let the tailer find the file and read the complete line (partial held).
        std::thread::sleep(Duration::from_millis(250));
        // Append the rest of the partial line; it should now parse as a second event.
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&path)
            .unwrap();
        writeln!(f, "ond\"}}}}\n").unwrap();
        std::thread::sleep(Duration::from_millis(250));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        let contents: Vec<&str> = events
            .iter()
            .map(|e| e.body_json.as_ref().unwrap()["text"].as_str().unwrap())
            .collect();
        assert_eq!(
            contents,
            vec!["first", "second"],
            "partial line must be retried until complete"
        );
    }

    #[test]
    fn tailer_fallback_scan_by_cwd() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/work-fallback");
        // Put the transcript under a *wrong* slug dir (not slugify(cwd)) so the
        // slug lookup misses and the fallback scan by cwd must find it.
        let wrong_slug = "-totally-wrong-slug";
        let wrong_dir = home
            .path()
            .join(".claude")
            .join("projects")
            .join(wrong_slug);
        std::fs::create_dir_all(&wrong_dir).unwrap();
        let stop = std::sync::Arc::new(AtomicBool::new(false));
        let blobs = std::sync::Arc::new(BlobStore::new(home.path().join("blobs")));
        let ctx = AdapterContext {
            session_id: SID.to_string(),
            started_at_unix_ms: STARTED,
            cwd: cwd.to_path_buf(),
            command: vec!["claude".into()],
            blobs,
            stop: std::sync::Arc::clone(&stop),
            projects_dir: Some(home.path().join(".claude").join("projects")),
        };
        let handle = Box::new(ClaudeAdapter).spawn(ctx).expect("spawn");
        // Write the transcript under the wrong slug AFTER spawn (so it is seen as
        // new) and after the preexisting snapshot (50 ms margin).
        std::thread::sleep(Duration::from_millis(50));
        std::fs::write(
            wrong_dir.join("fb.jsonl"),
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"fb\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/work-fallback\",\"sessionId\":\"s\"}\n",
        )
        .unwrap();
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert_eq!(
            events.len(),
            1,
            "fallback scan should locate the transcript by cwd"
        );
        assert_eq!(events[0].kind, EventKind::UserMessage);
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Active);
    }

    #[test]
    fn tailer_degrades_when_projects_dir_missing() {
        // No ~/.claude/projects anywhere: HOME points at an empty temp dir.
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/nowhere");
        let stop = std::sync::Arc::new(AtomicBool::new(false));
        let blobs = std::sync::Arc::new(BlobStore::new(home.path().join("blobs")));
        let ctx = AdapterContext {
            session_id: SID.to_string(),
            started_at_unix_ms: STARTED,
            cwd: cwd.to_path_buf(),
            command: vec!["claude".into()],
            blobs,
            stop: std::sync::Arc::clone(&stop),
            projects_dir: Some(home.path().join(".claude").join("projects")),
        };
        let handle = Box::new(ClaudeAdapter).spawn(ctx).expect("spawn");
        let events = drain(&handle.events);
        assert!(events.is_empty(), "no projects dir → no events");
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Degraded);
        // Degraded outcomes carry an actionable reason for the recorder to print
        // after the child exits (FR-1.5), not a bare status with no explanation.
        assert!(
            outcome.degrade_reason.is_some(),
            "degraded outcome must carry a degrade_reason"
        );
    }

    #[test]
    fn tailer_degrades_when_transcript_never_appears() {
        // Projects dir exists, slug dir exists, but no transcript is ever written:
        // the tailer must poll until stop, then return Degraded with a reason
        // (the "0 steps, status=ok" failure mode — previously the 3 s deadline
        // degraded silently mid-session under the agent's TUI).
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/no-transcript");
        let (handle, stop, _slug_dir) = spawn_with(home.path(), cwd);
        // Never write a transcript. Stop almost immediately.
        std::thread::sleep(Duration::from_millis(80));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert!(events.is_empty(), "no transcript ever → no events");
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Degraded);
        assert!(
            outcome.degrade_reason.is_some(),
            "degraded outcome must carry a degrade_reason pointing at hh doctor"
        );
        assert!(
            outcome
                .degrade_reason
                .as_deref()
                .unwrap()
                .contains("hh doctor"),
            "degrade reason should suggest running `hh doctor`"
        );
    }

    #[test]
    fn tailer_ignores_preexisting_transcript() {
        // A transcript that predates `hh run` belongs to a *different* session and
        // must NOT be tailed, even if it matches cwd (concurrent-session guard).
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/concurrent");
        let slug_dir = home
            .path()
            .join(".claude")
            .join("projects")
            .join(slugify(cwd));
        std::fs::create_dir_all(&slug_dir).unwrap();
        // Pre-existing (concurrent session's) transcript, written BEFORE spawn.
        std::fs::write(
            slug_dir.join("old.jsonl"),
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"not mine\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/concurrent\",\"sessionId\":\"other\"}\n",
        )
        .unwrap();
        let (handle, stop, _slug) = spawn_with(home.path(), cwd);
        // No new transcript is ever written for our session.
        std::thread::sleep(Duration::from_millis(80));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert!(
            events.is_empty(),
            "a pre-existing transcript from another session must not be tailed"
        );
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Degraded);
    }

    /// A candidate path that is a directory (the same-stem-dir issue: Claude
    /// writes both `<uuid>.jsonl` and a `<uuid>/` directory) is classified as
    /// [`CwdState::Directory`] and rejected, not re-polled forever (which would
    /// loop on the `read_to_string` io error as `None` and silently degrade).
    #[test]
    fn first_record_cwd_state_rejects_directory() {
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().join("2457c4b0-is-a-dir");
        std::fs::create_dir_all(&dir).unwrap();
        assert_eq!(
            first_record_cwd_state(&dir, Path::new("/tmp/anything")),
            CwdState::Directory,
            "a directory candidate must be rejected, not re-polled"
        );
    }

    /// A same-stem directory next to the real `.jsonl` transcript must not break
    /// discovery: the `.jsonl` extension filter skips the directory, the file is
    /// selected by cwd, and events are parsed normally. Regression guard for the
    /// issue the user flagged (a `<uuid>/` dir beside `<uuid>.jsonl`).
    #[test]
    fn tailer_ignores_same_stem_directory_beside_jsonl() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/same-stem");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        // The real transcript.
        write_transcript(
            &slug_dir,
            "abc123.jsonl",
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"hi\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/same-stem\",\"sessionId\":\"s\"}\n",
        );
        // A same-stem directory (no .jsonl extension) sitting beside it — must
        // be skipped by the extension filter, not break the dir iteration.
        std::fs::create_dir_all(slug_dir.join("abc123")).unwrap();
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert_eq!(
            events.len(),
            1,
            "the same-stem directory must not prevent discovering the .jsonl"
        );
        assert_eq!(events[0].kind, EventKind::UserMessage);
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Active);
    }

    /// A transcript that is found (cwd matches) but yields zero events — here
    /// because the only cwd-bearing record is `isMeta` (skipped by the parser) —
    /// must degrade with the specific "0 records parsed" reason, NOT finalize as
    /// `active` with 0 steps (the silent-breakage symptom). The reason carries
    /// the line count so the failure is a one-line diagnosis.
    #[test]
    fn tailer_degrades_when_zero_records_parsed() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/zero-records");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        // cwd-bearing so it is selected, but isMeta so parse_record skips it →
        // 0 events. Mirrors a format drift where the parser recognizes nothing.
        write_transcript(
            &slug_dir,
            "empty.jsonl",
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":true,\"message\":{\"role\":\"user\",\"content\":\"caveat\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/zero-records\",\"sessionId\":\"s\"}\n",
        );
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert!(events.is_empty(), "isMeta record yields no events");
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(
            outcome.status,
            AdapterStatus::Degraded,
            "0 records parsed must degrade, not report active with 0 steps"
        );
        let reason = outcome.degrade_reason.as_deref().unwrap();
        assert!(
            reason.contains("0 records parsed"),
            "reason must be the specific '0 records parsed' string: {reason}"
        );
        assert!(
            reason.contains("read 1 line"),
            "reason must carry the line count: {reason}"
        );
    }

    /// A transcript whose first JSON line is malformed records the first parse
    /// error (line + message) in the degrade reason, so a format drift is a
    /// one-line diagnosis instead of a silent skip.
    #[test]
    fn tailer_degrade_reason_records_first_parse_error() {
        let home = tempfile::TempDir::new().unwrap();
        let cwd = Path::new("/tmp/parse-err");
        let (handle, stop, slug_dir) = spawn_with(home.path(), cwd);
        // A valid cwd-bearing user record (so it is selected) followed by a
        // malformed line. The valid record yields 1 event → Active, so to
        // exercise the parse-error-in-reason path we make the ONLY line a
        // cwd-bearing record that is unparseable JSON. But cwd-verification
        // needs parseable JSON to read `cwd`... so instead place a valid
        // selected record then a broken one: the file is selected on the valid
        // record, the broken line is skipped with a debug log, and since the
        // valid record produced an event the outcome is Active. The parse-error
        // tracking is therefore asserted at the unit level below instead.
        write_transcript(
            &slug_dir,
            "broken.jsonl",
            "{\"type\":\"user\",\"isSidechain\":false,\"isMeta\":false,\"message\":{\"role\":\"user\",\"content\":\"ok\"},\"timestamp\":\"2026-07-02T06:14:40.699Z\",\"cwd\":\"/tmp/parse-err\",\"sessionId\":\"s\"}\n{not valid json\n",
        );
        std::thread::sleep(Duration::from_millis(300));
        stop.store(true, Ordering::Release);
        let events = drain(&handle.events);
        assert_eq!(
            events.len(),
            1,
            "the valid record parses; the broken line is skipped"
        );
        let outcome = handle.outcome.join().expect("tailer thread");
        assert_eq!(outcome.status, AdapterStatus::Active);
    }

    /// `locate_failure_reason` produces the specific "no new transcript
    /// appeared" string when nothing was seen, and the "N candidates but none
    /// matched cwd" string (with mismatch/directory counts) when candidates
    /// were rejected. Locks the one-line-diagnosis contract for degraded
    /// sessions without spinning a real tailer.
    #[test]
    fn locate_failure_reason_is_specific() {
        // No candidates appeared at all.
        let empty = DiscoveryDiag {
            projects: Some(PathBuf::from("/home/me/.claude/projects")),
            slug: Some("-home-me-work".into()),
            slug_dir: Some(PathBuf::from("/home/me/.claude/projects/-home-me-work")),
            cwd: Some(PathBuf::from("/home/me/work")),
            ..Default::default()
        };
        let r = locate_failure_reason(&empty);
        assert!(r.contains("no jsonl matched cwd slug -home-me-work"), "{r}");
        assert!(r.contains("no new transcript appeared"), "{r}");
        assert!(
            r.contains("looked in /home/me/.claude/projects/-home-me-work"),
            "{r}"
        );

        // Candidates appeared but none matched cwd; one was a directory.
        let mut seen = std::collections::HashSet::new();
        seen.insert(PathBuf::from(
            "/home/me/.claude/projects/-home-me-work/a.jsonl",
        ));
        let with_cands = DiscoveryDiag {
            projects: Some(PathBuf::from("/home/me/.claude/projects")),
            slug: Some("-home-me-work".into()),
            slug_dir: Some(PathBuf::from("/home/me/.claude/projects/-home-me-work")),
            cwd: Some(PathBuf::from("/home/me/work")),
            new_candidates: seen,
            cwd_mismatches: vec![PathBuf::from(
                "/home/me/.claude/projects/-home-me-work/a.jsonl",
            )],
            directories: vec![PathBuf::from(
                "/home/me/.claude/projects/-home-me-work/b.jsonl",
            )],
        };
        let r = locate_failure_reason(&with_cands);
        assert!(r.contains("1 new candidate(s)"), "{r}");
        assert!(r.contains("1 rejected for a different cwd"), "{r}");
        assert!(r.contains("1 candidate(s) were directories"), "{r}");
    }

    // -----------------------------------------------------------------------
    // Codex CLI parser tests
    // -----------------------------------------------------------------------

    fn parse_codex(value: &Value, ts_ms: i64) -> ParsedRecord {
        let tmp = tempfile::TempDir::new().unwrap();
        let blobs = BlobStore::new(tmp.path().join("blobs"));
        parse_codex_record(value, SID, ts_ms, &blobs)
    }

    fn snap_codex(pr: &ParsedRecord) -> String {
        serde_json::to_string_pretty(&serde_json::json!({
            "events": pr.events,
            "is_assistant_message": pr.is_assistant_message,
        }))
        .unwrap()
    }

    fn codex_rec(json: &str) -> Value {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn codex_parse_user_message() {
        let v = codex_rec(
            r#"{"type":"event_msg","timestamp":"2026-07-02T06:14:40.699Z","payload":{"type":"user_message","content":[{"text":"hello"}]}}"#,
        );
        let pr = parse_codex(&v, iso("2026-07-02T06:14:40.699Z"));
        insta::assert_snapshot!(snap_codex(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::UserMessage);
    }

    #[test]
    fn codex_parse_agent_message() {
        let v = codex_rec(
            r#"{"type":"event_msg","timestamp":"2026-07-02T06:14:41.500Z","payload":{"type":"agent_message","content":[{"text":"I can help with that"}]}}"#,
        );
        let pr = parse_codex(&v, iso("2026-07-02T06:14:41.500Z"));
        insta::assert_snapshot!(snap_codex(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
        assert!(pr.is_assistant_message);
    }

    #[test]
    fn codex_parse_response_item_message() {
        let v = codex_rec(
            r#"{"type":"response_item","timestamp":"2026-07-02T06:14:41.500Z","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Here is the solution"}]}}"#,
        );
        let pr = parse_codex(&v, iso("2026-07-02T06:14:41.500Z"));
        insta::assert_snapshot!(snap_codex(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
    }

    #[test]
    fn codex_parse_function_call_and_output() {
        let v = codex_rec(
            r#"{"type":"response_item","timestamp":"2026-07-02T06:14:42.000Z","payload":{"type":"function_call","call_id":"call_1","name":"Bash","arguments":"{\"command\":\"ls\"}"}}"#,
        );
        let pr = parse_codex(&v, iso("2026-07-02T06:14:42.000Z"));
        insta::assert_snapshot!(snap_codex(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::ToolCall);
        assert_eq!(
            pr.events[0].body_json.as_ref().unwrap()["correlate_key"],
            "call_1"
        );

        let v2 = codex_rec(
            r#"{"type":"response_item","timestamp":"2026-07-02T06:14:43.000Z","payload":{"type":"function_call_output","call_id":"call_1","output":"total 42"}}"#,
        );
        let pr2 = parse_codex(&v2, iso("2026-07-02T06:14:43.000Z"));
        assert_eq!(pr2.events.len(), 1);
        assert_eq!(pr2.events[0].kind, EventKind::ToolResult);
        assert_eq!(
            pr2.events[0].body_json.as_ref().unwrap()["correlate_key"],
            "call_1"
        );
    }

    #[test]
    fn codex_parse_reasoning() {
        let v = codex_rec(
            r#"{"type":"response_item","timestamp":"2026-07-02T06:14:41.000Z","payload":{"type":"reasoning","summary":[],"content":null,"encrypted_content":"gAAAAABp5lf5..."}}"#,
        );
        let pr = parse_codex(&v, iso("2026-07-02T06:14:41.000Z"));
        insta::assert_snapshot!(snap_codex(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::Thinking);
    }

    #[test]
    fn codex_parse_skips_session_meta() {
        let v = codex_rec(
            r#"{"type":"session_meta","timestamp":"2026-07-02T06:14:40.000Z","payload":{"id":"abc","cwd":"/tmp","originator":"codex-tui"}}"#,
        );
        let pr = parse_codex(&v, 0);
        assert!(pr.events.is_empty());
    }

    #[test]
    fn codex_parse_skips_unknown_type() {
        let v = codex_rec(
            r#"{"type":"unknown_type","timestamp":"2026-07-02T06:14:40.000Z","payload":{}}"#,
        );
        let pr = parse_codex(&v, 0);
        assert!(pr.events.is_empty());
    }

    #[test]
    fn codex_parse_non_object_value() {
        for v in [codex_rec("[]"), codex_rec("null"), codex_rec("\"oops\"")] {
            assert!(parse_codex(&v, 0).events.is_empty());
        }
    }

    // -----------------------------------------------------------------------
    // Gemini CLI parser tests
    // -----------------------------------------------------------------------

    fn parse_gemini(value: &Value, ts_ms: i64) -> ParsedRecord {
        let tmp = tempfile::TempDir::new().unwrap();
        let blobs = BlobStore::new(tmp.path().join("blobs"));
        parse_gemini_record(value, SID, ts_ms, &blobs)
    }

    fn snap_gemini(pr: &ParsedRecord) -> String {
        serde_json::to_string_pretty(&serde_json::json!({
            "events": pr.events,
            "is_assistant_message": pr.is_assistant_message,
        }))
        .unwrap()
    }

    fn gemini_rec(json: &str) -> Value {
        serde_json::from_str(json).unwrap()
    }

    #[test]
    fn gemini_parse_user_message() {
        let v = gemini_rec(
            r#"{"type":"user","id":"msg1","timestamp":"2026-07-02T06:14:40.699Z","content":[{"text":"hello"}]}"#,
        );
        let pr = parse_gemini(&v, iso("2026-07-02T06:14:40.699Z"));
        insta::assert_snapshot!(snap_gemini(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::UserMessage);
    }

    #[test]
    fn gemini_parse_agent_message() {
        let v = gemini_rec(
            r#"{"type":"gemini","id":"msg2","timestamp":"2026-07-02T06:14:41.500Z","content":[{"text":"Hi! How can I help?"}],"model":"gemini-2.5-pro"}"#,
        );
        let pr = parse_gemini(&v, iso("2026-07-02T06:14:41.500Z"));
        insta::assert_snapshot!(snap_gemini(&pr));
        assert_eq!(pr.events.len(), 1);
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
    }

    #[test]
    fn gemini_parse_with_tool_calls() {
        let v = gemini_rec(
            r#"{"type":"gemini","id":"msg3","timestamp":"2026-07-02T06:14:42.000Z","content":[{"text":"Let me check"}],"toolCalls":[{"id":"tc_1","name":"Bash","input":{"command":"ls"}}]}"#,
        );
        let pr = parse_gemini(&v, iso("2026-07-02T06:14:42.000Z"));
        insta::assert_snapshot!(snap_gemini(&pr));
        assert_eq!(pr.events.len(), 2); // agent_message + tool_call
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
        assert_eq!(pr.events[1].kind, EventKind::ToolCall);
        assert_eq!(
            pr.events[1].body_json.as_ref().unwrap()["correlate_key"],
            "tc_1"
        );
    }

    #[test]
    fn gemini_parse_with_thoughts() {
        let v = gemini_rec(
            r#"{"type":"gemini","id":"msg4","timestamp":"2026-07-02T06:14:41.000Z","content":[{"text":"answer"}],"thoughts":[{"text":"I need to think about this"}]}"#,
        );
        let pr = parse_gemini(&v, iso("2026-07-02T06:14:41.000Z"));
        insta::assert_snapshot!(snap_gemini(&pr));
        assert_eq!(pr.events.len(), 2); // agent_message + thinking
        assert_eq!(pr.events[0].kind, EventKind::AgentMessage);
        assert_eq!(pr.events[1].kind, EventKind::Thinking);
    }

    #[test]
    fn gemini_parse_skips_session_metadata() {
        let v = gemini_rec(
            r#"{"type":"session_metadata","sessionId":"abc","projectHash":"xyz","startTime":"2026-07-02T06:14:40.000Z"}"#,
        );
        let pr = parse_gemini(&v, 0);
        assert!(pr.events.is_empty());
    }

    #[test]
    fn gemini_parse_skips_message_update() {
        let v = gemini_rec(
            r#"{"type":"message_update","id":"msg2","timestamp":"2026-07-02T06:14:41.000Z","tokens":{"input":5,"output":4}}"#,
        );
        let pr = parse_gemini(&v, 0);
        assert!(pr.events.is_empty());
    }

    #[test]
    fn gemini_parse_skips_unknown_type() {
        let v = gemini_rec(r#"{"type":"unknown","id":"x","timestamp":"2026-07-02T06:14:40.000Z"}"#);
        let pr = parse_gemini(&v, 0);
        assert!(pr.events.is_empty());
    }

    #[test]
    fn gemini_parse_non_object_value() {
        for v in [gemini_rec("[]"), gemini_rec("null")] {
            assert!(parse_gemini(&v, 0).events.is_empty());
        }
    }

    // -----------------------------------------------------------------------
    // Detection tests for all adapters
    // -----------------------------------------------------------------------

    #[test]
    fn select_detects_all_adapters() {
        assert!(select(&["claude".into()], Path::new("/tmp")).is_some());
        assert!(select(&["claude-desktop".into()], Path::new("/tmp")).is_some());
        assert!(select(&["codex".into()], Path::new("/tmp")).is_some());
        assert!(select(&["gemini".into()], Path::new("/tmp")).is_some());
        assert!(select(&["python3".into()], Path::new("/tmp")).is_none());
    }

    #[test]
    fn is_claude_desktop_detects_basename() {
        assert!(is_claude_desktop(&["claude-desktop".into()]));
        assert!(is_claude_desktop(&["/usr/local/bin/claude-desktop".into()]));
        assert!(is_claude_desktop(&["claude-desktop.exe".into()]));
        assert!(!is_claude_desktop(&["claude".into()]));
        assert!(!is_claude_desktop(&["codex".into()]));
        assert!(!is_claude_desktop(&[]));
    }

    #[test]
    fn is_codex_cli_detects_basename() {
        assert!(is_codex_cli(&["codex".into()]));
        assert!(is_codex_cli(&["/usr/local/bin/codex".into()]));
        assert!(is_codex_cli(&["codex.exe".into()]));
        assert!(!is_codex_cli(&["claude".into()]));
        assert!(!is_codex_cli(&[]));
    }

    #[test]
    fn is_gemini_cli_detects_basename() {
        assert!(is_gemini_cli(&["gemini".into()]));
        assert!(is_gemini_cli(&["/usr/local/bin/gemini".into()]));
        assert!(is_gemini_cli(&["gemini.exe".into()]));
        assert!(!is_gemini_cli(&["claude".into()]));
        assert!(!is_gemini_cli(&[]));
    }

    #[test]
    fn resolve_override_accepts_all_adapters() {
        assert!(resolve_override("claude-code").is_some());
        assert!(resolve_override("claude-desktop").is_some());
        assert!(resolve_override("codex-cli").is_some());
        assert!(resolve_override("gemini-cli").is_some());
        assert!(resolve_override("unknown").is_none());
    }
}