attini 0.0.1

CLI coding agent that aims to be as autonomous as it can be, without ever leaving your control
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
//! Filesystem-backed session storage for the CLI agent
//! (`attini tell`).
//!
//! Each session lives under `.attini/{SESSION_NAME}/` relative to
//! the current working directory:
//!
//! - `LOCK` — exclusive lock file created with `O_EXCL` on open;
//!   contains `{"pid": i32, "started_at_unix_ms": u64}` of the
//!   holder. Removed on `Session::close` / `Drop`. Stale LOCKs
//!   (holder PID dead or file corrupted) are auto-recovered by
//!   one retry on the next `Session::open`.
//! - `conversation.jsonl` — append-only history. One JSON object
//!   per line, tagged by `kind`. User / assistant / tool records
//!   are the source of truth for reconstructing conversation
//!   context on subsequent invocations.
//! - `pending.json` — present iff the previous invocation
//!   suspended waiting for approval. Absent otherwise.

use std::fs::{self, File, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use nojson::{DisplayJson, Json, JsonFormatter, JsonParseError, RawJson};

use crate::sansio::deepseek::{ChatMessage, ToolCall};

/// Handle to an open session directory. Holds the LOCK file open
/// for the lifetime of this value; drop it via [`Session::close`]
/// to release the lock.
pub struct Session {
    dir: PathBuf,
    lock_path: PathBuf,
    _lock: File,
    conversation_path: PathBuf,
    pending_path: PathBuf,
    writer: File,
}

impl Session {
    /// Open (or create) the session directory for `name` under
    /// `.attini/` in the current working directory. Takes the LOCK
    /// via `O_EXCL` and writes the holder's PID / start time. If the
    /// LOCK is stale (corrupted or holder dead), one retry is
    /// attempted; otherwise returns `Err(AlreadyExists)` with a hint.
    pub fn open(name: &str) -> io::Result<Self> {
        let paths = session_paths(name)?;
        fs::create_dir_all(&paths.dir)?;
        // Layer 2 free-write zone. Errors here surface as Session::open
        // failure: scratchpad is a hard prerequisite of the patch tool's
        // always-allow rule, so `warn + skip` would leave the invariant
        // silently broken.
        fs::create_dir_all(&paths.scratchpad)?;
        let lock = acquire_lock_with_stale_retry(name, &paths.lock)?;
        let writer = OpenOptions::new()
            .create(true)
            .append(true)
            .open(&paths.conversation)?;
        Ok(Self {
            dir: paths.dir,
            lock_path: paths.lock,
            _lock: lock,
            conversation_path: paths.conversation,
            pending_path: paths.pending,
            writer,
        })
    }

    /// Release the lock and close file handles. Called from
    /// `Drop`, but callers can invoke explicitly to surface I/O
    /// errors from unlink.
    pub fn close(self) -> io::Result<()> {
        fs::remove_file(&self.lock_path)
    }

    pub fn dir(&self) -> &Path {
        &self.dir
    }

    /// Load every `ChatMessage` recorded in `conversation.jsonl`
    /// so far, in order. Unknown record kinds are skipped
    /// (forward-compat). Malformed lines abort the load with an
    /// error since a corrupt history is not safely recoverable.
    ///
    /// Note: this loader ignores any `summary` records. Callers that
    /// need compaction-aware loading should use
    /// [`Session::load_summaries`] plus
    /// [`Session::load_records_since_last_summary`] and combine the
    /// two themselves.
    pub fn load_conversation(&self) -> io::Result<Vec<ChatMessage>> {
        let file = match File::open(&self.conversation_path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => return Err(e),
        };
        let mut messages = Vec::new();
        for (i, line) in BufReader::new(file).lines().enumerate() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            match parse_conversation_line(&line) {
                Ok(Some(msg)) => messages.push(msg),
                Ok(None) => {}
                Err(e) => {
                    return Err(io::Error::other(format!(
                        "malformed conversation record at line {}: {e}",
                        i + 1
                    )));
                }
            }
        }
        Ok(messages)
    }

    /// Return every summary text ever written to
    /// `conversation.jsonl`, in time order. Callers concatenate
    /// these as system messages before real records. Missing file
    /// yields an empty vector.
    pub fn load_summaries(&self) -> io::Result<Vec<SummaryRecord>> {
        let file = match File::open(&self.conversation_path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
            Err(e) => return Err(e),
        };
        let mut summaries = Vec::new();
        for (i, line) in BufReader::new(file).lines().enumerate() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            match parse_summary_line(&line) {
                Ok(Some(s)) => summaries.push(s),
                Ok(None) => {}
                Err(e) => {
                    return Err(io::Error::other(format!(
                        "malformed conversation record at line {}: {e}",
                        i + 1
                    )));
                }
            }
        }
        Ok(summaries)
    }

    /// Return the real records (`user` / `assistant` / `tool`)
    /// whose `ts` is greater than the `cutoff_ts` of the newest
    /// summary. When there is no summary, every real record is
    /// returned.
    pub fn load_records_since_last_summary(&self) -> io::Result<Vec<ChatMessageWithTs>> {
        read_chat_message_with_ts(&self.conversation_path, false)
    }

    /// Latest `prompt_tokens` value recorded in `token_usage`
    /// records so far. Used by the compaction trigger to decide
    /// whether to summarise before the next invocation.
    pub fn latest_prompt_tokens(&self) -> io::Result<Option<u64>> {
        let file = match File::open(&self.conversation_path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e),
        };
        let mut latest: Option<u64> = None;
        for (i, line) in BufReader::new(file).lines().enumerate() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            match parse_prompt_tokens(&line) {
                Ok(Some(v)) => latest = Some(v),
                Ok(None) => {}
                Err(e) => {
                    return Err(io::Error::other(format!(
                        "malformed conversation record at line {}: {e}",
                        i + 1
                    )));
                }
            }
        }
        Ok(latest)
    }

    /// Reason recorded by the most recent `invocation_end` record, or
    /// `None` when the conversation has none yet (a fresh session).
    ///
    /// `attini approve` uses this to decide whether the previous
    /// invocation stopped somewhere it can pick back up: with a
    /// `TransportError` end it re-issues the identical request rather
    /// than appending a continuation message.
    pub fn last_invocation_end_reason(&self) -> io::Result<Option<InvocationEndReason>> {
        let file = match File::open(&self.conversation_path) {
            Ok(f) => f,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e),
        };
        let mut latest: Option<InvocationEndReason> = None;
        for (i, line) in BufReader::new(file).lines().enumerate() {
            let line = line?;
            if line.trim().is_empty() {
                continue;
            }
            match parse_invocation_end_reason(&line) {
                Ok(Some(reason)) => latest = Some(reason),
                Ok(None) => {}
                Err(e) => {
                    return Err(io::Error::other(format!(
                        "malformed conversation record at line {}: {e}",
                        i + 1
                    )));
                }
            }
        }
        Ok(latest)
    }

    pub fn conversation_path(&self) -> &Path {
        &self.conversation_path
    }

    pub fn pending_path(&self) -> &Path {
        &self.pending_path
    }

    /// Append a record to `conversation.jsonl` and flush.
    pub fn append(&mut self, record: &SessionRecord) -> io::Result<()> {
        let mut line = Json(record).to_string();
        line.push('\n');
        self.writer.write_all(line.as_bytes())?;
        self.writer.flush()
    }

    /// Write `pending.json` (overwriting any previous) as a JSON
    /// array of approval-blocked tool calls. The caller should
    /// follow up by exiting the process — the pending file signals
    /// to the next invocation that the agent loop is mid-turn.
    pub fn save_pending(&self, pending: &[Pending]) -> io::Result<()> {
        let content = Json(pending).to_string();
        fs::write(&self.pending_path, content)
    }

    /// Read `pending.json` if it exists. Returns the parked batch in
    /// array order (the order the tool calls appeared in the turn).
    pub fn load_pending(&self) -> io::Result<Option<Vec<Pending>>> {
        let text = match fs::read_to_string(&self.pending_path) {
            Ok(s) => s,
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
            Err(e) => return Err(e),
        };
        let json =
            RawJson::parse(&text).map_err(|e| io::Error::other(format!("pending.json: {e}")))?;
        Pending::from_json_array(json.value()).map(Some)
    }

    /// Remove `pending.json` after a resume has been applied.
    pub fn clear_pending(&self) -> io::Result<()> {
        match fs::remove_file(&self.pending_path) {
            Ok(()) => Ok(()),
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e),
        }
    }
}

impl Drop for Session {
    fn drop(&mut self) {
        // Best-effort unlock. Explicit `close()` returns errors;
        // Drop swallows them.
        let _ = fs::remove_file(&self.lock_path);
    }
}

/// Read conversation records as [`ChatMessageWithTs`] from a path
/// without acquiring the session LOCK. When `all` is false, only
/// records newer than the newest summary's `cutoff_ts` are returned
/// (matching [`Session::load_records_since_last_summary`]); when true,
/// every real record is returned, ignoring summaries.
pub fn read_chat_message_with_ts(path: &Path, all: bool) -> io::Result<Vec<ChatMessageWithTs>> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };
    let mut latest_cutoff: Option<u64> = None;
    let mut records: Vec<ChatMessageWithTs> = Vec::new();
    for (i, line) in BufReader::new(file).lines().enumerate() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        match parse_conversation_line_with_meta(&line) {
            Ok(LineKind::Message { message, ts }) => {
                records.push(ChatMessageWithTs { message, ts });
            }
            Ok(LineKind::Summary { cutoff_ts }) => {
                latest_cutoff = Some(match latest_cutoff {
                    Some(prev) => prev.max(cutoff_ts),
                    None => cutoff_ts,
                });
            }
            Ok(LineKind::Other) => {}
            Err(e) => {
                return Err(io::Error::other(format!(
                    "malformed conversation record at line {}: {e}",
                    i + 1
                )));
            }
        }
    }
    if !all && let Some(cutoff) = latest_cutoff {
        records.retain(|r| r.ts > cutoff);
    }
    Ok(records)
}

// -------------------------------------------------------------------
// Path resolution (LOCK not acquired, directory not created)
// -------------------------------------------------------------------

/// Absolute paths for a session's on-disk artifacts. Computed
/// without touching the filesystem so read-only commands can use
/// these without side effects.
#[derive(Debug, Clone)]
pub struct SessionPaths {
    pub dir: PathBuf,
    pub conversation: PathBuf,
    pub pending: PathBuf,
    pub lock: PathBuf,
    /// Agent-writable free zone (`.attini/{NAME}/scratchpad/`). The
    /// patch tool's Layer 2 always-allow rule covers everything under
    /// this directory regardless of git status; `Session::open`
    /// auto-creates it so the agent can rely on its existence.
    pub scratchpad: PathBuf,
    /// Cached Q&A state for `attini ask` (`.attini/{NAME}/ask.json`).
    /// Not part of the conversation; consumed only by the read-only
    /// `ask` command to give follow-up questions prior context.
    pub ask: PathBuf,
}

/// Root directory (`.attini/`) that holds every session in the CWD.
pub fn session_root() -> PathBuf {
    PathBuf::from(".attini")
}

/// Validate `name` and return the paths for its session. Does not
/// create the directory nor take the LOCK.
pub fn session_paths(name: &str) -> io::Result<SessionPaths> {
    if name.is_empty() {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "session name must not be empty",
        ));
    }
    if name.contains(|c: char| c == '/' || c == '\\' || c.is_control()) {
        return Err(io::Error::new(
            io::ErrorKind::InvalidInput,
            "session name must not contain path separators or control characters",
        ));
    }
    let dir = session_root().join(name);
    Ok(SessionPaths {
        conversation: dir.join("conversation.jsonl"),
        pending: dir.join("pending.json"),
        lock: dir.join("LOCK"),
        scratchpad: dir.join("scratchpad"),
        ask: dir.join("ask.json"),
        dir,
    })
}

// -------------------------------------------------------------------
// Read-only inspection helpers for the top-level `attini status` /
// `attini logstats` subcommands
// -------------------------------------------------------------------

/// Aggregate counters over one `conversation.jsonl`. Used by both
/// `attini show` (per-kind breakdown).
#[derive(Debug, Clone, Default)]
pub struct ConversationSummary {
    pub total_records: u64,
    pub last_ts: Option<u64>,
    pub last_kind: Option<String>,
    pub invocation_starts: u64,
    pub invocation_ends_completed: u64,
    pub invocation_ends_awaiting_approval: u64,
    pub invocation_ends_error: u64,
    pub user_messages: u64,
    pub assistant_messages: u64,
    pub assistant_tool_calls_total: u64,
    pub tool_messages: u64,
    pub approvals_approve: u64,
    pub approvals_reject: u64,
    /// Subset of `approvals_approve` whose record has an
    /// `auto_decided_by` sidecar (rule-driven auto approval).
    pub approvals_auto_approve: u64,
    /// Subset of `approvals_reject` whose record has an
    /// `auto_decided_by` sidecar (rule-driven auto deny or
    /// plan-mode reject).
    pub approvals_auto_deny: u64,
    pub summaries: u64,
    pub last_prompt_tokens: Option<u64>,
    pub last_prompt_cache_hit_tokens: Option<u64>,
    pub last_prompt_cache_miss_tokens: Option<u64>,
}

/// Walk `conversation.jsonl` and produce a summary. Missing file →
/// zero-initialised summary. Malformed lines abort with an error.
pub fn scan_conversation(path: &Path) -> io::Result<ConversationSummary> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            return Ok(ConversationSummary::default());
        }
        Err(e) => return Err(e),
    };
    let mut summary = ConversationSummary::default();
    for (i, line) in BufReader::new(file).lines().enumerate() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        summary.total_records += 1;
        classify_record(&line, &mut summary)
            .map_err(|e| io::Error::other(format!("malformed record at line {}: {e}", i + 1)))?;
    }
    Ok(summary)
}

fn classify_record(line: &str, out: &mut ConversationSummary) -> Result<(), String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    if let Ok(m) = value.to_member("ts")
        && let Some(v) = m.optional()
        && let Ok(ts) = v.try_into()
    {
        out.last_ts = Some(ts);
    }
    match kind.as_str() {
        "invocation_start" => out.invocation_starts += 1,
        "invocation_end" => {
            let reason = value
                .to_member("reason")
                .and_then(|m| m.required())
                .and_then(|m| m.to_unquoted_string_str())
                .map_err(|e| e.to_string())?;
            match reason.as_ref() {
                "completed" => out.invocation_ends_completed += 1,
                "awaiting_approval" => out.invocation_ends_awaiting_approval += 1,
                "error" => out.invocation_ends_error += 1,
                _ => {}
            }
        }
        "user" => out.user_messages += 1,
        "assistant" => {
            out.assistant_messages += 1;
            if let Ok(m) = value.to_member("tool_calls")
                && let Some(v) = m.optional()
                && let Ok(arr) = v.to_array()
            {
                out.assistant_tool_calls_total += arr.count() as u64;
            }
        }
        "tool" => out.tool_messages += 1,
        "summary" => out.summaries += 1,
        "token_usage" => {
            if let Ok(usage_m) = value.to_member("usage")
                && let Some(usage) = usage_m.optional()
            {
                out.last_prompt_tokens = usage
                    .to_member("prompt_tokens")
                    .ok()
                    .and_then(|m| m.optional())
                    .and_then(|v| v.try_into().ok())
                    .or(out.last_prompt_tokens);
                out.last_prompt_cache_hit_tokens = usage
                    .to_member("prompt_cache_hit_tokens")
                    .ok()
                    .and_then(|m| m.optional())
                    .and_then(|v| v.try_into().ok())
                    .or(out.last_prompt_cache_hit_tokens);
                out.last_prompt_cache_miss_tokens = usage
                    .to_member("prompt_cache_miss_tokens")
                    .ok()
                    .and_then(|m| m.optional())
                    .and_then(|v| v.try_into().ok())
                    .or(out.last_prompt_cache_miss_tokens);
            }
        }
        "tool_approval" => {
            let decision = value
                .to_member("decision")
                .and_then(|m| m.required())
                .and_then(|m| m.to_unquoted_string_str())
                .map_err(|e| e.to_string())?;
            let has_auto_sidecar = value
                .to_member("auto_decided_by")
                .ok()
                .and_then(|m| m.optional())
                .is_some();
            match decision.as_ref() {
                "approve" => {
                    out.approvals_approve += 1;
                    if has_auto_sidecar {
                        out.approvals_auto_approve += 1;
                    }
                }
                "reject" => {
                    out.approvals_reject += 1;
                    if has_auto_sidecar {
                        out.approvals_auto_deny += 1;
                    }
                }
                _ => {}
            }
        }
        _ => {}
    }
    out.last_kind = Some(kind);
    Ok(())
}

/// A subset of `Pending` safe to show to the user (omits the full
/// `arguments_json`, which for command tools would echo the entire
/// shell command line and for patches the full replacement text).
#[derive(Debug, Clone)]
pub struct PendingSummary {
    pub call_id: String,
    pub tool_kind: PendingToolKind,
    pub function_name: String,
    pub preview: String,
    pub ts: u64,
}

/// Read `pending.json` and return summaries of every parked call.
/// Missing file → `None`.
pub fn read_pending_summary(path: &Path) -> io::Result<Option<Vec<PendingSummary>>> {
    let text = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    let json = RawJson::parse(&text).map_err(|e| io::Error::other(format!("pending.json: {e}")))?;
    let pendings = Pending::from_json_array(json.value())?;
    Ok(Some(
        pendings
            .into_iter()
            .map(|p| PendingSummary {
                call_id: p.call_id,
                tool_kind: p.tool_kind,
                function_name: p.function_name,
                preview: p.preview,
                ts: p.ts,
            })
            .collect(),
    ))
}

// -------------------------------------------------------------------
// LOCK acquisition (with stale detection)
// -------------------------------------------------------------------

fn acquire_lock_with_stale_retry(name: &str, lock_path: &Path) -> io::Result<File> {
    match acquire_lock(lock_path) {
        Ok(file) => Ok(file),
        Err(AcquireError::Io(e)) => Err(e),
        Err(AcquireError::Locked) => match inspect_lock(lock_path) {
            LockStatus::PidAlive(pid) => Err(lock_conflict_error(name, lock_path, Some(pid))),
            LockStatus::PidDead | LockStatus::Corrupted | LockStatus::None => {
                let _ = fs::remove_file(lock_path);
                match acquire_lock(lock_path) {
                    Ok(file) => Ok(file),
                    Err(AcquireError::Io(e)) => Err(e),
                    Err(AcquireError::Locked) => Err(lock_conflict_error(name, lock_path, None)),
                }
            }
        },
    }
}

enum AcquireError {
    Locked,
    Io(io::Error),
}

fn acquire_lock(path: &Path) -> Result<File, AcquireError> {
    let mut file = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(path)
        .map_err(|e| {
            if e.kind() == io::ErrorKind::AlreadyExists {
                AcquireError::Locked
            } else {
                AcquireError::Io(e)
            }
        })?;
    let body = LockBody {
        pid: std::process::id() as i32,
        started_at_unix_ms: now_unix_millis(),
    };
    let text = Json(&body).to_string();
    file.write_all(text.as_bytes()).map_err(AcquireError::Io)?;
    file.sync_all().map_err(AcquireError::Io)?;
    Ok(file)
}

fn lock_conflict_error(name: &str, lock_path: &Path, holder_pid: Option<i32>) -> io::Error {
    let pid_hint = match holder_pid {
        Some(pid) => format!(" (holder pid {pid})"),
        None => String::new(),
    };
    io::Error::new(
        io::ErrorKind::AlreadyExists,
        format!(
            "session {name:?} is locked{pid_hint}: {path}\n\
             If no attini process is actually holding it, remove the LOCK manually: \
             `rm {path}`.",
            path = lock_path.display(),
        ),
    )
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LockStatus {
    /// No LOCK file present.
    None,
    /// LOCK file exists but its contents cannot be parsed / are
    /// empty / carry an invalid PID.
    Corrupted,
    /// LOCK file names a PID that no longer exists (`ESRCH`).
    PidDead,
    /// LOCK file names a PID that is alive, or that `kill(pid, 0)`
    /// reports as EPERM (safe side: treat as held).
    PidAlive(i32),
}

/// Non-mutating probe of a LOCK file. Does not create, open with
/// exclusive access, or otherwise disturb the file.
pub fn inspect_lock(path: &Path) -> LockStatus {
    match fs::metadata(path) {
        Ok(_) => classify_existing_lock(path),
        Err(e) if e.kind() == io::ErrorKind::NotFound => LockStatus::None,
        Err(_) => LockStatus::Corrupted,
    }
}

fn classify_existing_lock(path: &Path) -> LockStatus {
    let text = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(_) => return LockStatus::Corrupted,
    };
    let (pid, _started_at) = match parse_lock_body(&text) {
        Some(v) => v,
        None => return LockStatus::Corrupted,
    };
    match probe_pid(pid) {
        PidStatus::Dead => LockStatus::PidDead,
        PidStatus::Alive | PidStatus::EPerm => LockStatus::PidAlive(pid),
    }
}

fn parse_lock_body(text: &str) -> Option<(i32, u64)> {
    let json = RawJson::parse(text).ok()?;
    let value = json.value();
    let pid_i64: i64 = value
        .to_member("pid")
        .ok()?
        .required()
        .ok()?
        .try_into()
        .ok()?;
    let started_at_unix_ms: u64 = value
        .to_member("started_at_unix_ms")
        .ok()?
        .required()
        .ok()?
        .try_into()
        .ok()?;
    let pid: i32 = pid_i64.try_into().ok()?;
    if pid <= 0 {
        return None;
    }
    Some((pid, started_at_unix_ms))
}

enum PidStatus {
    Alive,
    Dead,
    EPerm,
}

#[expect(
    unsafe_code,
    reason = "libc::kill with signal 0 only probes process existence and touches no memory"
)]
fn probe_pid(pid: i32) -> PidStatus {
    // SAFETY: `kill` with signal 0 does not send a signal; it only
    // probes whether the process (or one with the same effective
    // uid) exists. No memory safety concerns.
    let ret = unsafe { libc::kill(pid as libc::pid_t, 0) };
    if ret == 0 {
        return PidStatus::Alive;
    }
    match io::Error::last_os_error().raw_os_error() {
        Some(errno) if errno == libc::ESRCH => PidStatus::Dead,
        Some(errno) if errno == libc::EPERM => PidStatus::EPerm,
        _ => PidStatus::Alive,
    }
}

struct LockBody {
    pid: i32,
    started_at_unix_ms: u64,
}

impl DisplayJson for LockBody {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("pid", self.pid)?;
            f.member("started_at_unix_ms", self.started_at_unix_ms)
        })
    }
}

// -------------------------------------------------------------------
// SessionRecord (on-disk record types for conversation.jsonl)
// -------------------------------------------------------------------

/// One line written to `conversation.jsonl`. Kept intentionally
/// small — only what the CLI shell needs to reconstruct state
/// and print a useful history. Not the same schema as the TUI's
/// `TranscriptRecord` (which is oriented at event observers);
/// having a dedicated CLI schema keeps the format easy to
/// parse and evolve independently.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SessionRecord {
    InvocationStart {
        ts: u64,
        attini_version: String,
        model: String,
    },
    InvocationEnd {
        ts: u64,
        reason: InvocationEndReason,
    },
    User {
        ts: u64,
        text: String,
    },
    Assistant {
        ts: u64,
        content: String,
        tool_calls: Vec<ToolCall>,
    },
    Tool {
        ts: u64,
        call_id: String,
        content: String,
    },
    ToolApproval {
        ts: u64,
        call_id: String,
        decision: ApprovalDecision,
        /// `Some` when the decision was made automatically (rule
        /// match or plan-mode reject); `None` for user `--approve`.
        /// Serialised as an optional sidecar object.
        auto_decided_by: Option<AutoDecidedBy>,
    },
    /// Snapshot of transport / agent metric counters. Emitted
    /// once at invocation end.
    MetricsSnapshot {
        ts: u64,
        counters: MetricsSnapshotBody,
    },
    /// Per-turn token usage reported by the model. Appended after
    /// each successful assistant turn when the streaming response
    /// carried a `usage` object. Compaction reads the latest
    /// `prompt_tokens` from these records to decide whether to
    /// summarise before the next invocation.
    TokenUsage {
        ts: u64,
        body: TokenUsageBody,
    },
    /// A compaction summary that replaces the range of real records
    /// from `since_ts` up to and including `cutoff_ts`. Multiple
    /// summaries accumulate in time order; the shell reads them all
    /// and only the real records after the latest `cutoff_ts`.
    Summary {
        ts: u64,
        since_ts: u64,
        cutoff_ts: u64,
        text: String,
    },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InvocationEndReason {
    /// Turn completed with a final assistant message (no pending
    /// tool calls).
    Completed,
    /// Agent loop suspended waiting for approval. `pending.json`
    /// is populated.
    AwaitingApproval,
    /// Something errored before completion.
    Error,
    /// A model call failed at the transport layer (connection reset,
    /// timeout, DNS, malformed stream) before any assistant output was
    /// recorded for the turn. Distinct from [`Self::Error`] because the
    /// identical request can safely be re-issued: `attini approve`
    /// offers a retry for this reason and not for a generic error.
    TransportError,
    /// The invocation-scope tool-call backstop
    /// (`TellConfig::session_tool_call_max`) tripped and the loop
    /// stopped without a final assistant message.
    SessionToolCallExhausted,
}

impl InvocationEndReason {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Completed => "completed",
            Self::AwaitingApproval => "awaiting_approval",
            Self::Error => "error",
            Self::TransportError => "transport_error",
            Self::SessionToolCallExhausted => "session_tool_call_exhausted",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ApprovalDecision {
    Approve,
    Reject,
}

impl ApprovalDecision {
    fn as_str(self) -> &'static str {
        match self {
            Self::Approve => "approve",
            Self::Reject => "reject",
        }
    }
}

/// Sidecar attached to `SessionRecord::ToolApproval` when the
/// decision was made automatically (rule match, or an approved plan
/// action).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoDecidedBy {
    /// The scope of the winning (last matching) rule.
    pub scope: String,
    /// The winning rule's argv prefix (command rules).
    pub args_prefix: Vec<String>,
    /// The winning rule's decision.
    pub allow: bool,
    /// Every rule that matched during the walk, in evaluation order,
    /// each marked with whether it was the one finally adopted.
    pub matches: Vec<AutoDecidedMatch>,
}

/// One matched rule in an automatic decision's evaluation history.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AutoDecidedMatch {
    pub scope: String,
    pub kind: String,
    pub allow: bool,
    pub args_prefix: Vec<String>,
    pub path: String,
    pub adopted: bool,
}

impl DisplayJson for AutoDecidedMatch {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("scope", &self.scope)?;
            f.member("kind", &self.kind)?;
            f.member("allow", self.allow)?;
            f.member("args_prefix", &self.args_prefix)?;
            f.member("path", &self.path)?;
            f.member("adopted", self.adopted)?;
            Ok(())
        })
    }
}

impl DisplayJson for AutoDecidedBy {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("scope", &self.scope)?;
            f.member("args_prefix", &self.args_prefix)?;
            f.member("allow", self.allow)?;
            f.member("matches", &self.matches)?;
            Ok(())
        })
    }
}

/// Placeholder body for a metrics snapshot. Filled with a flat
/// map of counter name → value so the shape can be inspected by
/// `jq` without a schema.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct MetricsSnapshotBody {
    pub entries: Vec<(String, u64)>,
}

impl DisplayJson for MetricsSnapshotBody {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            for (k, v) in &self.entries {
                f.member(k.as_str(), v)?;
            }
            Ok(())
        })
    }
}

/// Per-turn token usage payload for `SessionRecord::TokenUsage`.
/// All fields are optional because different models populate
/// different subsets; only `prompt_tokens` is required for
/// compaction to trigger.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct TokenUsageBody {
    pub prompt_tokens: Option<u64>,
    pub completion_tokens: Option<u64>,
    pub total_tokens: Option<u64>,
    pub prompt_cache_hit_tokens: Option<u64>,
    pub prompt_cache_miss_tokens: Option<u64>,
}

impl DisplayJson for TokenUsageBody {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            if let Some(v) = self.prompt_tokens {
                f.member("prompt_tokens", v)?;
            }
            if let Some(v) = self.completion_tokens {
                f.member("completion_tokens", v)?;
            }
            if let Some(v) = self.total_tokens {
                f.member("total_tokens", v)?;
            }
            if let Some(v) = self.prompt_cache_hit_tokens {
                f.member("prompt_cache_hit_tokens", v)?;
            }
            if let Some(v) = self.prompt_cache_miss_tokens {
                f.member("prompt_cache_miss_tokens", v)?;
            }
            Ok(())
        })
    }
}

impl DisplayJson for SessionRecord {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        match self {
            Self::InvocationStart {
                ts,
                attini_version,
                model,
            } => f.object(|f| {
                f.member("kind", "invocation_start")?;
                f.member("ts", ts)?;
                f.member("attini_version", attini_version)?;
                f.member("model", model)
            }),
            Self::InvocationEnd { ts, reason } => f.object(|f| {
                f.member("kind", "invocation_end")?;
                f.member("ts", ts)?;
                f.member("reason", reason.as_str())
            }),
            Self::User { ts, text } => f.object(|f| {
                f.member("kind", "user")?;
                f.member("ts", ts)?;
                f.member("text", text)
            }),
            Self::Assistant {
                ts,
                content,
                tool_calls,
            } => f.object(|f| {
                f.member("kind", "assistant")?;
                f.member("ts", ts)?;
                f.member("content", content)?;
                f.member("tool_calls", tool_calls)
            }),
            Self::Tool {
                ts,
                call_id,
                content,
            } => f.object(|f| {
                f.member("kind", "tool")?;
                f.member("ts", ts)?;
                f.member("call_id", call_id)?;
                f.member("content", content)
            }),
            Self::ToolApproval {
                ts,
                call_id,
                decision,
                auto_decided_by,
            } => f.object(|f| {
                f.member("kind", "tool_approval")?;
                f.member("ts", ts)?;
                f.member("call_id", call_id)?;
                f.member("decision", decision.as_str())?;
                if let Some(by) = auto_decided_by {
                    f.member("auto_decided_by", by)?;
                }
                Ok(())
            }),
            Self::MetricsSnapshot { ts, counters } => f.object(|f| {
                f.member("kind", "metrics_snapshot")?;
                f.member("ts", ts)?;
                f.member("counters", counters)
            }),
            Self::TokenUsage { ts, body } => f.object(|f| {
                f.member("kind", "token_usage")?;
                f.member("ts", ts)?;
                f.member("usage", body)
            }),
            Self::Summary {
                ts,
                since_ts,
                cutoff_ts,
                text,
            } => f.object(|f| {
                f.member("kind", "summary")?;
                f.member("ts", ts)?;
                f.member("since_ts", since_ts)?;
                f.member("cutoff_ts", cutoff_ts)?;
                f.member("text", text)
            }),
        }
    }
}

/// One `summary` record from `conversation.jsonl`, with the
/// metadata compaction and inspection code needs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SummaryRecord {
    pub ts: u64,
    pub since_ts: u64,
    pub cutoff_ts: u64,
    pub text: String,
}

/// A conversation `ChatMessage` paired with the `ts` of the record
/// it came from. Used by compaction to decide safe cutoff
/// boundaries and to compute `since_ts` for a new summary.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ChatMessageWithTs {
    pub message: ChatMessage,
    pub ts: u64,
}

enum LineKind {
    Message { message: ChatMessage, ts: u64 },
    Summary { cutoff_ts: u64 },
    Other,
}

fn parse_conversation_line_with_meta(line: &str) -> Result<LineKind, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    match kind.as_str() {
        "user" | "assistant" | "tool" => {
            let ts: u64 = value
                .to_member("ts")
                .and_then(|m| m.required())
                .and_then(|m| m.try_into())
                .map_err(|e| e.to_string())?;
            let message = parse_conversation_line(line)?.ok_or_else(|| {
                "kind matched user/assistant/tool but parse_conversation_line returned None"
                    .to_string()
            })?;
            Ok(LineKind::Message { message, ts })
        }
        "summary" => {
            let cutoff_ts: u64 = value
                .to_member("cutoff_ts")
                .and_then(|m| m.required())
                .and_then(|m| m.try_into())
                .map_err(|e| e.to_string())?;
            Ok(LineKind::Summary { cutoff_ts })
        }
        _ => Ok(LineKind::Other),
    }
}

fn parse_summary_line(line: &str) -> Result<Option<SummaryRecord>, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    if kind != "summary" {
        return Ok(None);
    }
    let ts: u64 = value
        .to_member("ts")
        .and_then(|m| m.required())
        .and_then(|m| m.try_into())
        .map_err(|e| e.to_string())?;
    let since_ts: u64 = value
        .to_member("since_ts")
        .and_then(|m| m.required())
        .and_then(|m| m.try_into())
        .map_err(|e| e.to_string())?;
    let cutoff_ts: u64 = value
        .to_member("cutoff_ts")
        .and_then(|m| m.required())
        .and_then(|m| m.try_into())
        .map_err(|e| e.to_string())?;
    let text = read_string(value, "text")?;
    Ok(Some(SummaryRecord {
        ts,
        since_ts,
        cutoff_ts,
        text,
    }))
}

fn parse_prompt_tokens(line: &str) -> Result<Option<u64>, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    if kind != "token_usage" {
        return Ok(None);
    }
    let Some(usage) = value
        .to_member("usage")
        .map_err(|e| e.to_string())?
        .optional()
    else {
        return Ok(None);
    };
    let Some(pt) = usage
        .to_member("prompt_tokens")
        .map_err(|e| e.to_string())?
        .optional()
    else {
        return Ok(None);
    };
    let n: u64 = pt.try_into().map_err(|e: JsonParseError| e.to_string())?;
    Ok(Some(n))
}

/// Pull `reason` from an `invocation_end` line. Returns `Ok(None)` for
/// any other record kind so a full-file scan can look for the last one.
fn parse_invocation_end_reason(line: &str) -> Result<Option<InvocationEndReason>, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    if kind != "invocation_end" {
        return Ok(None);
    }
    let reason = value
        .to_member("reason")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    let parsed = match reason.as_str() {
        "completed" => InvocationEndReason::Completed,
        "awaiting_approval" => InvocationEndReason::AwaitingApproval,
        "error" => InvocationEndReason::Error,
        "transport_error" => InvocationEndReason::TransportError,
        "session_tool_call_exhausted" => InvocationEndReason::SessionToolCallExhausted,
        other => return Err(format!("unknown invocation_end.reason {other:?}")),
    };
    Ok(Some(parsed))
}

/// Histogram of one slice of the conversation log: how many records
/// plus how many bytes they occupy.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RecordKindBytes {
    pub count: u64,
    pub bytes: u64,
}

/// Per-path read footprint. `ranges` counts distinct `line_range`
/// values (a rough duplicate-read detector); `calls` counts every
/// read that targeted this path.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ReadTargetStats {
    pub calls: u64,
    pub bytes: u64,
    pub max_bytes: u64,
    pub ranges: u64,
}

/// (argv[0], argv[1]) family stats for `command` tool results.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct CommandFamily {
    pub program: String,
    pub subcommand: Option<String>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CommandFamilyStats {
    pub count: u64,
    pub bytes: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ProgramStats {
    pub count: u64,
    pub bytes: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct ToolResultStats {
    pub count: u64,
    pub bytes: u64,
    pub max_bytes: u64,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct SummaryBytes {
    pub count: u64,
    pub bytes: u64,
}

/// Cumulative token usage over every `TokenUsage` record.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct TokenUsageAggregate {
    pub records: u64,
    pub prompt_total: u64,
    pub completion_total: u64,
    pub cache_hit_total: u64,
    pub cache_miss_total: u64,
    pub prompt_max: u64,
    pub latest: Option<u64>,
}

/// Whole-file analysis of a conversation log for `attini
/// logstats`. Produced by [`analyze_conversation`]; renderers decide
/// how many rows to display (human vs `--json`).
#[derive(Debug, Clone, Default)]
pub struct ConversationAnalysis {
    pub records: u64,
    pub total_bytes: u64,
    pub kind_bytes: Vec<(String, RecordKindBytes)>,
    pub assistant_content_bytes: u64,
    pub tool_calls_count: u64,
    pub tool_results: Vec<(String, ToolResultStats)>,
    pub read_targets: Vec<(String, ReadTargetStats)>,
    pub programs: Vec<(String, ProgramStats)>,
    pub command_families: Vec<(CommandFamily, CommandFamilyStats)>,
    pub token_usage: TokenUsageAggregate,
    pub summary_text: SummaryBytes,
}

/// Line-by-line scan of a conversation log, returning a
/// [`ConversationAnalysis`]. Read-only; never acquires the session
/// LOCK. Missing files yield an empty analysis. Malformed lines are
/// skipped. The `assistant` record's `tool_calls` are joined with
/// the following `tool` records by `call_id` so tool-result stats
/// can be attributed to a function name.
pub fn analyze_conversation(path: &Path) -> io::Result<ConversationAnalysis> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(ConversationAnalysis::default()),
        Err(e) => return Err(e),
    };
    let reader = io::BufReader::new(file);

    use std::collections::BTreeMap;

    let mut kind_bytes: BTreeMap<String, RecordKindBytes> = BTreeMap::new();
    let mut assistant_content_bytes = 0u64;
    let mut tool_calls_count = 0u64;
    let mut tool_results: BTreeMap<String, ToolResultStats> = BTreeMap::new();
    let mut read_targets: BTreeMap<String, ReadTargetStats> = BTreeMap::new();
    let mut programs: BTreeMap<String, ProgramStats> = BTreeMap::new();
    let mut command_families: BTreeMap<CommandFamily, CommandFamilyStats> = BTreeMap::new();
    let mut token_usage_total = TokenUsageAggregate::default();
    let mut summary_bytes = SummaryBytes::default();
    let mut records = 0u64;
    let mut total_bytes = 0u64;
    let mut waiting_tools: Vec<(String, ToolCall)> = Vec::new();

    for line in reader.lines() {
        let line = match line {
            Ok(l) => l,
            Err(_) => continue,
        };
        if line.trim().is_empty() {
            continue;
        }
        total_bytes += (line.len() as u64) + 1;
        let parsed = match parse_session_record_line(&line) {
            Ok(Some(record)) => record,
            Ok(None) => {
                kind_bytes.entry("unknown".to_string()).or_default().count += 1;
                kind_bytes.get_mut("unknown").unwrap().bytes += (line.len() as u64) + 1;
                continue;
            }
            Err(_) => {
                kind_bytes.entry("malformed".to_string()).or_default().count += 1;
                kind_bytes.get_mut("malformed").unwrap().bytes += (line.len() as u64) + 1;
                continue;
            }
        };
        records += 1;
        let this_bytes = (line.len() as u64) + 1;

        match &parsed {
            SessionRecord::InvocationStart { .. } => {
                kind_bytes
                    .entry("invocation_start".to_string())
                    .or_default()
                    .count += 1;
                kind_bytes.get_mut("invocation_start").unwrap().bytes += this_bytes;
            }
            SessionRecord::InvocationEnd { .. } => {
                kind_bytes
                    .entry("invocation_end".to_string())
                    .or_default()
                    .count += 1;
                kind_bytes.get_mut("invocation_end").unwrap().bytes += this_bytes;
            }
            SessionRecord::User { .. } => {
                kind_bytes.entry("user".to_string()).or_default().count += 1;
                kind_bytes.get_mut("user").unwrap().bytes += this_bytes;
            }
            SessionRecord::Assistant {
                content,
                tool_calls,
                ..
            } => {
                kind_bytes.entry("assistant".to_string()).or_default().count += 1;
                kind_bytes.get_mut("assistant").unwrap().bytes += this_bytes;
                assistant_content_bytes += content.len() as u64;
                // Collect every tool_call from this turn so the `tool`
                // results that follow can be attributed by call_id, even
                // when the model emitted several calls in one turn.
                for tc in tool_calls {
                    waiting_tools.push((tc.id.clone(), tc.clone()));
                }
                tool_calls_count += tool_calls.len() as u64;
            }
            SessionRecord::Tool {
                call_id, content, ..
            } => {
                kind_bytes.entry("tool".to_string()).or_default().count += 1;
                kind_bytes.get_mut("tool").unwrap().bytes += this_bytes;
                // Attribute this tool result to its pending call. A
                // `tool` record answers exactly one call; remove it from
                // the waiting set so the next record does not re-use the
                // same function name.
                let matched_idx = waiting_tools.iter().position(|(id, _)| id == call_id);
                let fname = matched_idx
                    .map(|i| waiting_tools[i].1.function_name.clone())
                    .unwrap_or_else(|| "unknown".to_string());
                let bytes = content.len() as u64;
                let entry = tool_results.entry(fname.clone()).or_default();
                entry.count += 1;
                entry.bytes += bytes;
                entry.max_bytes = entry.max_bytes.max(bytes);
                if let Some(idx) = matched_idx {
                    let tc = waiting_tools[idx].1.clone();
                    if fname == "read"
                        && let Some(path) = tool_arg_string(&tc, "path")
                    {
                        let target = read_targets.entry(path).or_default();
                        target.calls += 1;
                        target.bytes += bytes;
                        target.max_bytes = target.max_bytes.max(bytes);
                        // A `line_range` argument (which may be an
                        // array) indicates a partial read; count it
                        // to detect overlapping re-reads.
                        if tool_arg_present(&tc, "line_range") {
                            target.ranges += 1;
                        }
                    }
                    if fname == "command"
                        && let Some(argv) = tool_arg_array(&tc, "argv")
                        && let Some(program) = argv.first()
                    {
                        programs.entry(program.clone()).or_default().count += 1;
                        programs.get_mut(program).unwrap().bytes += bytes;
                        let family = CommandFamily {
                            program: program.clone(),
                            subcommand: argv.get(1).cloned(),
                        };
                        command_families.entry(family.clone()).or_default().count += 1;
                        command_families.get_mut(&family).unwrap().bytes += bytes;
                    }
                    waiting_tools.remove(idx);
                }
            }
            SessionRecord::ToolApproval { .. } => {
                kind_bytes
                    .entry("tool_approval".to_string())
                    .or_default()
                    .count += 1;
                kind_bytes.get_mut("tool_approval").unwrap().bytes += this_bytes;
            }
            SessionRecord::MetricsSnapshot { .. } => {
                kind_bytes
                    .entry("metrics_snapshot".to_string())
                    .or_default()
                    .count += 1;
                kind_bytes.get_mut("metrics_snapshot").unwrap().bytes += this_bytes;
            }
            SessionRecord::TokenUsage { body, .. } => {
                kind_bytes
                    .entry("token_usage".to_string())
                    .or_default()
                    .count += 1;
                kind_bytes.get_mut("token_usage").unwrap().bytes += this_bytes;
                token_usage_total.records += 1;
                if let Some(v) = body.prompt_tokens {
                    token_usage_total.prompt_total += v;
                    token_usage_total.prompt_max = token_usage_total.prompt_max.max(v);
                    token_usage_total.latest = Some(v);
                }
                if let Some(v) = body.completion_tokens {
                    token_usage_total.completion_total += v;
                }
                if let Some(v) = body.prompt_cache_hit_tokens {
                    token_usage_total.cache_hit_total += v;
                }
                if let Some(v) = body.prompt_cache_miss_tokens {
                    token_usage_total.cache_miss_total += v;
                }
            }
            SessionRecord::Summary { text, .. } => {
                kind_bytes.entry("summary".to_string()).or_default().count += 1;
                kind_bytes.get_mut("summary").unwrap().bytes += this_bytes;
                summary_bytes.count += 1;
                summary_bytes.bytes += text.len() as u64;
            }
        }
    }

    Ok(ConversationAnalysis {
        records,
        total_bytes,
        kind_bytes: kind_bytes.into_iter().collect(),
        assistant_content_bytes,
        tool_calls_count,
        tool_results: tool_results.into_iter().collect(),
        read_targets: read_targets.into_iter().collect(),
        programs: programs.into_iter().collect(),
        command_families: command_families.into_iter().collect(),
        token_usage: token_usage_total,
        summary_text: summary_bytes,
    })
}

/// Best-effort extraction of a string field from a tool-call
/// `arguments_json`. `nojson` is used since the arguments are
/// guaranteed parseable (they came from the model). Malformed
/// arguments yield `None`.
fn tool_arg_string(tc: &ToolCall, key: &str) -> Option<String> {
    let json = RawJson::parse(&tc.arguments_json).ok()?;
    let member = json.value().to_member(key).ok()?.optional()?;
    member.to_unquoted_string_str().ok().map(|s| s.into_owned())
}

/// Whether a tool-call argument (of any JSON shape) is present in the
/// `arguments_json`. Used for keys like `line_range` that are arrays;
/// their presence is more meaningful than their string value.
fn tool_arg_present(tc: &ToolCall, key: &str) -> bool {
    let Ok(json) = RawJson::parse(&tc.arguments_json) else {
        return false;
    };
    json.value()
        .to_member(key)
        .ok()
        .and_then(|m| m.optional())
        .is_some()
}

fn tool_arg_array(tc: &ToolCall, key: &str) -> Option<Vec<String>> {
    let json = RawJson::parse(&tc.arguments_json).ok()?;
    let member = json.value().to_member(key).ok()?.optional()?;
    let mut out = Vec::new();
    for child in member.to_array().ok()? {
        if let Ok(s) = child.to_unquoted_string_str() {
            out.push(s.into_owned());
        }
    }
    Some(out)
}

/// Read every `SessionRecord` from a `conversation.jsonl` file
/// without acquiring the session LOCK. Suited for observing a
/// session's tail while it (or another process) still holds the
/// LOCK. Missing files return an empty vector. Individual malformed
/// or unknown lines are silently skipped so a partial file (e.g. a
/// half-written last line from a crashed writer) still yields the
/// prefix of well-formed records.
pub fn read_conversation_records(path: &Path) -> io::Result<Vec<SessionRecord>> {
    let file = match File::open(path) {
        Ok(f) => f,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(e) => return Err(e),
    };
    let reader = io::BufReader::new(file);
    let mut out = Vec::new();
    for line in reader.lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        if let Ok(Some(record)) = parse_session_record_line(&line) {
            out.push(record);
        }
    }
    Ok(out)
}

/// Deserialize one JSON Lines record into the corresponding
/// [`SessionRecord`] variant. Unknown `kind` values return
/// `Ok(None)` so callers can iterate a mixed stream without
/// erroring on forward-compatible additions. Malformed JSON (missing
/// required field, wrong type) returns `Err`.
fn parse_session_record_line(line: &str) -> Result<Option<SessionRecord>, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    match kind.as_str() {
        "invocation_start" => {
            let ts = read_u64(value, "ts")?;
            let attini_version = read_string(value, "attini_version")?;
            let model = read_string(value, "model")?;
            Ok(Some(SessionRecord::InvocationStart {
                ts,
                attini_version,
                model,
            }))
        }
        "invocation_end" => {
            let ts = read_u64(value, "ts")?;
            let reason_str = read_string(value, "reason")?;
            let reason = match reason_str.as_str() {
                "completed" => InvocationEndReason::Completed,
                "awaiting_approval" => InvocationEndReason::AwaitingApproval,
                "error" => InvocationEndReason::Error,
                "transport_error" => InvocationEndReason::TransportError,
                "session_tool_call_exhausted" => InvocationEndReason::SessionToolCallExhausted,
                other => return Err(format!("unknown invocation_end.reason {other:?}")),
            };
            Ok(Some(SessionRecord::InvocationEnd { ts, reason }))
        }
        "user" => {
            let ts = read_u64(value, "ts")?;
            let text = read_string(value, "text")?;
            Ok(Some(SessionRecord::User { ts, text }))
        }
        "assistant" => {
            let ts = read_u64(value, "ts")?;
            let content = read_string(value, "content")?;
            let tool_calls = read_tool_calls(value)?;
            Ok(Some(SessionRecord::Assistant {
                ts,
                content,
                tool_calls,
            }))
        }
        "tool" => {
            let ts = read_u64(value, "ts")?;
            let call_id = read_string(value, "call_id")?;
            let content = read_string(value, "content")?;
            Ok(Some(SessionRecord::Tool {
                ts,
                call_id,
                content,
            }))
        }
        "tool_approval" => {
            let ts = read_u64(value, "ts")?;
            let call_id = read_string(value, "call_id")?;
            let decision_str = read_string(value, "decision")?;
            let decision = match decision_str.as_str() {
                "approve" => ApprovalDecision::Approve,
                "reject" => ApprovalDecision::Reject,
                other => return Err(format!("unknown tool_approval.decision {other:?}")),
            };
            let auto_decided_by = parse_auto_decided_by(value)?;
            Ok(Some(SessionRecord::ToolApproval {
                ts,
                call_id,
                decision,
                auto_decided_by,
            }))
        }
        "metrics_snapshot" => {
            let ts = read_u64(value, "ts")?;
            let counters = parse_metrics_counters(value)?;
            Ok(Some(SessionRecord::MetricsSnapshot {
                ts,
                counters: MetricsSnapshotBody { entries: counters },
            }))
        }
        "token_usage" => {
            let ts = read_u64(value, "ts")?;
            let body = parse_token_usage_body(value)?;
            Ok(Some(SessionRecord::TokenUsage { ts, body }))
        }
        "summary" => {
            let ts = read_u64(value, "ts")?;
            let since_ts = read_u64(value, "since_ts")?;
            let cutoff_ts = read_u64(value, "cutoff_ts")?;
            let text = read_string(value, "text")?;
            Ok(Some(SessionRecord::Summary {
                ts,
                since_ts,
                cutoff_ts,
                text,
            }))
        }
        _ => Ok(None),
    }
}

fn read_u64(value: nojson::RawJsonValue<'_, '_>, key: &str) -> Result<u64, String> {
    value
        .to_member(key)
        .and_then(|m| m.required())
        .and_then(|m| m.try_into())
        .map_err(|e: JsonParseError| e.to_string())
}

fn parse_auto_decided_by(
    value: nojson::RawJsonValue<'_, '_>,
) -> Result<Option<AutoDecidedBy>, String> {
    let Some(m) = value
        .to_member("auto_decided_by")
        .map_err(|e| e.to_string())?
        .optional()
    else {
        return Ok(None);
    };
    if m.as_raw_str().trim() == "null" {
        return Ok(None);
    }
    let scope = read_string(m, "scope")?;
    let allow = read_bool(m, "allow")?;
    let args_prefix = read_string_array(m, "args_prefix")?;
    let mut matches = Vec::new();
    let list = m
        .to_member("matches")
        .and_then(|arr| arr.required())
        .map_err(|e| e.to_string())?;
    for item in list.to_array().map_err(|e| e.to_string())? {
        matches.push(AutoDecidedMatch {
            scope: read_string(item, "scope")?,
            kind: read_string(item, "kind")?,
            allow: read_bool(item, "allow")?,
            args_prefix: read_string_array(item, "args_prefix")?,
            path: read_string(item, "path")?,
            adopted: read_bool(item, "adopted")?,
        });
    }
    Ok(Some(AutoDecidedBy {
        scope,
        args_prefix,
        allow,
        matches,
    }))
}

fn read_bool(value: nojson::RawJsonValue<'_, '_>, key: &str) -> Result<bool, String> {
    let raw = value
        .to_member(key)
        .and_then(|m| m.required())
        .and_then(|m| m.as_boolean_str())
        .map_err(|e: JsonParseError| e.to_string())?;
    match raw {
        "true" => Ok(true),
        "false" => Ok(false),
        other => Err(format!("{key}: expected a boolean (got {other})")),
    }
}

fn read_string_array(
    value: nojson::RawJsonValue<'_, '_>,
    key: &str,
) -> Result<Vec<String>, String> {
    let list = value
        .to_member(key)
        .and_then(|arr| arr.required())
        .map_err(|e| format!("{key}: {e}"))?;
    let mut out = Vec::new();
    for item in list.to_array().map_err(|e| format!("{key}: {e}"))? {
        out.push(
            item.to_unquoted_string_str()
                .map_err(|e| format!("{key}: {e}"))?
                .into_owned(),
        );
    }
    Ok(out)
}

fn parse_metrics_counters(
    value: nojson::RawJsonValue<'_, '_>,
) -> Result<Vec<(String, u64)>, String> {
    let counters = value
        .to_member("counters")
        .and_then(|m| m.required())
        .map_err(|e| e.to_string())?;
    let mut out = Vec::new();
    for (k, v) in counters.to_object().map_err(|e| e.to_string())? {
        let name = k
            .to_unquoted_string_str()
            .map_err(|e| e.to_string())?
            .into_owned();
        let n: u64 = v.try_into().map_err(|e: JsonParseError| e.to_string())?;
        out.push((name, n));
    }
    Ok(out)
}

fn parse_token_usage_body(value: nojson::RawJsonValue<'_, '_>) -> Result<TokenUsageBody, String> {
    let usage = value
        .to_member("usage")
        .and_then(|m| m.required())
        .map_err(|e| e.to_string())?;
    let opt_u64 = |key: &str| -> Result<Option<u64>, String> {
        let Some(v) = usage.to_member(key).map_err(|e| e.to_string())?.optional() else {
            return Ok(None);
        };
        if v.as_raw_str().trim() == "null" {
            return Ok(None);
        }
        let n: u64 = v.try_into().map_err(|e: JsonParseError| e.to_string())?;
        Ok(Some(n))
    };
    Ok(TokenUsageBody {
        prompt_tokens: opt_u64("prompt_tokens")?,
        completion_tokens: opt_u64("completion_tokens")?,
        total_tokens: opt_u64("total_tokens")?,
        prompt_cache_hit_tokens: opt_u64("prompt_cache_hit_tokens")?,
        prompt_cache_miss_tokens: opt_u64("prompt_cache_miss_tokens")?,
    })
}

/// Extract a [`ChatMessage`] from one JSON Lines record if the
/// record contributes to the conversation context. Returns
/// `Ok(None)` for records that are logged for observability but
/// do not add to the message list (invocation_start /
/// invocation_end / tool_approval / metrics_snapshot).
fn parse_conversation_line(line: &str) -> Result<Option<ChatMessage>, String> {
    let json = RawJson::parse(line).map_err(|e| e.to_string())?;
    let value = json.value();
    let kind = value
        .to_member("kind")
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned();
    match kind.as_str() {
        "user" => {
            let text = read_string(value, "text")?;
            Ok(Some(ChatMessage::User(text)))
        }
        "assistant" => {
            let content = read_string(value, "content")?;
            let tool_calls = read_tool_calls(value)?;
            Ok(Some(ChatMessage::Assistant {
                content,
                tool_calls,
            }))
        }
        "tool" => {
            let call_id = read_string(value, "call_id")?;
            let content = read_string(value, "content")?;
            Ok(Some(ChatMessage::Tool {
                tool_call_id: call_id,
                content,
            }))
        }
        // Non-conversation records (start/end/approval/metrics)
        // are recorded for observability but do not add to the
        // message list. Unknown kinds are skipped forward-compat.
        _ => Ok(None),
    }
}

fn read_string(value: nojson::RawJsonValue<'_, '_>, key: &str) -> Result<String, String> {
    Ok(value
        .to_member(key)
        .and_then(|m| m.required())
        .and_then(|m| m.to_unquoted_string_str())
        .map_err(|e| e.to_string())?
        .into_owned())
}

fn read_optional_string(
    value: nojson::RawJsonValue<'_, '_>,
    key: &str,
) -> Result<Option<String>, String> {
    let member = value.to_member(key).map_err(|e| e.to_string())?;
    let Some(v) = member.optional() else {
        return Ok(None);
    };
    // Distinguish JSON `null` from a real string.
    let is_null = v.as_raw_str().trim() == "null";
    if is_null {
        return Ok(None);
    }
    Ok(Some(
        v.to_unquoted_string_str()
            .map_err(|e| e.to_string())?
            .into_owned(),
    ))
}

fn read_tool_calls(value: nojson::RawJsonValue<'_, '_>) -> Result<Vec<ToolCall>, String> {
    let member = value.to_member("tool_calls").map_err(|e| e.to_string())?;
    let Some(v) = member.optional() else {
        return Ok(Vec::new());
    };
    let mut out = Vec::new();
    for item in v.to_array().map_err(|e| e.to_string())? {
        let id = read_string(item, "id")?;
        let function = item
            .to_member("function")
            .and_then(|m| m.required())
            .map_err(|e| e.to_string())?;
        let function_name = read_string(function, "name")?;
        let arguments_json = read_string(function, "arguments")?;
        out.push(ToolCall {
            id,
            function_name,
            arguments_json,
        });
    }
    Ok(out)
}

// -------------------------------------------------------------------
// Pending state (pending.json)
// -------------------------------------------------------------------

/// Serialisable snapshot of one approval-blocked point in the
/// agent loop. The next invocation loads this to know which tool
/// call to execute (on approve) or synthesise a rejection for
/// (on reject).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pending {
    pub ts: u64,
    pub call_id: String,
    pub tool_kind: PendingToolKind,
    pub function_name: String,
    pub arguments_json: String,
    /// Human-readable preview shown to the user (already printed
    /// during the invocation that produced this pending record).
    /// Kept here so the resuming invocation can re-print if the
    /// user forgot.
    pub preview: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PendingToolKind {
    Patch,
    Command,
    /// A read-only call (`read` / `list` / `search`) that targeted a path
    /// outside the workspace and is waiting for one-shot human approval to
    /// widen the read boundary for that single call.
    Read,
}

impl PendingToolKind {
    fn as_str(self) -> &'static str {
        match self {
            Self::Patch => "patch",
            Self::Command => "command",
            Self::Read => "read",
        }
    }

    fn parse(s: &str) -> Option<Self> {
        match s {
            "patch" => Some(Self::Patch),
            "command" => Some(Self::Command),
            "read" => Some(Self::Read),
            _ => None,
        }
    }
}

impl DisplayJson for Pending {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("ts", self.ts)?;
            f.member("call_id", &self.call_id)?;
            f.member("tool_kind", self.tool_kind.as_str())?;
            f.member("function_name", &self.function_name)?;
            f.member("arguments_json", &self.arguments_json)?;
            f.member("preview", &self.preview)
        })
    }
}

impl Pending {
    fn from_json(value: nojson::RawJsonValue<'_, '_>) -> io::Result<Self> {
        let map_err = |e: String| io::Error::other(format!("pending.json: {e}"));
        let ts: u64 = value
            .to_member("ts")
            .and_then(|m| m.required())
            .and_then(|m| m.try_into())
            .map_err(|e| map_err(e.to_string()))?;
        let call_id = read_string(value, "call_id").map_err(map_err)?;
        let tool_kind_str = read_string(value, "tool_kind").map_err(map_err)?;
        let tool_kind = PendingToolKind::parse(&tool_kind_str).ok_or_else(|| {
            io::Error::other(format!("pending.json: unknown tool_kind {tool_kind_str:?}"))
        })?;
        let function_name = read_string(value, "function_name").map_err(map_err)?;
        let arguments_json = read_string(value, "arguments_json").map_err(map_err)?;
        let preview = read_string(value, "preview").map_err(map_err)?;
        Ok(Self {
            ts,
            call_id,
            tool_kind,
            function_name,
            arguments_json,
            preview,
        })
    }

    fn from_json_array(value: nojson::RawJsonValue<'_, '_>) -> io::Result<Vec<Self>> {
        let iter = value
            .to_array()
            .map_err(|e| io::Error::other(format!("pending.json: {e}")))?;
        let mut out = Vec::new();
        for elem in iter {
            out.push(Self::from_json(elem)?);
        }
        Ok(out)
    }
}

// -------------------------------------------------------------------
// ask state (ask.json)
// -------------------------------------------------------------------

/// One cached Q&A from `attini ask`. Purely advisory: it is never
/// injected into the agent's conversation, only passed to a later
/// `attini ask` so a follow-up question can build on a previous
/// observer answer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AskEntry {
    pub ts: u64,
    pub question: Option<String>,
    pub answer: String,
}

/// Snapshot of the question/answer cache for one session.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AskState {
    /// FNV-1a fingerprint of the conversation records that produced
    /// the first entry in this state. `ask` recomputes it for the
    /// window it actually observed; a mismatch means the observation
    /// changed (session advanced, or `--all`/`--limit` differs) and
    /// the cache is discarded rather than trusted.
    pub conversation_fingerprint: u64,
    pub entries: Vec<AskEntry>,
}

impl DisplayJson for AskEntry {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("ts", self.ts)?;
            f.member("question", &self.question)?;
            f.member("answer", &self.answer)
        })
    }
}

impl DisplayJson for AskState {
    fn fmt(&self, f: &mut JsonFormatter<'_, '_>) -> std::fmt::Result {
        f.object(|f| {
            f.member("conversation_fingerprint", self.conversation_fingerprint)?;
            f.member("entries", &self.entries)
        })
    }
}

impl AskState {
    fn from_json(value: nojson::RawJsonValue<'_, '_>) -> io::Result<Self> {
        let map_err = |e: String| io::Error::other(format!("ask.json: {e}"));
        let conversation_fingerprint: u64 = value
            .to_member("conversation_fingerprint")
            .and_then(|m| m.required())
            .and_then(|m| m.try_into())
            .map_err(|e| map_err(e.to_string()))?;
        let iter = value
            .to_member("entries")
            .and_then(|m| m.required())
            .and_then(|m| m.to_array())
            .map_err(|e| map_err(e.to_string()))?;
        let mut entries = Vec::new();
        for elem in iter {
            entries.push(Self::entry_from_json(elem).map_err(&map_err)?);
        }
        Ok(Self {
            conversation_fingerprint,
            entries,
        })
    }

    fn entry_from_json(value: nojson::RawJsonValue<'_, '_>) -> Result<AskEntry, String> {
        let ts: u64 = value
            .to_member("ts")
            .and_then(|m| m.required())
            .and_then(|m| m.try_into())
            .map_err(|e| e.to_string())?;
        let question = read_optional_string(value, "question")?;
        let answer = read_string(value, "answer")?;
        Ok(AskEntry {
            ts,
            question,
            answer,
        })
    }
}

/// Read `ask.json` for a session if present. A missing file yields
/// `Ok(None)`; malformed content is a hard error (it would silently
/// break follow-up context otherwise).
pub fn load_ask_state(path: &Path) -> io::Result<Option<AskState>> {
    let text = match fs::read_to_string(path) {
        Ok(s) => s,
        Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None),
        Err(e) => return Err(e),
    };
    let json = RawJson::parse(&text).map_err(|e| io::Error::other(format!("ask.json: {e}")))?;
    AskState::from_json(json.value()).map(Some)
}

/// Write `ask.json` atomically (temp file in the same directory,
/// then rename) so a concurrent reader never sees a partial file.
pub fn save_ask_state(path: &Path, state: &AskState) -> io::Result<()> {
    let parent = path
        .parent()
        .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "ask.json has no parent"))?;
    fs::create_dir_all(parent)?;
    let file_name = path
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("ask.json");
    let tmp = parent.join(format!(".{file_name}.tmp-{}", std::process::id()));
    fs::write(&tmp, Json(state).to_string())?;
    fs::rename(&tmp, path)
}

/// FNV-1a (64-bit) of the ordered conversation records. Deterministic
/// across processes (unlike `DefaultHasher`), and only depends on the
/// records actually observed — so a different `--all`/`--limit` window
/// produces a different fingerprint and naturally resets the ask cache.
pub fn conversation_fingerprint(records: &[ChatMessageWithTs]) -> u64 {
    const PRIME: u64 = 0x0000_0100_0000_01b3;
    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
    for rec in records {
        for b in rec.ts.to_string().as_bytes() {
            hash ^= *b as u64;
            hash = hash.wrapping_mul(PRIME);
        }
        hash ^= 0xFF;
        hash = hash.wrapping_mul(PRIME);
        let body = Json(&rec.message).to_string();
        for b in body.as_bytes() {
            hash ^= *b as u64;
            hash = hash.wrapping_mul(PRIME);
        }
        hash ^= 0xFE;
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

// -------------------------------------------------------------------
// Helpers
// -------------------------------------------------------------------

pub fn now_unix_millis() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn analyze_conversation_splits_payload_and_attributes_result() {
        use std::io::Write;

        let dir = std::env::temp_dir().join(format!("attini-analyze-{}", now_unix_millis()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("conversation.jsonl");
        let mut f = std::fs::File::create(&path).unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::InvocationStart {
                ts: 1,
                attini_version: "0.0.0".to_string(),
                model: "m".to_string(),
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::User {
                ts: 2,
                text: "hi".to_string(),
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Assistant {
                ts: 3,
                content: "".to_string(),
                tool_calls: vec![ToolCall {
                    id: "c1".to_string(),
                    function_name: "read".to_string(),
                    arguments_json: r#"{"path":"src/main.rs","line_range":[1,2]}"#.to_string(),
                }],
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Tool {
                ts: 4,
                call_id: "c1".to_string(),
                content: "the file contents".to_string(),
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Assistant {
                ts: 5,
                content: "done".to_string(),
                tool_calls: vec![ToolCall {
                    id: "c2".to_string(),
                    function_name: "command".to_string(),
                    arguments_json: r#"{"argv":["cargo","test"]}"#.to_string(),
                }],
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Tool {
                ts: 6,
                call_id: "c2".to_string(),
                content: "test output".to_string(),
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::TokenUsage {
                ts: 7,
                body: TokenUsageBody {
                    prompt_tokens: Some(100),
                    completion_tokens: Some(20),
                    prompt_cache_hit_tokens: Some(30),
                    prompt_cache_miss_tokens: Some(70),
                    total_tokens: Some(120),
                },
            })
        )
        .unwrap();
        drop(f);

        let a = analyze_conversation(&path).unwrap();
        assert_eq!(a.records, 7);
        assert_eq!(a.assistant_content_bytes, "done".len() as u64);
        assert_eq!(a.tool_calls_count, 2);
        // tool results attributed by function name
        assert_eq!(a.tool_results.len(), 2);
        let read = a.tool_results.iter().find(|(k, _)| k == "read").unwrap();
        assert_eq!(read.1.count, 1);
        assert_eq!(read.1.bytes, "the file contents".len() as u64);
        let cmd = a.tool_results.iter().find(|(k, _)| k == "command").unwrap();
        assert_eq!(cmd.1.count, 1);
        assert_eq!(cmd.1.bytes, "test output".len() as u64);
        // read target captured
        let read_targets = a
            .read_targets
            .iter()
            .find(|(p, _)| p == "src/main.rs")
            .unwrap();
        assert!(read_targets.1.ranges > 0);
        // program / family captured generically
        let program = a.programs.iter().find(|(p, _)| p == "cargo").unwrap();
        assert_eq!(program.1.count, 1);
        let fam = a
            .command_families
            .iter()
            .find(|(fam, _)| fam.program == "cargo" && fam.subcommand.as_deref() == Some("test"))
            .unwrap();
        assert_eq!(fam.1.count, 1);
        // token usage aggregate
        assert_eq!(a.token_usage.records, 1);
        assert_eq!(a.token_usage.prompt_total, 100);
        assert_eq!(a.token_usage.completion_total, 20);
        assert_eq!(a.token_usage.cache_hit_total, 30);
        assert_eq!(a.token_usage.cache_miss_total, 70);
        assert_eq!(a.token_usage.latest, Some(100));

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn analyze_conversation_joins_multiple_calls_in_one_turn() {
        use std::io::Write;

        let dir = std::env::temp_dir().join(format!("attini-analyze-multi-{}", now_unix_millis()));
        std::fs::create_dir_all(&dir).unwrap();
        let path = dir.join("conversation.jsonl");
        let mut f = std::fs::File::create(&path).unwrap();
        // One assistant turn emits two tool calls.
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Assistant {
                ts: 1,
                content: "".to_string(),
                tool_calls: vec![
                    ToolCall {
                        id: "a".to_string(),
                        function_name: "read".to_string(),
                        arguments_json: r#"{"path":"src/x.rs","line_range":[1,2]}"#.to_string(),
                    },
                    ToolCall {
                        id: "b".to_string(),
                        function_name: "command".to_string(),
                        arguments_json: r#"{"argv":["cargo","check"]}"#.to_string(),
                    },
                ],
            })
        )
        .unwrap();
        // The two tool results arrive; order may differ from call order.
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Tool {
                ts: 2,
                call_id: "b".to_string(),
                content: "cargo check ok".to_string(),
            })
        )
        .unwrap();
        writeln!(
            f,
            "{}",
            Json(&SessionRecord::Tool {
                ts: 3,
                call_id: "a".to_string(),
                content: "src/x.rs contents".to_string(),
            })
        )
        .unwrap();
        drop(f);

        let a = analyze_conversation(&path).unwrap();
        assert_eq!(a.tool_calls_count, 2);
        // Both tool results must be attributed, with none lost to
        // "unknown" despite the out-of-order arrival.
        let read = a.tool_results.iter().find(|(k, _)| k == "read").unwrap();
        assert_eq!(read.1.count, 1);
        let cmd = a.tool_results.iter().find(|(k, _)| k == "command").unwrap();
        assert_eq!(cmd.1.count, 1);
        assert!(!a.tool_results.iter().any(|(k, _)| k == "unknown"));
        // read target captured from call "a"
        let target = a
            .read_targets
            .iter()
            .find(|(p, _)| p == "src/x.rs")
            .unwrap();
        assert_eq!(target.1.calls, 1);
        assert!(target.1.ranges > 0);

        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn conversation_fingerprint_is_deterministic_and_window_sensitive() {
        let a = ChatMessageWithTs {
            message: ChatMessage::User("hello".to_string()),
            ts: 1,
        };
        let b = ChatMessageWithTs {
            message: ChatMessage::User("world".to_string()),
            ts: 2,
        };
        let fp1 = conversation_fingerprint(&[a.clone(), b.clone()]);
        let fp2 = conversation_fingerprint(&[a.clone(), b.clone()]);
        assert_eq!(fp1, fp2, "fingerprint must be deterministic");

        let fp_more = conversation_fingerprint(&[a.clone(), b.clone(), a.clone()]);
        assert_ne!(fp1, fp_more, "adding a record must change the fingerprint");

        let fp_window = conversation_fingerprint(&[b]);
        assert_ne!(
            fp1, fp_window,
            "a different window must change the fingerprint"
        );
    }

    #[test]
    fn ask_state_roundtrips_through_json() {
        let state = AskState {
            conversation_fingerprint: 42,
            entries: vec![
                AskEntry {
                    ts: 1,
                    question: Some("what?".to_string()),
                    answer: "answer one".to_string(),
                },
                AskEntry {
                    ts: 2,
                    question: None,
                    answer: "answer two".to_string(),
                },
            ],
        };
        let json = Json(&state).to_string();
        let parsed = RawJson::parse(&json).expect("ask.json should parse");
        let got = AskState::from_json(parsed.value()).expect("ask.json should convert");
        assert_eq!(got, state);
    }

    #[test]
    fn approval_decision_serialises_stable_strings() {
        assert_eq!(ApprovalDecision::Approve.as_str(), "approve");
        assert_eq!(ApprovalDecision::Reject.as_str(), "reject");
    }

    #[test]
    fn invocation_end_reason_serialises_stable_strings() {
        assert_eq!(InvocationEndReason::Completed.as_str(), "completed");
        assert_eq!(
            InvocationEndReason::AwaitingApproval.as_str(),
            "awaiting_approval"
        );
        assert_eq!(InvocationEndReason::Error.as_str(), "error");
        assert_eq!(
            InvocationEndReason::SessionToolCallExhausted.as_str(),
            "session_tool_call_exhausted"
        );
    }

    #[test]
    fn pending_tool_kind_roundtrips() {
        for kind in [
            PendingToolKind::Patch,
            PendingToolKind::Command,
            PendingToolKind::Read,
        ] {
            assert_eq!(PendingToolKind::parse(kind.as_str()), Some(kind));
        }
        assert!(PendingToolKind::parse("bogus").is_none());
    }

    #[test]
    fn pending_batch_roundtrips_through_json_array() {
        let a = Pending {
            ts: 1,
            call_id: "call_1".to_string(),
            tool_kind: PendingToolKind::Patch,
            function_name: "patch".to_string(),
            arguments_json: r#"{"edits":[]}"#.to_string(),
            preview: "patch preview".to_string(),
        };
        let b = Pending {
            ts: 2,
            call_id: "call_2".to_string(),
            tool_kind: PendingToolKind::Command,
            function_name: "command".to_string(),
            arguments_json: r#"{"argv":["git","status"]}"#.to_string(),
            preview: "command preview".to_string(),
        };
        let json = Json(&[a.clone(), b.clone()]).to_string();
        let parsed = RawJson::parse(&json).expect("array should parse");
        let got = Pending::from_json_array(parsed.value()).expect("array should convert");
        assert_eq!(got, vec![a, b]);
    }

    #[test]
    fn assistant_record_with_tool_calls_roundtrips_through_parse() {
        let record = SessionRecord::Assistant {
            ts: 42,
            content: "hi".to_string(),
            tool_calls: vec![ToolCall {
                id: "call_1".to_string(),
                function_name: "read".to_string(),
                arguments_json: r#"{"path":"src/foo.rs"}"#.to_string(),
            }],
        };
        let line = nojson::Json(&record).to_string();
        let parsed = parse_conversation_line(&line)
            .expect("parse must succeed")
            .expect("assistant record must yield a ChatMessage");
        match parsed {
            ChatMessage::Assistant {
                content,
                tool_calls,
            } => {
                assert_eq!(content, "hi");
                assert_eq!(tool_calls.len(), 1);
                assert_eq!(tool_calls[0].id, "call_1");
                assert_eq!(tool_calls[0].function_name, "read");
                assert_eq!(tool_calls[0].arguments_json, r#"{"path":"src/foo.rs"}"#);
            }
            other => panic!("expected assistant, got {other:?}"),
        }
    }

    #[test]
    fn tool_record_roundtrips_through_parse() {
        let record = SessionRecord::Tool {
            ts: 7,
            call_id: "call_x".to_string(),
            content: r#"{"ok":true}"#.to_string(),
        };
        let line = nojson::Json(&record).to_string();
        let parsed = parse_conversation_line(&line)
            .expect("parse must succeed")
            .expect("tool record must yield a ChatMessage");
        match parsed {
            ChatMessage::Tool {
                tool_call_id,
                content,
            } => {
                assert_eq!(tool_call_id, "call_x");
                assert_eq!(content, r#"{"ok":true}"#);
            }
            other => panic!("expected tool, got {other:?}"),
        }
    }

    #[test]
    fn summary_record_roundtrips_through_parse_summary_line() {
        let record = SessionRecord::Summary {
            ts: 100,
            since_ts: 10,
            cutoff_ts: 90,
            text: "user asked for X".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        let parsed = parse_summary_line(&line)
            .expect("parse ok")
            .expect("summary yields SummaryRecord");
        assert_eq!(parsed.ts, 100);
        assert_eq!(parsed.since_ts, 10);
        assert_eq!(parsed.cutoff_ts, 90);
        assert_eq!(parsed.text, "user asked for X");
    }

    #[test]
    fn summary_record_is_not_returned_by_parse_conversation_line() {
        // Compaction API split: `load_conversation` (which uses
        // `parse_conversation_line`) must not surface summary
        // records as ChatMessages — those are exposed via
        // `load_summaries` instead.
        let record = SessionRecord::Summary {
            ts: 100,
            since_ts: 10,
            cutoff_ts: 90,
            text: "should not appear as ChatMessage".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        let parsed = parse_conversation_line(&line).expect("parse ok");
        assert!(parsed.is_none());
    }

    #[test]
    fn token_usage_record_serialises_only_present_fields() {
        let record = SessionRecord::TokenUsage {
            ts: 42,
            body: TokenUsageBody {
                prompt_tokens: Some(1000),
                completion_tokens: None,
                total_tokens: Some(1050),
                prompt_cache_hit_tokens: Some(800),
                prompt_cache_miss_tokens: Some(200),
            },
        };
        let line = nojson::Json(&record).to_string();
        assert_eq!(
            line,
            r#"{"kind":"token_usage","ts":42,"usage":{"prompt_tokens":1000,"total_tokens":1050,"prompt_cache_hit_tokens":800,"prompt_cache_miss_tokens":200}}"#
        );
    }

    #[test]
    fn parse_prompt_tokens_returns_none_for_non_token_usage_lines() {
        let record = SessionRecord::User {
            ts: 1,
            text: "hi".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        assert!(parse_prompt_tokens(&line).expect("parse ok").is_none());
    }

    #[test]
    fn parse_prompt_tokens_extracts_value_from_token_usage_line() {
        let record = SessionRecord::TokenUsage {
            ts: 42,
            body: TokenUsageBody {
                prompt_tokens: Some(17_000),
                ..Default::default()
            },
        };
        let line = nojson::Json(&record).to_string();
        assert_eq!(parse_prompt_tokens(&line).expect("parse ok"), Some(17_000));
    }

    #[test]
    fn parse_prompt_tokens_tolerates_missing_prompt_tokens_field() {
        let record = SessionRecord::TokenUsage {
            ts: 42,
            body: TokenUsageBody {
                prompt_tokens: None,
                total_tokens: Some(5),
                ..Default::default()
            },
        };
        let line = nojson::Json(&record).to_string();
        assert!(parse_prompt_tokens(&line).expect("parse ok").is_none());
    }

    #[test]
    fn parse_invocation_end_reason_round_trips_transport_error() {
        let record = SessionRecord::InvocationEnd {
            ts: 7,
            reason: InvocationEndReason::TransportError,
        };
        let line = nojson::Json(&record).to_string();
        assert_eq!(
            parse_invocation_end_reason(&line).expect("parse ok"),
            Some(InvocationEndReason::TransportError)
        );
    }

    #[test]
    fn parse_invocation_end_reason_returns_none_for_other_kinds() {
        let record = SessionRecord::User {
            ts: 1,
            text: "hi".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        assert!(
            parse_invocation_end_reason(&line)
                .expect("parse ok")
                .is_none()
        );
    }

    #[test]
    fn parse_conversation_line_with_meta_carries_ts_for_user_records() {
        let record = SessionRecord::User {
            ts: 999,
            text: "hi".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        match parse_conversation_line_with_meta(&line).expect("parse ok") {
            LineKind::Message { ts, message } => {
                assert_eq!(ts, 999);
                assert!(matches!(message, ChatMessage::User(_)));
            }
            other => panic!("expected message, got {other:?}"),
        }
    }

    #[test]
    fn parse_conversation_line_with_meta_recognises_summary_cutoff() {
        let record = SessionRecord::Summary {
            ts: 500,
            since_ts: 100,
            cutoff_ts: 450,
            text: "".to_string(),
        };
        let line = nojson::Json(&record).to_string();
        match parse_conversation_line_with_meta(&line).expect("parse ok") {
            LineKind::Summary { cutoff_ts } => assert_eq!(cutoff_ts, 450),
            other => panic!("expected summary, got {other:?}"),
        }
    }

    impl std::fmt::Debug for LineKind {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            match self {
                LineKind::Message { ts, .. } => write!(f, "Message(ts={ts})"),
                LineKind::Summary { cutoff_ts } => write!(f, "Summary(cutoff_ts={cutoff_ts})"),
                LineKind::Other => write!(f, "Other"),
            }
        }
    }
}