clustervision 0.15.1

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

use claude::user as user_line;
use cv_testkit::{claude, World};
use std::path::PathBuf;
use std::process::Command;
use std::{fs, str};

/// A planted secret that `cv export --redact` must scrub (matches cv_core::redact's sk- recognizer).
const SECRET: &str = "sk-abcDEF1234567890ghijkl";

/// A legacy decision: opened assigned to `who` and tagged `decision`, with nothing posed — the
/// shape `cv task open --tags decision` wrote before it was refused. Stamped a few seconds
/// ahead so it sorts after anything the test just opened.
fn plant_legacy_tag_decision(w: &World, id: &str, title: &str, who: &str) {
    let ts = chrono_at(3);
    w.append_task_log(&[
        serde_json::json!({"id": id, "task_id": id, "ts": ts, "by": "cv", "event": "opened",
            "title": title, "channel": "tasks", "assignee": who}),
        serde_json::json!({"id": format!("{}f", &id[..id.len() - 1]), "task_id": id, "ts": ts, "by": "cv",
            "event": "tagged", "tags": ["decision"]}),
    ]);
}

fn assistant_line(uuid: &str, ts: &str, blocks: serde_json::Value) -> serde_json::Value {
    claude::with(
        claude::assistant(uuid, ts, "claude-test-1", blocks),
        serde_json::json!({"cwd": "/work/proj"}),
    )
}

/// The standard two-session corpus:
/// - `alphasess`: created 2026-01-01, updated 2026-06-01, 3 messages, title "alpha adventures",
///   contains "zebrafish", a planted secret, and an Edit on /work/proj/src/widget.rs.
/// - `betasess`: created 2026-03-01, updated 2026-03-02, 4 messages, no title.
///
/// Orderings disagree on purpose: updated → alpha first; created → beta first; messages → beta.
fn standard_corpus(w: &World) {
    w.write_session(
        "alphasess",
        &[
            serde_json::json!({"type": "ai-title", "aiTitle": "alpha adventures"}),
            user_line("u1", "2026-01-01T10:00:00Z", "please fix the zebrafish migration"),
            assistant_line(
                "a1",
                "2026-01-02T10:00:00Z",
                serde_json::json!([
                    {"type": "text", "text": format!("on it — found a leaked key {SECRET} in the env")},
                    {"type": "tool_use", "id": "t1", "name": "Edit",
                     "input": {"file_path": "/work/proj/src/widget.rs", "old_string": "a", "new_string": "b"}}
                ]),
            ),
            serde_json::json!({
                "type": "user", "uuid": "u2", "sessionId": "s", "timestamp": "2026-06-01T10:00:00Z",
                "message": {"role": "user", "content": [
                    {"type": "tool_result", "tool_use_id": "t1", "content": "edited ok", "is_error": false}
                ]}
            }),
        ],
    );
    w.write_session(
        "betasess",
        &[
            user_line("b1", "2026-03-01T09:00:00Z", "how many quokkas in the census"),
            assistant_line(
                "b2",
                "2026-03-01T09:05:00Z",
                serde_json::json!([{"type": "text", "text": "seventeen quokkas"}]),
            ),
            user_line("b3", "2026-03-02T09:00:00Z", "thanks"),
            assistant_line(
                "b4",
                "2026-03-02T09:01:00Z",
                serde_json::json!([{"type": "text", "text": "anytime"}]),
            ),
        ],
    );
}

/// Index of `needle`'s first occurrence, with a labeled panic when missing.
fn pos(hay: &str, needle: &str) -> usize {
    hay.find(needle)
        .unwrap_or_else(|| panic!("expected {needle:?} in:\n{hay}"))
}

// ───────────────────────────── ls ─────────────────────────────

#[test]
fn ls_sort_modes_and_filters() {
    let w = World::new("ls");
    standard_corpus(&w);

    // Default (updated): alpha's last timestamp (06-01) beats beta's (03-02).
    let (out, _) = w.cv_ok(&["ls"]);
    assert!(out.contains("2 session(s)"), "{out}");
    assert!(pos(&out, "alphases") < pos(&out, "betasess"), "updated order:\n{out}");
    assert!(out.contains("alpha adventures"), "{out}");

    // created: beta (03-01) is newer than alpha (01-01).
    let (out, _) = w.cv_ok(&["ls", "--sort-by", "created"]);
    assert!(pos(&out, "betasess") < pos(&out, "alphases"), "created order:\n{out}");

    // messages: beta has 4, alpha 3.
    let (out, _) = w.cv_ok(&["ls", "--sort-by", "messages"]);
    assert!(pos(&out, "betasess") < pos(&out, "alphases"), "messages order:\n{out}");
    assert!(out.contains("4 msg"), "{out}");

    // explicit updated round-trips the default.
    let (out, _) = w.cv_ok(&["ls", "--sort-by", "updated"]);
    assert!(pos(&out, "alphases") < pos(&out, "betasess"), "{out}");

    // A bad sort key is a clap-level error: nonzero exit, usage on stderr, no panic.
    let (_, err) = w.cv_fails(&["ls", "--sort-by", "bogus"]);
    assert!(err.contains("bogus"), "{err}");

    // --limit truncates and says how many more exist.
    let (out, _) = w.cv_ok(&["ls", "--limit", "1"]);
    assert!(out.contains("… 1 more"), "{out}");

    // cwd filter notes how much was filtered away.
    let (out, _) = w.cv_ok(&["ls", "--cwd", "/work/proj"]);
    assert!(out.contains("2 session(s)"), "{out}");
    let (out, _) = w.cv_ok(&["ls", "--cwd", "/nowhere"]);
    assert!(out.contains("0 session(s) (of 2 discovered; filtered)"), "{out}");

    // Unknown harness is a real error.
    let (_, err) = w.cv_fails(&["ls", "--harness", "clippy9000"]);
    assert!(err.contains("unknown harness"), "{err}");
}

#[test]
fn ls_json_emits_the_same_rows_machine_readably() {
    let w = World::new("lsjson");
    standard_corpus(&w);

    // Stdout is exactly one JSON array — no header/footer — with one object per table row,
    // in table order (updated: alpha first), carrying the one snake_case session-row shape (INTERFACE-V2 §3).
    let (out, _) = w.cv_ok(&["ls", "--json"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    assert_eq!(rows.len(), 2, "{out}");
    assert_eq!(rows[0]["id"], "alphasess", "updated order:\n{out}");
    assert_eq!(rows[0]["harness"], "claude");
    assert_eq!(rows[0]["title"], "alpha adventures");
    assert_eq!(rows[0]["message_count"], 3);
    assert_eq!(rows[0]["cwd"], "/work/proj");
    assert!(
        rows[0]["created_at"].as_str().unwrap().starts_with("2026-01-01"),
        "{out}"
    );
    assert!(
        rows[0]["updated_at"].as_str().unwrap().starts_with("2026-06-01"),
        "{out}"
    );
    assert!(rows[0]["path"].as_str().unwrap().ends_with("alphasess.jsonl"), "{out}");
    // betasess has no title: present as an explicit null, not absent.
    assert!(rows[1]["title"].is_null(), "{out}");
    // size_bytes is always emitted (it comes free from the exists() guard's metadata call) and
    // matches the file's real length; the enrichment fields stay absent without --enrich.
    let real_size = std::fs::metadata(rows[0]["path"].as_str().unwrap()).unwrap().len();
    assert_eq!(rows[0]["size_bytes"].as_u64().unwrap(), real_size, "{out}");
    assert!(rows[0]["size_bytes"].as_u64().unwrap() > 0, "{out}");
    assert!(rows[0].get("git").is_none(), "no --enrich ⇒ no git:\n{out}");
    assert!(
        rows[0].get("display_title").is_none(),
        "no --enrich ⇒ no display_title:\n{out}"
    );

    // --limit bounds the array just like the table, with no "… N more" footer polluting stdout.
    let (out, _) = w.cv_ok(&["ls", "--json", "--limit", "1"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(rows.len(), 1, "{out}");

    // Filters apply identically; an empty result is an empty array, still valid JSON.
    let (out, _) = w.cv_ok(&["ls", "--json", "--harness", "codex"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert!(rows.is_empty(), "{out}");
}

#[test]
fn ls_json_enrich_adds_git_branch_and_synthesized_title() {
    let w = World::new("lsjsonenrich");
    // A session with a recorded git branch and NO explicit title — so display_title must be
    // synthesized from the first real user turn, and a leading <system-reminder> block is peeled.
    w.write_session(
        "enrichsess",
        &[
            serde_json::json!({
                "type": "user", "uuid": "e1", "sessionId": "s",
                "timestamp": "2026-05-01T10:00:00Z", "cwd": "/work/proj", "gitBranch": "feature/enrich",
                "message": {"role": "user", "content":
                    "<system-reminder>be nice</system-reminder>\n\nteach me about capybaras please"}
            }),
            assistant_line(
                "e2",
                "2026-05-01T10:01:00Z",
                serde_json::json!([{"type": "text", "text": "capybaras are the largest rodents"}]),
            ),
        ],
    );

    let (out, _) = w.cv_ok(&["ls", "--json", "--enrich"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).expect("pure JSON");
    assert_eq!(rows.len(), 1, "{out}");
    // The raw catalog title stays null; display_title carries the synthesized fallback with the
    // system-reminder noise stripped.
    assert!(rows[0]["title"].is_null(), "{out}");
    assert_eq!(rows[0]["display_title"], "teach me about capybaras please", "{out}");
    // git object matches `cv show --json`'s shape (branch present).
    assert_eq!(rows[0]["git"]["branch"], "feature/enrich", "{out}");
    // size_bytes still present alongside the enrichment.
    assert!(rows[0]["size_bytes"].as_u64().unwrap() > 0, "{out}");
}

// ───────────────────────────── search ─────────────────────────────

#[test]
fn search_fallback_messaging_and_index_path() {
    let w = World::new("search");
    standard_corpus(&w);

    // No index yet: a live scan with an explicit note, that still finds the content.
    let (out, err) = w.cv_ok(&["search", "zebrafish"]);
    assert!(err.contains("no index yet"), "want live-scan note, got stderr:\n{err}");
    assert!(err.contains("scanning live"), "{err}");
    assert!(out.contains("alphases"), "{out}");
    assert!(out.to_lowercase().contains("zebrafish"), "snippet expected:\n{out}");

    // A stale legacy sqlite index gets a cleanup nudge.
    fs::write(w.cv_home.join("index.sqlite"), b"stale").unwrap();
    let (_, err) = w.cv_ok(&["search", "zebrafish"]);
    assert!(
        err.contains("legacy sqlite index no longer used"),
        "want legacy-index note, got stderr:\n{err}"
    );
    fs::remove_file(w.cv_home.join("index.sqlite")).unwrap();

    // Build the index; search must now use it (no live-scan note) and still hit.
    let (out, _) = w.cv_ok(&["index"]);
    assert!(out.contains("indexed 2 top-level session(s)"), "{out}");
    let (out, err) = w.cv_ok(&["search", "zebrafish"]);
    assert!(
        !err.contains("scanning live"),
        "indexed search must not live-scan:\n{err}"
    );
    assert!(out.contains("alphases"), "{out}");

    // The index is authoritative: a miss is a miss (with the index hint), not a fallback.
    let (out, _) = w.cv_ok(&["search", "xyzzyplugh"]);
    assert!(out.contains("no matches"), "{out}");
    assert!(out.contains("(index"), "{out}");

    // Harness filter that matches nothing still exits 0 with the no-match message.
    let (out, _) = w.cv_ok(&["search", "zebrafish", "--harness", "codex"]);
    assert!(out.contains("no matches"), "{out}");
}

#[test]
fn search_json_emits_machine_readable_hits() {
    let w = World::new("searchjson");
    standard_corpus(&w);

    // Live-scan path (no index yet): the note stays on stderr; stdout is exactly one JSON
    // array with the FULL session id (the table truncates to "alphases"), the snippet the
    // table would print, and an explicit null score (a live scan has none).
    let (out, err) = w.cv_ok(&["search", "zebrafish", "--json"]);
    assert!(err.contains("scanning live"), "{err}");
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    assert_eq!(rows.len(), 1, "{out}");
    assert_eq!(rows[0]["id"], "alphasess", "full id, not the 8-char prefix:\n{out}");
    assert_eq!(rows[0]["harness"], "claude");
    assert_eq!(rows[0]["title"], "alpha adventures");
    assert!(rows[0]["snippet"].as_str().unwrap().contains("zebrafish"), "{out}");
    assert!(rows[0]["score"].is_null(), "{out}");
    // Sub-agent provenance keys are always present — null for a top-level hit — so consumers
    // can branch on them without probing for the keys.
    for key in ["agent_id", "parent_id", "workflow"] {
        let obj = rows[0].as_object().unwrap();
        assert!(obj.contains_key(key), "provenance key {key} must be present:\n{out}");
        assert!(obj[key].is_null(), "top-level hit must have null {key}:\n{out}");
    }
    assert!(
        rows[0]["updated_at"].as_str().unwrap().starts_with("2026-06-01"),
        "{out}"
    );

    // A live-scan miss is an empty array — valid JSON, no prose on stdout.
    let (out, _) = w.cv_ok(&["search", "xyzzyplugh", "--json"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert!(rows.is_empty(), "{out}");

    // --limit bounds the array; the "stopped at" footer moves to stderr, keeping stdout pure.
    // ("the" appears in both fixture sessions on the live path.)
    let (out, err) = w.cv_ok(&["search", "the", "--json", "--limit", "1"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(rows.len(), 1, "{out}");
    assert!(err.contains("stopped at 1"), "{err}");

    // Indexed path: same hit, still the full id, now with a real BM25 score and dates off
    // the index.
    w.cv_ok(&["index"]);
    let (out, err) = w.cv_ok(&["search", "zebrafish", "--json"]);
    assert!(!err.contains("scanning live"), "{err}");
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    assert_eq!(rows.len(), 1, "{out}");
    assert_eq!(rows[0]["id"], "alphasess", "{out}");
    assert!(rows[0]["score"].as_f64().unwrap() > 0.0, "{out}");
    // Provenance keys ride on indexed hits too (null: the fixture has no sub-agent lanes).
    let obj = rows[0].as_object().unwrap();
    for key in ["agent_id", "parent_id", "workflow"] {
        assert!(
            obj.contains_key(key) && obj[key].is_null(),
            "{key} present+null:\n{out}"
        );
    }
    assert!(
        rows[0]["updated_at"].as_str().unwrap().starts_with("2026-06-01"),
        "{out}"
    );

    // Indexed miss and non-matching --harness filter: empty arrays, still valid JSON.
    let (out, _) = w.cv_ok(&["search", "xyzzyplugh", "--json"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert!(rows.is_empty(), "{out}");
    let (out, _) = w.cv_ok(&["search", "zebrafish", "--json", "--harness", "codex"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(out.trim()).unwrap();
    assert!(rows.is_empty(), "{out}");
}

// ───────────────────────────── show windows ─────────────────────────────

/// The 0.11 window grammar, on the one command every consumer reaches for: `--range A..B` is
/// 0-based and end-exclusive, `--first/--last/--around` are the named selectors, only one of the
/// four may be given, and every 0.10 spelling errors with a pointer at what replaced it.
#[test]
fn show_range_windowing() {
    let w = World::new("show");
    standard_corpus(&w);

    // Whole session: header + all three turns.
    let (out, _) = w.cv_ok(&["show", "alphasess"]);
    assert!(out.contains("# alpha adventures"), "{out}");
    assert!(out.contains("zebrafish migration"), "{out}");
    assert!(out.contains("[tool_use Edit t1]"), "{out}");
    assert!(out.contains("edited ok"), "{out}");

    // `A..B` is end-exclusive: 1..2 is exactly msg 1 (the assistant turn).
    let (out, _) = w.cv_ok(&["show", "alphasess", "--range", "1..2"]);
    assert!(out.contains("[tool_use Edit t1]"), "{out}");
    assert!(!out.contains("zebrafish"), "window must exclude msg 0:\n{out}");
    assert!(!out.contains("edited ok"), "window must exclude msg 2:\n{out}");

    // Open-ended tail `A..`.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--range", "2.."]);
    assert!(out.contains("edited ok"), "{out}");
    assert!(!out.contains("zebrafish"), "{out}");

    // Open-ended head `..B` — end-exclusive, so `..1` is just msg 0.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--range", "..1"]);
    assert!(out.contains("zebrafish"), "{out}");
    assert!(!out.contains("[tool_use Edit t1]"), "{out}");

    // `--first N` is the replacement for the old `-N` head window.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--first", "1"]);
    assert!(out.contains("zebrafish"), "{out}");
    assert!(!out.contains("[tool_use Edit t1]"), "{out}");
    let (out, _) = w.cv_ok(&["show", "alphasess", "--first", "2"]);
    assert!(out.contains("zebrafish") && out.contains("[tool_use Edit t1]"), "{out}");
    assert!(!out.contains("edited ok"), "{out}");

    // `--last N` counts from the end (3 messages ⇒ --last 1 is msg 2).
    let (out, _) = w.cv_ok(&["show", "alphasess", "--last", "1"]);
    assert!(out.contains("edited ok"), "{out}");
    assert!(!out.contains("zebrafish"), "{out}");
    // More than exist ⇒ the whole session, not an error.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--last", "99"]);
    assert!(out.contains("zebrafish") && out.contains("edited ok"), "{out}");

    // `--around N` with an explicit --context: 0 is the single message the old bare `N` meant.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--around", "1", "--context", "0"]);
    assert!(out.contains("[tool_use Edit t1]"), "{out}");
    assert!(!out.contains("zebrafish"), "{out}");
    assert!(!out.contains("edited ok"), "{out}");
    // …and context pulls in the neighbours either side.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--around", "1", "--context", "1"]);
    assert!(out.contains("zebrafish") && out.contains("edited ok"), "{out}");
    // --context without --around is a usage error (it has no centre to hang off).
    let (_, err) = w.cv_fails(&["show", "alphasess", "--context", "2"]);
    assert!(err.contains("--around"), "{err}");

    // `--max-bytes` truncates the render and prints the copy-pasteable continuation line.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--max-bytes", "1"]);
    assert!(
        out.contains("continue with --range"),
        "continuation line expected:\n{out}"
    );
    assert!(!out.contains("edited ok"), "budget must cut the render short:\n{out}");

    // Range entirely past the end: still exits 0, renders the header and no messages.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--range", "10..20"]);
    assert!(out.contains("# alpha adventures"), "{out}");
    assert!(!out.contains("──"), "no message blocks expected:\n{out}");

    // Inverted range is rejected.
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "9..3"]);
    assert!(err.contains("end (3) is before start (9)"), "{err}");

    // Garbage range is rejected.
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "abc"]);
    assert!(err.contains("bad range"), "{err}");

    // ── the 0.10 grammar is GONE, and each rejection names its replacement ──
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "1-2"]);
    assert!(
        err.contains("A..B") && err.contains("--first N") && err.contains("--last N"),
        "`A-B` must point at the new grammar:\n{err}"
    );
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "-1"]);
    assert!(
        err.contains("--first N") && err.contains("--last N"),
        "`-N` must point at the flags:\n{err}"
    );
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "2-"]);
    assert!(err.contains("A.."), "`N-` must point at `A..`:\n{err}");
    let (_, err) = w.cv_fails(&["show", "alphasess", "--range", "1"]);
    assert!(
        err.contains("--around 1 --context 0") && err.contains("1..2"),
        "a bare index must point at both spellings of one message:\n{err}"
    );

    // ── exactly one selector: clap refuses two at once, naming the conflict ──
    for pair in [
        ["--first", "--last"],
        ["--first", "--range"],
        ["--last", "--range"],
        ["--first", "--around"],
        ["--last", "--around"],
        ["--range", "--around"],
    ] {
        let a = if pair[0] == "--range" { "0..1" } else { "1" };
        let b = if pair[1] == "--range" { "0..1" } else { "1" };
        let args = ["show", "alphasess", pair[0], a, pair[1], b];
        let (ok, code, out, err) = w.cv(&args);
        assert!(!ok, "two selectors must be refused: cv {args:?}\n{out}");
        assert_eq!(code, 2, "clap usage errors exit 2\nstderr:\n{err}");
        assert!(
            err.contains("cannot be used with"),
            "conflict must be named: cv {args:?}\n{err}"
        );
    }

    // JSON path honors the same windows.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--json", "--range", "1..2"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["messages"].as_array().unwrap().len(), 1, "{out}");
    let (out, _) = w.cv_ok(&["show", "alphasess", "--json", "--first", "2"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["messages"].as_array().unwrap().len(), 2, "{out}");
    let (out, _) = w.cv_ok(&["show", "alphasess", "--json", "--last", "1"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["messages"].as_array().unwrap().len(), 1, "{out}");
    // And a past-the-end JSON window is empty, not a panic.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--json", "--range", "10..20"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["messages"].as_array().unwrap().len(), 0, "{out}");
}

/// `--thinking <native|text|drop>` means the same thing on every command that emits a session, and
/// nothing else answers to that word. The modes differ in whether a turn whose only content is
/// provider-signed reasoning survives a target that cannot hold the signature.
#[test]
fn thinking_mode_is_one_word_on_every_emitting_command() {
    let w = World::new("think");
    standard_corpus(&w);

    // Present, with the same three values, wherever a session is written out.
    for cmd in ["port", "splice", "pack"] {
        let (ok, _, out, err) = w.cv(&[cmd, "--help"]);
        assert!(ok, "cv {cmd} --help failed:\n{err}");
        for mode in ["native", "text", "drop"] {
            assert!(
                out.contains(mode),
                "cv {cmd} --help must offer --thinking {mode}:\n{out}"
            );
        }
    }

    // An unknown mode is rejected by name, listing what is valid.
    let (_, _, _, err) = w.cv(&["port", "alphasess", "--thinking", "sideways"]);
    assert!(err.contains("sideways"), "the bad value is quoted back:\n{err}");

    // And the word is NOT overloaded: prune's old boolean spelling is gone.
    let (_, code, _, err) = w.cv(&["prune", "alphasess", "--thinking"]);
    assert_eq!(code, 2, "{err}");
    assert!(err.contains("--drop-thinking"), "{err}");
}

// ───────────────────────────── export ─────────────────────────────

#[test]
fn export_formats() {
    let w = World::new("export");
    standard_corpus(&w);

    // Markdown: header metadata + role sections + content.
    let (out, _) = w.cv_ok(&["export", "alphasess"]);
    assert!(out.contains("# alpha adventures"), "{out}");
    assert!(out.contains("- harness: claude"), "{out}");
    assert!(out.contains("- id: alphasess"), "{out}");
    assert!(out.contains("## user"), "{out}");
    assert!(out.contains("zebrafish migration"), "{out}");
    assert!(out.contains("**🔧 Edit**"), "{out}");

    // JSON: the full IR round-trips through serde — and `export` is a DOCUMENT boundary, so what
    // it writes is an OpenSession 0.3 document: the IR led by the version marker.
    let (out, _) = w.cv_ok(&["export", "alphasess", "--format", "json"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["open_session"], "0.3", "{out}");
    assert!(
        out.trim_start().starts_with("{\n  \"open_session\""),
        "the marker leads the document:\n{out}"
    );
    assert_eq!(v["id"], "alphasess", "{out}");
    assert_eq!(v["harness"], "claude", "{out}");
    assert_eq!(v["messages"].as_array().unwrap().len(), 3, "{out}");

    // `show --json` is the RAW IR: the marker belongs to a document, never to a Session.
    let (out, _) = w.cv_ok(&["show", "alphasess", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert!(v.get("open_session").is_none(), "{out}");
    assert_eq!(v["id"], "alphasess", "{out}");

    // HTML left `export` for `share` (the streaming, redacting renderer): the old spelling
    // points there and exits 2.
    let (ok, code, _, err) = w.cv(&["export", "alphasess", "--format", "html"]);
    assert!(!ok && code == 2, "{err}");
    assert!(err.contains("cv share <id>"), "{err}");

    // Unknown format is an error, not a silent default.
    let (_, err) = w.cv_fails(&["export", "alphasess", "--format", "docx"]);
    assert!(err.contains("unknown format"), "{err}");
}

// ───────────────────────────── prune --json ─────────────────────────────

#[test]
fn prune_json_emits_machine_readable_report() {
    let w = World::new("prunejson");
    let big = "x".repeat(4096);
    // A realistic Claude fixture: the in-file sessionId matches the filename (prune reads the
    // source id from the lines, not the path).
    w.write_session(
        "prunesrc",
        &[
            serde_json::json!({
                "type": "user", "uuid": "u1", "sessionId": "prunesrc", "timestamp": "2026-01-01T10:00:00Z",
                "cwd": "/work/proj",
                "message": {"role": "user", "content": "read the big file"}
            }),
            serde_json::json!({
                "type": "assistant", "uuid": "a1", "sessionId": "prunesrc", "timestamp": "2026-01-01T10:01:00Z",
                "cwd": "/work/proj",
                "message": {"role": "assistant", "model": "claude-test-1", "content": [
                    {"type": "text", "text": "reading"},
                    {"type": "tool_use", "id": "t1", "name": "Read", "input": {"file_path": "/big.txt"}}
                ]}
            }),
            serde_json::json!({
                "type": "user", "uuid": "u2", "sessionId": "prunesrc", "timestamp": "2026-01-01T10:02:00Z",
                "message": {"role": "user", "content": [
                    {"type": "tool_result", "tool_use_id": "t1", "content": big, "is_error": false}
                ]}
            }),
            serde_json::json!({
                "type": "assistant", "uuid": "a2", "sessionId": "prunesrc", "timestamp": "2026-01-01T10:03:00Z",
                "cwd": "/work/proj",
                "message": {"role": "assistant", "model": "claude-test-1", "content": [
                    {"type": "text", "text": "done"}
                ]}
            }),
        ],
    );
    let dir = w.home.join(".claude/projects/-work-proj");
    let source_before = fs::read_to_string(dir.join("prunesrc.jsonl")).unwrap();

    // Dry run first: stdout is ONE JSON object; nothing written means honest nulls + a note,
    // and the fixture dir is untouched.
    let (out, _) = w.cv_ok(&[
        "prune",
        "prunesrc",
        "--min-size",
        "100",
        "--keep-last",
        "0",
        "--dry-run",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    assert_eq!(v["source_id"], "prunesrc", "{out}");
    assert_eq!(v["dry_run"], true, "{out}");
    assert!(v["new_id"].is_null(), "unpinned dry-run id must be null:\n{out}");
    assert!(v["new_path"].is_null(), "{out}");
    assert!(v["sidecar_path"].is_null(), "{out}");
    assert!(v["note"].as_str().unwrap().contains("dry run"), "{out}");
    assert_eq!(v["snipped_payloads"], 1, "{out}");
    assert!(
        v["before_bytes"].as_u64().unwrap() > v["after_bytes"].as_u64().unwrap(),
        "{out}"
    );
    assert_eq!(fs::read_dir(&dir).unwrap().count(), 1, "dry run must write nothing");

    // A dry run with --to CAN report the id — it's caller-chosen, not minted.
    let (out, _) = w.cv_ok(&[
        "prune",
        "prunesrc",
        "--min-size",
        "100",
        "--keep-last",
        "0",
        "--dry-run",
        "--to",
        "pinnedsess",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    assert_eq!(v["new_id"], "pinnedsess", "{out}");
    assert!(v["new_path"].is_null(), "still nothing written:\n{out}");

    // Real prune: full ids + real paths in the JSON; the files exist; the source is untouched.
    let (out, _) = w.cv_ok(&[
        "prune",
        "prunesrc",
        "--min-size",
        "100",
        "--keep-last",
        "0",
        "--to",
        "prunedsess",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    assert_eq!(v["source_id"], "prunesrc", "{out}");
    assert_eq!(v["new_id"], "prunedsess", "{out}");
    assert_eq!(v["harness"], "claude", "{out}");
    assert_eq!(v["dry_run"], false, "{out}");
    assert!(v["note"].is_null(), "{out}");
    assert_eq!(v["snipped_payloads"], 1, "{out}");
    assert!(v["tokens_freed"].as_u64().unwrap() > 0, "{out}");
    let new_path = PathBuf::from(v["new_path"].as_str().unwrap());
    assert!(new_path.ends_with("prunedsess.jsonl"), "{out}");
    assert!(new_path.exists(), "pruned session must exist at new_path");
    let sidecar = PathBuf::from(v["sidecar_path"].as_str().unwrap());
    assert!(sidecar.ends_with("prunedsess.flat.jsonl"), "{out}");
    assert!(sidecar.exists(), "sidecar must exist at sidecar_path");
    assert_eq!(
        fs::read_to_string(dir.join("prunesrc.jsonl")).unwrap(),
        source_before,
        "prune must never modify the source session"
    );

    // Without --json the report stays off stdout entirely (status goes to stderr).
    let (out, err) = w.cv_ok(&[
        "prune",
        "prunesrc",
        "--min-size",
        "100",
        "--keep-last",
        "0",
        "--dry-run",
    ]);
    assert!(out.trim().is_empty(), "non-json prune must keep stdout empty:\n{out}");
    assert!(err.contains("pruned"), "{err}");
}

// ───────────────────────────── rewind ─────────────────────────────

/// A keeper session (two compactions) that committed `63cef47…` mid-way, plus one sub-agent that
/// committed `9f00ba5…` — the shapes `cv rewind` exists for.
fn keeper_corpus(w: &World) -> PathBuf {
    let sid = "aaaaaaaa-0000-4000-8000-000000000001";
    let line = |ty: &str, uuid: &str, parent: Option<&str>, message: serde_json::Value| {
        serde_json::json!({"type": ty, "sessionId": sid, "uuid": uuid, "parentUuid": parent,
            "isSidechain": false, "cwd": "/work/proj", "timestamp": "2026-06-01T10:00:00Z", "message": message})
    };
    let boundary = |uuid: &str| {
        serde_json::json!({"type": "system", "subtype": "compact_boundary", "sessionId": sid, "uuid": uuid,
            "parentUuid": null, "isSidechain": false, "compactMetadata": {"trigger": "auto"}})
    };
    let path = w.write_session(
        sid,
        &[
            line("user", "u0", None, serde_json::json!({"role": "user", "content": "fix the gate"})),
            boundary("b1"),
            line("assistant", "a1", Some("b1"), serde_json::json!({"role": "assistant", "content": [
                {"type": "tool_use", "id": "toolu_c", "name": "Bash",
                 "input": {"command": "git commit -am 'gate: name the project'"}}]})),
            line("user", "r1", Some("a1"), serde_json::json!({"role": "user", "content": [
                {"type": "tool_result", "tool_use_id": "toolu_c", "content": "[main 63cef47] gate: name the project"}]})),
            line("assistant", "a2", Some("r1"), serde_json::json!({"role": "assistant", "content": [
                {"type": "text", "text": "landed"}]})),
            boundary("b2"),
            line("user", "u3", Some("b2"), serde_json::json!({"role": "user", "content": "now something else"})),
        ],
    );
    let agent = w
        .home
        .join(".claude/projects/-work-proj")
        .join(sid)
        .join("subagents/agent-a7f5742c50c0b9654.jsonl");
    fs::create_dir_all(agent.parent().unwrap()).unwrap();
    let side = |uuid: &str, parent: Option<&str>, ty: &str, message: serde_json::Value| {
        serde_json::json!({"type": ty, "sessionId": sid, "uuid": uuid, "parentUuid": parent,
            "isSidechain": true, "agentId": "a7f5742c50c0b9654", "cwd": "/work/proj",
            "timestamp": "2026-06-01T11:00:00Z", "message": message})
    };
    let lines = [
        side(
            "s0",
            None,
            "user",
            serde_json::json!({"role": "user", "content": "review lane"}),
        ),
        side(
            "s1",
            Some("s0"),
            "assistant",
            serde_json::json!({"role": "assistant", "content": [
            {"type": "tool_use", "id": "toolu_s", "name": "Bash",
             "input": {"command": "git commit -qam fix && git rev-parse HEAD"}}]}),
        ),
        side(
            "s2",
            Some("s1"),
            "user",
            serde_json::json!({"role": "user", "content": [
            {"type": "tool_result", "tool_use_id": "toolu_s", "content": "9f00ba5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e5e"}]}),
        ),
        side(
            "s3",
            Some("s2"),
            "assistant",
            serde_json::json!({"role": "assistant", "content": [
            {"type": "text", "text": "done"}]}),
        ),
    ];
    let body: String = lines.iter().map(|l| format!("{l}\n")).collect();
    fs::write(&agent, body).unwrap();
    path
}

fn jsonl(path: &std::path::Path) -> Vec<serde_json::Value> {
    fs::read_to_string(path)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect()
}

#[test]
fn rewind_derives_the_agent_as_of_a_commit() {
    let w = World::new("rewind");
    let src = keeper_corpus(&w);
    let before = fs::read(&src).unwrap();
    let out = w.base.join("rw");
    let out_s = out.to_str().unwrap();

    // By commit sha: the cut is the tool result that printed it; the window opens at b1.
    let (stdout, err) = w.cv_ok(&[
        "rewind",
        "aaaaaaaa",
        "--at",
        "63cef473b771e07a",
        "--out",
        out_s,
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).expect("stdout must be pure JSON");
    assert_eq!(v["source_id"], "aaaaaaaa-0000-4000-8000-000000000001", "{stdout}");
    assert_eq!(
        (v["start_line"].as_u64(), v["cut_line"].as_u64()),
        (Some(2), Some(4)),
        "{stdout}"
    );
    assert_eq!(v["evidence"]["kind"], "created", "{stdout}");
    assert_eq!(v["omitted_lines"], 3, "{stdout}");
    let new_id = v["new_id"].as_str().unwrap().to_string();
    let new_path = PathBuf::from(v["new_path"].as_str().unwrap());
    assert_eq!(new_path, out.join(format!("{new_id}.jsonl")));
    let got = jsonl(&new_path);
    assert_eq!(got.len(), 3);
    assert!(got.iter().all(|r| r["sessionId"] == new_id.as_str()), "{got:?}");
    assert!(PathBuf::from(v["provenance_path"].as_str().unwrap()).exists());
    // The resume incantation is `cv resume`'s rendering for the NEW id, in the cut's cwd.
    assert_eq!(
        v["resume"],
        serde_json::json!(["cd /work/proj", format!("claude --resume {new_id}")])
    );
    assert!(err.contains("exact: commit created here"), "{err}");
    assert!(
        err.contains("copy it there first"),
        "an --out elsewhere must say where claude looks:\n{err}"
    );
    assert_eq!(fs::read(&src).unwrap(), before, "rewind must never modify the source");

    // By message index, written to the project dir by default (where `claude --resume` looks).
    let (stdout, _) = w.cv_ok(&["rewind", "aaaaaaaa", "--at", "1", "--to", "rw-by-idx", "--json"]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(v["cut_msg_idx"], 1, "{stdout}");
    assert!(w.home.join(".claude/projects/-work-proj/rw-by-idx.jsonl").exists());
    assert!(w
        .home
        .join(".claude/projects/-work-proj/rw-by-idx.rewind.json")
        .exists());

    // Dry run: nothing written, honest nulls.
    let (stdout, _) = w.cv_ok(&["rewind", "aaaaaaaa", "--full", "--dry-run", "--json"]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(
        (v["dry_run"].as_bool(), v["start_line"].as_u64()),
        (Some(true), Some(1)),
        "{stdout}"
    );
    assert!(v["new_id"].is_null() && v["new_path"].is_null(), "{stdout}");

    // A sha no tool result shows: exit 1 with the reason. A bad --at: exit 2.
    let (_, err) = w.cv_fails(&["rewind", "aaaaaaaa", "--at", "deadbeef1"]);
    assert!(err.contains("deadbeef1") && err.contains("git commit"), "{err}");
    let (ok, code, _, err) = w.cv(&["rewind", "aaaaaaaa", "--at", "nope"]);
    assert!(!ok && code == 2, "{err}");
    let (ok, code, _, err) = w.cv(&["rewind", "aaaaaaaa", "--at", "99"]);
    assert!(!ok && code == 1 && err.contains("message(s)"), "{err}");
}

#[test]
fn rewind_extracts_a_subagent_as_a_standalone_session() {
    let w = World::new("rewindsub");
    keeper_corpus(&w);
    let proj = w.home.join(".claude/projects/-work-proj");

    // `agent-<id>` resolves fleet-wide (as `cv show agent-…` does); the sub-agent's own commit is
    // exact evidence; the session lands in the PARENT's project dir.
    let (stdout, err) = w.cv_ok(&[
        "rewind",
        "agent-a7f5742c",
        "--at",
        "9f00ba5",
        "--to",
        "kept-sub",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap_or_else(|e| panic!("{e}: {stdout}\n{err}"));
    assert_eq!(v["subagent"], true, "{stdout}");
    assert_eq!(
        v["source_session_id"], "aaaaaaaa-0000-4000-8000-000000000001",
        "{stdout}"
    );
    assert_eq!(v["cut_line"], 3, "{stdout}");
    let got = jsonl(&proj.join("kept-sub.jsonl"));
    assert_eq!(got.len(), 3);
    assert!(got
        .iter()
        .all(|r| r["isSidechain"] == false && r.get("agentId").is_none() && r["sessionId"] == "kept-sub"));
    assert!(got[0]["parentUuid"].is_null(), "the root chain starts at a null parent");
    assert!(err.contains("sub-agent of aaaaaaaa"), "{err}");

    // `<parent> --agent <id>` and a plain transcript path reach the same transcript.
    let (stdout, _) = w.cv_ok(&["rewind", "aaaaaaaa", "--agent", "a7f57", "--dry-run", "--json"]);
    assert!(stdout.contains("\"subagent\": true"), "{stdout}");
    let path = proj.join("aaaaaaaa-0000-4000-8000-000000000001/subagents/agent-a7f5742c50c0b9654.jsonl");
    let (stdout, _) = w.cv_ok(&["rewind", path.to_str().unwrap(), "--dry-run", "--json"]);
    let v: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert_eq!(
        (v["subagent"].as_bool(), v["lines_written"].as_u64()),
        (Some(true), Some(4)),
        "{stdout}"
    );

    // The derived session is an ordinary top-level session to the rest of cv.
    let (out, _) = w.cv_ok(&["show", "kept-sub"]);
    assert!(out.contains("review lane"), "{out}");
}

// ───────────────────────────── dataset ─────────────────────────────

#[test]
fn dataset_emits_parseable_jsonl() {
    let w = World::new("dataset");
    standard_corpus(&w);

    let (out, err) = w.cv_ok(&["dataset"]);
    let lines: Vec<&str> = out.lines().filter(|l| !l.trim().is_empty()).collect();
    assert_eq!(
        lines.len(),
        2,
        "one record per session:\nstdout:\n{out}\nstderr:\n{err}"
    );
    for line in &lines {
        let v: serde_json::Value = serde_json::from_str(line).expect("each record is JSON");
        assert!(v["messages"].is_array(), "chatml shape: {line}");
    }
    assert!(err.contains("wrote 2 record(s)"), "{err}");

    // sharegpt shape + redaction scrubs the planted secret from the dataset too.
    let (out, _) = w.cv_ok(&["dataset", "--format", "sharegpt", "--redact"]);
    assert!(!out.contains(SECRET), "dataset --redact leaked the secret:\n{out}");
    for line in out.lines().filter(|l| !l.trim().is_empty()) {
        let v: serde_json::Value = serde_json::from_str(line).expect("valid JSON");
        assert!(v["conversations"].is_array(), "sharegpt shape: {line}");
    }

    let (_, err) = w.cv_fails(&["dataset", "--format", "parquet"]);
    assert!(err.contains("unknown format"), "{err}");
}

// ───────────────────────────── events / touched ─────────────────────────────

#[test]
fn events_and_touched() {
    let w = World::new("events");
    standard_corpus(&w);

    // `cv events` ingests on the spot (no prior `cv index` needed).
    let (out, _) = w.cv_ok(&["events", "alphasess"]);
    assert!(out.contains("event(s) in claude:alphases"), "{out}");
    assert!(out.contains("file_edit"), "{out}");
    assert!(out.contains("/work/proj/src/widget.rs"), "{out}");

    // Kind filter: no command events in this session — friendly empty message, exit 0.
    let (out, _) = w.cv_ok(&["events", "alphasess", "--kind", "command"]);
    assert!(out.contains("no \"command\" events"), "{out}");

    // A chat-only session has no tool events at all.
    let (out, _) = w.cv_ok(&["events", "betasess"]);
    assert!(out.contains("no tool events"), "{out}");

    // touched: absolute path and repo-relative suffix both match; --edits-only keeps it.
    let (out, _) = w.cv_ok(&["touched", "/work/proj/src/widget.rs"]);
    assert!(out.contains("1 session(s) touched"), "{out}");
    assert!(out.contains("alphases"), "{out}");
    let (out, _) = w.cv_ok(&["touched", "src/widget.rs", "--edits-only"]);
    assert!(out.contains("alphases"), "{out}");
    assert!(out.contains("edit(s)"), "{out}");

    // An untouched path: explicit empty-result hint, exit 0.
    let (out, _) = w.cv_ok(&["touched", "src/nonexistent.rs"]);
    assert!(out.contains("no sessions touched"), "{out}");

    // Unknown session id is a real error.
    let (_, err) = w.cv_fails(&["events", "bogus-id"]);
    assert!(err.contains("no session matching"), "{err}");
}

// ───────────────────────────── export --redact ─────────────────────────────

#[test]
fn export_redact_scrubs_planted_secret() {
    let w = World::new("redact");
    standard_corpus(&w);

    // The secret IS in the raw transcript (sanity), and `cv show` prints it.
    let (out, _) = w.cv_ok(&["show", "alphasess"]);
    assert!(out.contains(SECRET), "fixture sanity: secret present in show:\n{out}");

    // md: gone from stdout, replaced by a placeholder; the per-class tally is on stderr.
    let (out, err) = w.cv_ok(&["export", "alphasess", "--redact"]);
    assert!(!out.contains(SECRET), "export --redact leaked the secret:\n{out}");
    assert!(out.contains("[REDACTED:api_key]"), "{out}");
    assert!(out.contains("## user"), "still the export rendering: {out}");
    assert!(err.contains("redacted") && err.contains("1 api_key"), "{err}");

    // json: the whole OpenSession document is clean, and still the document (marker led).
    let (out, err) = w.cv_ok(&["export", "alphasess", "--format", "json", "--redact"]);
    assert!(
        !out.contains(SECRET),
        "export --format json --redact leaked the secret:\n{out}"
    );
    let v: serde_json::Value = serde_json::from_str(&out).expect("valid JSON");
    assert_eq!(v["open_session"], "0.3", "{out}");
    assert_eq!(v["id"], "alphasess");
    assert!(err.contains("1 api_key"), "{err}");

    // Without the flag nothing is scrubbed and nothing is tallied.
    let (out, err) = w.cv_ok(&["export", "alphasess"]);
    assert!(out.contains(SECRET), "{out}");
    assert!(!err.contains("redacted"), "{err}");

    // The removed command errors with the replacement, exit 2.
    let (ok, code, _, err) = w.cv(&["redact", "alphasess", "--stats"]);
    assert!(!ok && code == 2, "{err}");
    assert!(err.contains("cv export <id> --redact"), "{err}");
}

// ───────────────────────────── error-path honesty ─────────────────────────────

#[test]
fn error_paths_exit_nonzero_with_stderr() {
    let w = World::new("errs");
    standard_corpus(&w);

    // `show` tries the id as a sub-agent too before giving up — its message says so.
    let (_, err) = w.cv_fails(&["show", "nonexistent-id"]);
    assert!(err.contains("no session (and no sub-agent) matching"), "{err}");

    let (_, err) = w.cv_fails(&["export", "nonexistent-id"]);
    assert!(err.contains("no session matching"), "{err}");

    let (_, err) = w.cv_fails(&["show", "nonexistent-id", "--tree"]);
    assert!(err.contains("no session matching"), "{err}");

    let (_, err) = w.cv_fails(&["resume", "nonexistent-id"]);
    assert!(err.contains("no session matching"), "{err}");

    let (_, err) = w.cv_fails(&["show", "alphasess", "--harness", "marsrover"]);
    assert!(err.contains("unknown harness"), "{err}");

    // Every name this release removed: gone, but never silently — each one exits 2 (a caller
    // mistake, not a failure) with a line naming the version and the replacement. The 0.11
    // tombstones left at 0.15; these leave at the next release.
    let removed: &[(&[&str], &str)] = &[
        // `timeline` was `ls` with the shown window reversed.
        (&["timeline", "--limit", "5"], "cv ls --sort-by updated --asc"),
        // `redact` was `export` with the scrubber in front.
        (&["redact", "alphasess", "--format", "json"], "cv export <id> --redact"),
        // `diff` was a role+text prefix compare; export both and use a real diff.
        (&["diff", "alphasess", "betasess"], "cv export <id> --format md"),
        // `export --format html` had a second, non-streaming renderer; `share` is the one.
        (&["export", "alphasess", "--format", "html"], "cv share <id>"),
        // `adopt --list/--orphans` were lanes tables.
        (&["adopt", "--list", "alphasess"], "cv lanes alphasess"),
        (&["adopt", "--orphans"], "cv lanes --recent <N> --unfinished"),
        // `formats check` needed a checkout: it is the test; `census` is plain `formats`.
        (
            &["formats", "check"],
            "cargo test -p clustervision-core --test formats_manifest",
        ),
        (&["formats", "census"], "cv formats"),
        // `fork` was `splice <id>:..N`; `loom` was a two-span `splice`.
        (
            &["fork", "alphasess", "--at", "2", "--session"],
            "cv splice <id>:..N --session",
        ),
        (
            &["loom", "alphasess", "--at", "2", "--graft", "betasess", "--from", "1"],
            "cv splice <base>:..N <other>:M..",
        ),
        // `tree`, `prompts` and `compaction` were views of one session: `show` flags now.
        (&["tree", "alphasess"], "cv show <id> --tree"),
        (&["prompts", "alphasess", "--json"], "cv show <id> --kind prompt,answer"),
        (
            &["compaction", "alphasess", "--summaries"],
            "cv show <id> --kind compaction_boundary,compaction_summary",
        ),
    ];
    for (args, pointer) in removed {
        let (ok, code, out, err) = w.cv(args);
        assert!(!ok, "cv {args:?} must not still work\nstdout:\n{out}");
        assert_eq!(code, 2, "cv {args:?} must exit 2 (caller mistake)\nstderr:\n{err}");
        assert!(!err.contains("panicked"), "cv {args:?} panicked:\n{err}");
        assert!(
            err.contains("0.15.0") || err.contains("is now"),
            "cv {args:?} must say when it went away:\n{err}"
        );
        assert!(err.contains(pointer), "cv {args:?} must point at {pointer:?}:\n{err}");
    }
    // The 0.11 tombstones are plain unknown names now: clap's error, still exit 2, no pointer.
    let (ok, code, _, err) = w.cv(&["convert", "alphasess"]);
    assert!(!ok && code == 2 && err.contains("unrecognized subcommand"), "{err}");
    let (ok, code, _, err) = w.cv(&["prune", "alphasess", "--retrieve", "t1"]);
    assert!(!ok && code == 2 && err.contains("unexpected argument"), "{err}");
    // The pointers are real: the replacement parses (it fails on the harness, not the grammar).
    let (_, err) = w.cv_fails(&["port", "alphasess", "--harness", "marsrover"]);
    assert!(err.contains("unknown"), "{err}");

    // A splice spec carries the same `A..B` window grammar as `--range`, split off the END of the
    // id (so a `harness:id` prefix still works): the 0.10 `<id>:A-B` points at its replacement,
    // and a non-numeric window is a bad spec, not a mystery id.
    let (_, err) = w.cv_fails(&["splice", "alphasess:1-2"]);
    assert!(err.contains("bad spec") && err.contains("<id>:A..B"), "{err}");
    let (_, err) = w.cv_fails(&["splice", "alphasess:zz..3"]);
    assert!(err.contains("bad spec"), "{err}");

    // An empty id matches every session: the ambiguity is named, not silently picked, and the
    // candidates are listed as the `harness:full-id` you can paste straight back in (§2).
    let (ok, code, out, err) = w.cv(&["events", ""]);
    assert!(!ok, "an ambiguous id must not be silently resolved:\n{out}");
    assert_eq!(code, 2, "{err}");
    assert!(err.contains("ambiguous id"), "{err}");
    assert!(err.contains("2 candidates"), "{err}");
    assert!(
        err.contains("claude:alphasess") && err.contains("claude:betasess"),
        "candidates must be listed as harness:full-id:\n{err}"
    );
    // …and pasting one back in resolves it.
    w.cv_ok(&["events", "claude:alphasess"]);
}

// ───────────────────────────── blame on a non-file ─────────────────────────────

#[test]
fn blame_outside_repo_and_missing_file() {
    let w = World::new("blame");
    standard_corpus(&w);

    // A path that exists nowhere, outside any git repo: must not panic. Either outcome (clean
    // degradation to catalog-only mode, or a clear error) is fine — but never a panic/signal.
    let (_ok, code, out, err) = w.cv(&["blame", "/not/a/file"]);
    assert_ne!(code, -1, "cv blame died by signal\nstderr:\n{err}");
    assert!(!err.contains("panicked"), "panic in blame:\n{err}");
    assert!(
        out.contains("not inside a git repository") || !err.trim().is_empty(),
        "blame must explain itself\nstdout:\n{out}\nstderr:\n{err}"
    );
}

// ───────────────────────────── show --tree ─────────────────────────────

#[test]
fn show_tree_renders() {
    let w = World::new("tree");
    standard_corpus(&w);

    let (out, _) = w.cv_ok(&["show", "alphasess", "--tree"]);
    assert!(out.contains("# alpha adventures"), "{out}");
    assert!(out.contains("3 msg"), "{out}");
}

// ───────────────────────────── stats / ls --asc ─────────────────────────────

#[test]
fn stats_and_ls_asc() {
    let w = World::new("stats");
    standard_corpus(&w);

    let (out, _) = w.cv_ok(&["stats"]);
    assert!(out.contains("2 session(s) · 7 message(s)"), "{out}");
    assert!(out.contains("claude"), "{out}");

    // `ls` is newest first; `--asc` prints the same rows oldest → newest (the old `timeline` feed).
    let (out, _) = w.cv_ok(&["ls"]);
    assert!(pos(&out, "alphases") < pos(&out, "betasess"), "{out}");
    let (out, _) = w.cv_ok(&["ls", "--sort-by", "updated", "--asc"]);
    assert!(out.contains("2 session(s)"), "{out}");
    assert!(pos(&out, "betasess") < pos(&out, "alphases"), "{out}");
    // `--asc` flips the order of the shown window, never its membership: `--limit 1` is still
    // the newest session, printed alone.
    let (out, _) = w.cv_ok(&["ls", "--asc", "--limit", "1", "--json"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(&out).unwrap();
    assert_eq!(rows.len(), 1, "{out}");
    assert_eq!(rows[0]["id"], "alphasess", "{out}");

    // The removed command errors with the replacement, exit 2.
    let (ok, code, _, err) = w.cv(&["timeline"]);
    assert!(!ok && code == 2, "{err}");
    assert!(err.contains("cv ls --sort-by updated --asc"), "{err}");
}

#[test]
fn stats_tokens_totals_usage_per_model() {
    let w = World::new("stats-tokens");
    let reply = |uuid: &str, id: &str, model: &str| {
        serde_json::json!({
            "type": "assistant", "uuid": uuid, "sessionId": "s", "timestamp": "2026-03-01T09:05:00Z",
            "message": {"id": id, "role": "assistant", "model": model,
                "content": [{"type": "text", "text": "ok"}],
                "usage": {"input_tokens": 5, "cache_read_input_tokens": 2_000_000,
                          "cache_creation_input_tokens": 1_000, "output_tokens": 300}}
        })
    };
    w.write_session(
        "toksess",
        &[
            user_line("u1", "2026-03-01T09:00:00Z", "go"),
            reply("a1", "msg_1", "claude-opus-5-5"),
            // The same streamed response's second content-block line: one call, not two.
            reply("a2", "msg_1", "claude-opus-5-5"),
            reply("a3", "msg_2", "claude-fable-5-1"),
        ],
    );

    let (out, _) = w.cv_ok(&["stats", "--tokens"]);
    assert!(out.contains("1 repeated usage record(s) skipped"), "{out}");
    assert!(out.contains("claude-opus-5-5"), "{out}");
    assert!(out.contains("claude-fable-5-1"), "{out}");
    // 2 calls × (5 + 2,000,000 + 1,000 + 300) = 4,002,610.
    assert!(out.contains("4.0M"), "{out}");

    let (json, _) = w.cv_ok(&["stats", "--tokens", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(v["tokens"]["total"]["calls"], 2);
    assert_eq!(v["tokens"]["total"]["total"], 4_002_610);
    assert_eq!(v["tokens"]["total"]["uncached"], 2_610);
    assert_eq!(v["tokens"]["duplicates"], 1);

    let (json, _) = w.cv_ok(&["stats", "--json"]);
    let v: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert!(
        v.get("tokens").is_none(),
        "without --tokens the payload stays catalog-only"
    );
}

/// Resolution by unique id prefix works across commands (find() contract the CLI leans on).
#[test]
fn id_prefix_resolution() {
    let w = World::new("prefix");
    standard_corpus(&w);

    let (out, _) = w.cv_ok(&["show", "alpha"]);
    assert!(out.contains("# alpha adventures"), "{out}");

    let (out, _) = w.cv_ok(&["show", "beta", "--harness", "claude"]);
    assert!(out.contains("quokkas"), "{out}");
}

// ───────────────────────────── extra claude roots ─────────────────────────────

/// Claude Code sessions outside `~/.claude` (a second `CLAUDE_CONFIG_DIR`, e.g. one per agent
/// seat) are listed, searched and read when named by `$CLUSTERVISION_HOME/claude-roots` (with a
/// `*` seat wildcard) or `$CLUSTERVISION_CLAUDE_ROOTS`; the default root keeps working beside them.
#[test]
fn extra_claude_roots_are_listed_and_read() {
    let w = World::new("roots");
    standard_corpus(&w);
    let seat_proj = w.home.join("seats/bonsai/claude/projects/-work-proj");
    fs::create_dir_all(&seat_proj).unwrap();
    let seat_line = user_line("s1", "2026-07-01T10:00:00Z", "the seat asks about narwhals");
    fs::write(seat_proj.join("seatsess.jsonl"), format!("{seat_line}\n")).unwrap();
    let env_proj = w.base.join("elsewhere/projects/-work-proj");
    fs::create_dir_all(&env_proj).unwrap();
    let env_line = user_line("e1", "2026-07-02T10:00:00Z", "the env root asks about axolotls");
    fs::write(env_proj.join("envsess.jsonl"), format!("{env_line}\n")).unwrap();

    // Not configured yet: the seat session is invisible, exactly as before.
    w.cv_fails(&["show", "seatsess"]);

    fs::write(w.cv_home.join("claude-roots"), "# agent seats\n~/seats/*/claude\n").unwrap();
    let (out, _) = w.cv_ok(&["show", "seatsess"]);
    assert!(out.contains("narwhals"), "{out}");
    let (out, _) = w.cv_ok(&["show", "alphasess"]);
    assert!(out.contains("zebrafish"), "the default root still works:\n{out}");
    let (out, _) = w.cv_ok(&["ls"]);
    assert!(out.contains("3 session(s)"), "{out}");
    let (out, _) = w.cv_ok(&["search", "narwhals"]);
    assert!(out.contains("seatsess"), "{out}");

    let roots = w.base.join("elsewhere");
    let (ok, _, out, err) = w.cv_env(
        &["show", "envsess"],
        &[("CLUSTERVISION_CLAUDE_ROOTS", roots.to_str().unwrap())],
    );
    assert!(ok, "stdout:\n{out}\nstderr:\n{err}");
    assert!(out.contains("axolotls"), "{out}");
}

// ───────────────────────────── task substrate: identity + sanitizing ─────────────────────────────

/// Extract the task id `cv task open` prints on its own line (the uuid-shaped one).
fn opened_task_id(stdout: &str) -> String {
    stdout
        .lines()
        .map(str::trim)
        .find(|l| l.len() == 36 && l.chars().filter(|c| *c == '-').count() == 4)
        .unwrap_or_else(|| panic!("no task id in open output:\n{stdout}"))
        .to_string()
}

/// G4: identity is environment, not assertion — CV_ENDPOINT is the default `--from`, an explicit
/// flag still wins, and an identity-bearing verb with no resolvable identity is a hard error.
#[test]
fn task_identity_resolution_order() {
    let w = World::new("task-ident");

    // Open needs no ceremony: bare command records "cv".
    let (out, _) = w.cv_ok(&["task", "open", "first task"]);
    let id = opened_task_id(&out);
    let (json, _) = w.cv_ok(&["task", "show", &id, "--json"]);
    assert!(json.contains(r#""opened_by": "cv""#), "{json}");

    // Identity-bearing verb without CV_ENDPOINT or --from: refuse, name the cure.
    let (ok, _, _, err) = w.cv_env(&["task", "claim", &id], &[]);
    assert!(!ok, "claim without identity must fail");
    assert!(
        err.contains("set CV_ENDPOINT or pass --from"),
        "error names the cure:\n{err}"
    );

    // CV_ENDPOINT alone resolves it.
    let (ok, code, out, err) = w.cv_env(&["task", "claim", &id], &[("CV_ENDPOINT", "agent:demo")]);
    assert!(ok, "claim with CV_ENDPOINT: exit {code}\n{out}\n{err}");
    let (json, _) = w.cv_ok(&["task", "show", &id, "--json"]);
    assert!(json.contains(r#""assignee": "agent:demo""#), "{json}");

    // Explicit --from beats the env var.
    let (ok, ..) = w.cv_env(
        &["task", "release", &id, "--from", "agent:explicit"],
        &[("CV_ENDPOINT", "agent:demo")],
    );
    assert!(ok);
    let (json, _) = w.cv_ok(&["task", "show", &id, "--json", "--events"]);
    assert!(
        json.contains(r#""by": "agent:explicit""#),
        "explicit --from wins:\n{json}"
    );

    // Whitespace-only CV_ENDPOINT is no identity.
    let (ok, _, _, err) = w.cv_env(&["task", "claim", &id], &[("CV_ENDPOINT", "   ")]);
    assert!(!ok && err.contains("CV_ENDPOINT"), "{err}");
}

/// G5 + G8: an ANSI-bomb title renders stripped on every task surface, and list/inbox rows carry
/// an age column (inbox marks >24h rows with a leading marker — not testable with a fresh log,
/// covered in unit tests; here we prove the column exists).
#[test]
fn task_surfaces_sanitize_and_age() {
    let w = World::new("task-ansi");

    let bomb = "evil\u{1b}]0;pwned\u{7}title \u{1b}[31mred\nline";
    let (out, _) = w.cv_ok(&["task", "open", bomb]);
    let id = opened_task_id(&out);

    let (out, _) = w.cv_ok(&["task", "list"]);
    assert!(!out.contains('\u{1b}'), "list leaks ESC:\n{out:?}");
    assert!(out.contains("eviltitle red line"), "stripped title renders:\n{out}");
    assert!(out.contains("0s") || out.contains("1s"), "age column present:\n{out}");

    let (out, _) = w.cv_ok(&["task", "show", &id]);
    assert!(!out.contains('\u{1b}'), "show leaks ESC:\n{out:?}");

    // Assign it so the inbox has a row, then check the inbox strips too.
    let (ok, ..) = w.cv_env(&["task", "claim", &id], &[("CV_ENDPOINT", "agent:demo")]);
    assert!(ok);
    let (out, _) = w.cv_ok(&["task", "inbox", "agent:demo"]);
    assert!(!out.contains('\u{1b}'), "inbox leaks ESC:\n{out:?}");
    assert!(out.contains("claimed work (1):"), "inbox groups by reason:\n{out}");
}

/// The land facet's verbs and flags went away in 0.15.0: each old spelling errors with a pointer
/// and exit 2, and `done` labels itself self-reported.
#[test]
fn task_land_facet_verbs_and_flags_are_removed_with_pointers() {
    let w = World::new("task-land-removed");
    let (out, _) = w.cv_ok(&["task", "open", "finish it"]);
    let id = opened_task_id(&out);
    let removed: &[&[&str]] = &[
        &["task", "propose", &id, "--branch", "x"],
        &["task", "reroute", &id, "--to", "y"],
        &["task", "pass", &id],
        &["task", "refute", &id],
        &["task", "verify", "--all"],
        &["task", "debt"],
        &["task", "stats"],
        &["task", "claim", &id, "--from", "a", "--token", "t"],
        &["task", "done", &id, "--check-cmd", "true"],
        &["task", "split", &id, "--dry-run"],
        &["task", "watch", "ember"],
    ];
    for args in removed {
        let (ok, code, out, err) = w.cv(args);
        assert!(!ok, "cv {args:?} must not still work\nstdout:\n{out}");
        assert_eq!(code, 2, "cv {args:?} must exit 2 (caller mistake)\nstderr:\n{err}");
        assert!(
            err.contains("removed in 0.15.0"),
            "cv {args:?} must say when it went away:\n{err}"
        );
        assert!(
            err.contains(" — ") && err.matches('`').count() >= 2,
            "cv {args:?} must point at a replacement:\n{err}"
        );
    }
    let (out, _) = w.cv_ok(&["task", "list", "--all"]);
    assert!(
        out.contains("open"),
        "none of the refused commands wrote anything:\n{out}"
    );
    w.cv_ok(&["task", "done", &id, "--observed", "tests green in sess-1"]);
    let (out, _) = w.cv_ok(&["task", "show", &id]);
    assert!(
        out.contains("done:     self-reported") && out.contains("tests green in sess-1"),
        "a completion is labeled as the agent's own word:\n{out}"
    );
}

/// `cv board` went away in 0.15.0: every spelling errors with a pointer at the task log, exit 2.
#[test]
fn board_is_removed_with_a_pointer() {
    let w = World::new("board-removed");
    for args in [
        &["board", "post", "general", "hi"][..],
        &["board", "read", "general"],
        &["board", "channels"],
    ] {
        let (ok, code, out, err) = w.cv(args);
        assert!(!ok, "cv {args:?} must not still work\nstdout:\n{out}");
        assert_eq!(code, 2, "cv {args:?} must exit 2\nstderr:\n{err}");
        assert!(
            err.contains("removed in 0.15.0") && err.contains("cv task events"),
            "{err}"
        );
    }
    assert!(!w.cv_home.join("board").exists(), "nothing wrote a board dir");
}

// ───────────────────────── cv task ergonomics (0.12.0) ─────────────────────────

/// `--body-file`, `--tags`/`list --tag`, `--blocked-by`/`--blocks` with the blocked marker and
/// `show`'s relation lines, `note --file`, `--tsv`.
#[test]
fn task_open_relations_tags_and_file_bodies() {
    let w = World::new("task-ergo");
    let brief = w.base.join("brief.md");
    fs::write(
        &brief,
        "# The brief\n\nA body that is a document, not a shell string.\n",
    )
    .unwrap();

    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "FOUNDATION: the thing others wait on",
        "--tags",
        "lean,deploy",
    ]);
    let a = opened_task_id(&out);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "DEPENDENT: needs the foundation",
        "--body-file",
        brief.to_str().unwrap(),
        "--blocked-by",
        &a,
        "--tags",
        "lean",
    ]);
    let b = opened_task_id(&out);
    let (out, _) = w.cv_ok(&["task", "open", "UPSTREAM: blocks the foundation", "--blocks", &a]);
    let c = opened_task_id(&out);

    // The body came from the file.
    let (json, _) = w.cv_ok(&["task", "show", &b, "--json"]);
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert!(t["body"].as_str().unwrap().contains("not a shell string"), "{json}");
    assert_eq!(t["tags"], serde_json::json!(["lean"]), "{json}");
    assert_eq!(t["blocked_by"], serde_json::json!([a]), "{json}");
    // `--blocks` wrote the relation on the OTHER task.
    let (json, _) = w.cv_ok(&["task", "show", &a, "--json"]);
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(t["blocked_by"], serde_json::json!([c]), "{json}");
    assert_eq!(t["tags"], serde_json::json!(["lean", "deploy"]), "{json}");

    // show: tags, blocked by (with the blocker's state and title), blocks (the reverse).
    let (out, _) = w.cv_ok(&["task", "show", &a]);
    assert!(out.contains("tags:     lean, deploy"), "{out}");
    assert!(
        out.contains("blocked by: ") && out.contains("[open] UPSTREAM: blocks the foundation"),
        "{out}"
    );
    assert!(out.contains("⊘ BLOCKED"), "{out}");
    assert!(
        out.contains("blocks:   ") && out.contains("DEPENDENT: needs the foundation"),
        "{out}"
    );

    // list: blocked rows carry the marker; --tag filters; ids are rendered at a unique length.
    let (out, _) = w.cv_ok(&["task", "list"]);
    let blocked_rows = |out: &str| {
        out.lines()
            .filter(|l| l.starts_with(|c: char| c.is_ascii_hexdigit()) && l.contains("⊘ "))
            .count()
    };
    assert_eq!(blocked_rows(&out), 2, "A and B are blocked:\n{out}");
    assert!(out.contains("⊘ = blocked"), "{out}");
    let (out, _) = w.cv_ok(&["task", "list", "--tag", "deploy"]);
    assert!(out.contains("FOUNDATION") && !out.contains("DEPENDENT"), "{out}");
    let (out, _) = w.cv_ok(&["task", "list"]);
    for line in out.lines().filter(|l| l.starts_with(|c: char| c.is_ascii_hexdigit())) {
        let shown = line.split_whitespace().next().unwrap();
        let (ok, _, _, err) = w.cv(&["task", "show", shown]);
        assert!(ok, "the prefix `list` prints must resolve in `show`: {shown}\n{err}");
    }

    // Finishing the upstream task unblocks A without another event.
    w.cv_ok(&["task", "done", &c, "--observed", "merged"]);
    let (out, _) = w.cv_ok(&["task", "show", &a]);
    assert!(!out.contains("⊘ BLOCKED"), "{out}");
    let (out, _) = w.cv_ok(&["task", "list"]);
    assert_eq!(blocked_rows(&out), 1, "only B stays blocked:\n{out}");

    // tsv: one line per task, seven cells, full ids, no alignment.
    let (out, _) = w.cv_ok(&["task", "list", "--tsv"]);
    assert_eq!(out.lines().count(), 2, "{out}");
    let cells: Vec<&str> = out.lines().find(|l| l.starts_with(&b)).unwrap().split('\t').collect();
    assert_eq!(cells.len(), 7, "{cells:?}");
    assert_eq!(cells[1], "open");
    assert_eq!(cells[5], "DEPENDENT: needs the foundation");
    assert_eq!(cells[6], a);

    // `--wide` went away in 0.15.0; the flag points at `show --brief`.
    let (ok, code, _, err) = w.cv(&["task", "list", "--wide"]);
    assert!(!ok && code == 2, "{err}");
    assert!(
        err.contains("removed in 0.15.0") && err.contains("show <id> --brief"),
        "{err}"
    );

    // note --file.
    let note = w.base.join("note.txt");
    fs::write(&note, "progress from a file").unwrap();
    w.cv_ok(&["task", "note", &b, "--file", note.to_str().unwrap()]);
    let (out, _) = w.cv_ok(&["task", "show", &b]);
    assert!(out.contains("progress from a file"), "{out}");
    let (ok, ..) = w.cv(&["task", "note", &b]);
    assert!(!ok, "note needs text or --file");

    // tag / block verbs after the fact; a self-block is refused; an unknown blocker is refused.
    w.cv_ok(&["task", "tag", &b, "deploy"]);
    let (json, _) = w.cv_ok(&["task", "show", &b, "--json"]);
    assert!(json.contains("\"deploy\""), "{json}");
    let (ok, _, _, err) = w.cv(&["task", "block", &b, "--by", &b]);
    assert!(!ok && err.contains("cannot block itself"), "{err}");
    let (ok, _, _, err) = w.cv(&["task", "open", "typo", "--blocked-by", "ffffffff"]);
    assert!(
        !ok && err.contains("no task matches"),
        "relations resolve before the open:\n{err}"
    );
    let (out, _) = w.cv_ok(&["task", "list", "--all"]);
    assert!(!out.contains("typo"), "a refused open leaves nothing behind:\n{out}");
}

/// `sweep` observes git and the filesystem and prints candidates; it closes nothing.
#[test]
fn task_sweep_names_merged_branches_and_missing_issue_paths_without_closing() {
    let w = World::new("task-sweep");
    let repo = w.base.join("repo");
    fs::create_dir_all(&repo).unwrap();
    let git = |args: &[&str]| {
        let out = Command::new("git")
            .args(args)
            .current_dir(&repo)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@t")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@t")
            .env("HOME", &w.home)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
    };
    git(&["init", "-q", "-b", "main"]);
    fs::write(repo.join("a.txt"), "a").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "init"]);
    git(&["checkout", "-q", "-b", "k-ran"]);
    fs::write(repo.join("b.txt"), "b").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "work"]);
    git(&["checkout", "-q", "main"]);
    git(&["merge", "-q", "--no-ff", "-m", "merge", "k-ran"]);
    git(&["checkout", "-q", "-b", "p3b1"]);
    fs::write(repo.join("c.txt"), "c").unwrap();
    git(&["add", "."]);
    git(&["commit", "-q", "-m", "unmerged work"]);
    git(&["checkout", "-q", "main"]);
    fs::write(repo.join("plan.md"), "plan").unwrap();

    let r = repo.to_str().unwrap();
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "K-RAN: run claim",
        "--repo",
        r,
        "--body",
        "one commit on branch `k-ran`, not pushed",
    ]);
    let merged = opened_task_id(&out);
    w.cv_ok(&[
        "task",
        "open",
        "P3B1: receiver",
        "--repo",
        r,
        "--body",
        "work is on `p3b1`",
    ]);
    w.cv_ok(&["task", "open", "PLAN: keep", "--repo", r, "--issue", "plan.md"]);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "GONE: issue file deleted",
        "--repo",
        r,
        "--issue",
        "docs/gone.md",
    ]);
    let gone = opened_task_id(&out);
    w.cv_ok(&[
        "task",
        "open",
        "WORDS: a body that says fix and main",
        "--repo",
        r,
        "--body",
        "fix main",
    ]);
    w.cv_ok(&[
        "task",
        "open",
        "OTHER REPO: names k-ran but lives elsewhere",
        "--repo",
        w.base.to_str().unwrap(),
        "--body",
        "k-ran",
    ]);

    let (out, _) = w.cv_ok(&["task", "sweep", "--repo", r]);
    assert!(out.contains("2 candidate(s)"), "{out}");
    assert!(
        out.contains("K-RAN: run claim") && out.contains("names branch `k-ran`, merged into main"),
        "{out}"
    );
    assert!(
        out.contains("GONE: issue file deleted") && out.contains("issue path no longer exists"),
        "{out}"
    );
    assert!(
        !out.contains("P3B1") && !out.contains("PLAN:") && !out.contains("WORDS") && !out.contains("OTHER REPO"),
        "{out}"
    );
    assert!(out.contains("nothing was closed"), "{out}");
    // Nothing changed state.
    let (json, _) = w.cv_ok(&["task", "show", &merged, "--json"]);
    assert!(json.contains("\"state\": \"open\""), "{json}");
    let (json, _) = w.cv_ok(&["task", "sweep", "--repo", r, "--json"]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(&json).unwrap();
    assert_eq!(rows.len(), 2);
    assert!(rows.iter().any(|x| x["task_id"] == gone));
}

// ───────────────────────────── decisions: decide / resolve / inbox / split ─────────────────────────────

/// Replace the volatile parts of a rendering (ids, local timestamps, ages) with placeholders so
/// a golden can be compared across machines and clocks.
fn normalize(s: &str) -> String {
    let s = regex::Regex::new(r"\b[0-9a-f]{8}-[0-9a-f]{1,4}(?:-[0-9a-f]{1,4}){0,3}(?:-[0-9a-f]{1,12})?\b")
        .unwrap()
        .replace_all(s, "<id>");
    let s = regex::Regex::new(r"\b\d{4}-\d\d-\d\d \d\d:\d\d\b")
        .unwrap()
        .replace_all(&s, "<ts>");
    let s = regex::Regex::new(r"\b\d\d-\d\d \d\d:\d\d\b")
        .unwrap()
        .replace_all(&s, "<ts>");
    regex::Regex::new(r"\b\d+[smhdw] ago\b")
        .unwrap()
        .replace_all(&s, "<age> ago")
        .into_owned()
}

/// `inbox` orders decisions, then assigned actions, then claimed work; `--md` renders the whole
/// inbox as one Markdown page (bodies, the first line of each note) — pinned as a normalized golden.
#[test]
fn task_inbox_orders_decisions_first_and_renders_markdown() {
    let w = World::new("inbox-md");
    let (out, _) = w.cv_ok(&["task", "open", "the claimed one", "--body", "claimed body"]);
    let c = opened_task_id(&out);
    assert!(w.cv_env(&["task", "claim", &c], &[("CV_ENDPOINT", "ember")]).0);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "write the docs",
        "--assignee",
        "ember",
        "--body",
        "First line of the action.\n\nSecond paragraph.",
    ]);
    let a = opened_task_id(&out);
    w.cv_ok(&[
        "task",
        "note",
        &a,
        "a note with two lines\nsecond line hidden in md",
        "--from",
        "orchestrator:x",
    ]);
    let (out, _) = w.cv_ok(&[
        "task",
        "decide",
        "P6: WHO MAY REFILL a purse",
        "--for",
        "ember",
        "--default",
        "keep open",
        "--option",
        "per-refill consent",
        "--body",
        "today anyone may fund any purse.",
        "--from",
        "orchestrator:x",
    ]);
    let d = opened_task_id(&out);
    plant_legacy_tag_decision(
        &w,
        "01a0f000-0000-7000-8000-00000000000b",
        "legacy decision by tag",
        "ember",
    );

    let (out, _) = w.cv_ok(&["task", "inbox", "ember"]);
    let dec = out.find("decisions owed (2):").expect(&out);
    let assigned = out.find("assigned actions (1):").expect(&out);
    let claimed = out.find("claimed work (1):").expect(&out);
    assert!(dec < assigned && assigned < claimed, "group order:\n{out}");
    assert!(
        out.find("P6: WHO MAY REFILL").unwrap() < out.find("legacy decision by tag").unwrap(),
        "{out}"
    );

    let (md, _) = w.cv_ok(&["task", "inbox", "ember", "--md"]);
    let got = normalize(&md);
    let expected = "\
# Inbox for ember — <ts>

2 decision(s) owed · 1 assigned action(s) · 1 claimed · 3 unread

## Decisions owed (2)

### 1. P6: WHO MAY REFILL a purse

`<id>` · open · asked <age> ago by orchestrator:x · **unread** (last: orchestrator:x)

- **default:** keep open
- alternative: per-refill consent
- resolve: `cv task resolve <id> --accept-default --from ember`

today anyone may fund any purse.

### 2. legacy decision by tag

`<id>` · open · waiting <age> ago by cv · **unread** (last: cv)

## Assigned actions (1)

### 3. write the docs

`<id>` · open · waiting <age> ago by cv · **unread** (last: orchestrator:x)

First line of the action.

Second paragraph.

notes (1):

- _orchestrator:x, <ts>:_ a note with two lines

## Claimed work (1)

### 4. the claimed one

`<id>` · claimed · waiting <age> ago by cv

claimed body

";
    assert_eq!(got, expected, "--md golden (normalized):\n{md}");
    let _ = d;
}

/// `show --notes-last N` keeps the newest N notes, `--notes-grep` the matching ones; both say how
/// many of the total they kept.
#[test]
fn task_show_notes_last_and_grep() {
    let w = World::new("notes-filter");
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "EMBER: everything only ember can do",
        "--assignee",
        "ember",
    ]);
    let parent = opened_task_id(&out);
    for n in [
        "move the build base from /tank (slow) to NVMe?",
        "PUSH also ~/dev/cv: one unsigned commit.",
        "K-PORTAL: who births a guest cell",
        "JOIN-SOLANA works.",
    ] {
        w.cv_ok(&["task", "note", &parent, n, "--from", "orchestrator:x"]);
    }
    let (out, _) = w.cv_ok(&["task", "show", &parent, "--brief"]);
    assert!(out.contains("notes:    4 of 4 (newest last) — one line each"), "{out}");
    let (out, _) = w.cv_ok(&["task", "show", &parent, "--brief", "--notes-last", "2"]);
    assert!(out.contains("notes:    2 of 4"), "{out}");
    assert!(
        !out.contains("move the build base") && out.contains("JOIN-SOLANA"),
        "{out}"
    );
    let (out, _) = w.cv_ok(&["task", "show", &parent, "--notes-grep", "k-portal"]);
    assert!(out.contains("notes:    1 of 4") && out.contains("K-PORTAL"), "{out}");
}

/// `note <id> -` and `--body -` read stdin; a relative `--issue` is absolutized at open time
/// (canonicalized when it exists); handles and URLs pass through.
#[test]
fn task_note_reads_stdin_and_open_absolutizes_issue() {
    let w = World::new("stdin-paths");
    fs::write(w.base.join("PLAN.md"), "# plan\n").unwrap();
    let (ok, _, out, err) = w.cv_stdin(
        &[
            "task",
            "open",
            "with a heredoc body",
            "--body",
            "-",
            "--issue",
            "PLAN.md",
        ],
        "a `code span` body\nwith two lines\n",
    );
    assert!(ok, "{err}");
    let a = opened_task_id(&out);
    let (json, _) = w.cv_ok(&["task", "show", &a, "--json"]);
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(t["body"], "a `code span` body\nwith two lines\n");
    let issue = t["issue"].as_str().unwrap();
    assert!(
        std::path::Path::new(issue).is_absolute() && issue.ends_with("PLAN.md"),
        "{issue}"
    );
    assert_eq!(
        std::path::Path::new(issue).canonicalize().unwrap(),
        w.base.join("PLAN.md").canonicalize().unwrap()
    );

    let (ok, _, _, err) = w.cv_stdin(&["task", "note", &a, "-"], "note from stdin\n");
    assert!(ok, "{err}");
    let (out, _) = w.cv_ok(&["task", "show", &a]);
    assert!(out.contains("note from stdin"), "{out}");

    let (out, _) = w.cv_ok(&["task", "open", "handle", "--issue", "#42"]);
    let b = opened_task_id(&out);
    let (json, _) = w.cv_ok(&["task", "show", &b, "--json"]);
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(&json).unwrap()["issue"],
        "#42"
    );
    let (out, _) = w.cv_ok(&["task", "open", "url", "--issue", "https://x.y/issues/4"]);
    let c = opened_task_id(&out);
    let (json, _) = w.cv_ok(&["task", "show", &c, "--json"]);
    assert_eq!(
        serde_json::from_str::<serde_json::Value>(&json).unwrap()["issue"],
        "https://x.y/issues/4"
    );
    // A relative path that does not exist yet is still rooted at the cwd.
    let (out, _) = w.cv_ok(&["task", "open", "future doc", "--issue", "docs/later.md"]);
    let d = opened_task_id(&out);
    let (json, _) = w.cv_ok(&["task", "show", &d, "--json"]);
    let issue = serde_json::from_str::<serde_json::Value>(&json).unwrap()["issue"]
        .as_str()
        .unwrap()
        .to_string();
    assert!(
        issue.starts_with(w.base.to_str().unwrap())
            || issue.starts_with(&w.base.canonicalize().unwrap().display().to_string()),
        "{issue}"
    );
}

fn seeded_old_and_new(w: &World) -> (String, String) {
    let old = "01900000-0000-7000-8000-000000000001".to_string(); // uuid v7 from 2024
    let new = "01a00000-0000-7000-8000-000000000002".to_string();
    w.seed_task_log(&[
        serde_json::json!({"id": old, "task_id": old, "ts": "2026-01-01T00:00:00Z", "by": "orchestrator:old",
            "event": "opened", "title": "OLD: from another project", "channel": "tasks", "assignee": "ember"}),
        serde_json::json!({"id": new, "task_id": new, "ts": chrono_now(), "by": "orchestrator:new",
            "event": "opened", "title": "NEW: today's task", "channel": "tasks", "assignee": "ember"}),
    ]);
    (old, new)
}

/// An RFC 3339 "now" for seeded events (the test crate has no chrono: derive it from cv itself).
fn chrono_now() -> String {
    chrono_at(0)
}

/// [`chrono_now`] shifted by `offset` seconds.
fn chrono_at(offset: u64) -> String {
    let secs = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        + offset;
    // days since epoch → civil date (Howard Hinnant's algorithm), UTC, minute precision is plenty
    let days = secs / 86_400;
    let (h, m, s) = ((secs % 86_400) / 3600, (secs % 3600) / 60, secs % 60);
    let z = days as i64 + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mo = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if mo <= 2 { y + 1 } else { y };
    format!("{y:04}-{mo:02}-{d:02}T{h:02}:{m:02}:{s:02}Z")
}

/// A bare `list`/`inbox` is scoped to the last 14 days (or tasks involving `$CV_ENDPOINT`) and
/// says how many it hid; `--all` and `--since` lift the window.
#[test]
fn task_list_and_inbox_scope_to_recent_and_all_shows_old() {
    let w = World::new("scope");
    let (old, new) = seeded_old_and_new(&w);
    let (out, _) = w.cv_ok(&["task", "list"]);
    assert!(out.contains("NEW: today") && !out.contains("OLD: from"), "{out}");
    assert!(
        out.trim_end()
            .ends_with("(1 older task(s) hidden — `--all`, or `--since 90d`)"),
        "{out}"
    );
    let (out, _) = w.cv_ok(&["task", "list", "--all"]);
    assert!(
        out.contains("OLD: from") && out.contains("NEW: today") && !out.contains("hidden"),
        "{out}"
    );
    let (out, _) = w.cv_ok(&["task", "list", "--since", "2025-12-01"]);
    assert!(out.contains("OLD: from") && !out.contains("hidden"), "{out}");
    let (out, _) = w.cv_ok(&["task", "list", "--since", "1d"]);
    assert!(!out.contains("OLD: from") && out.contains("hidden"), "{out}");
    // The caller's own tasks escape the window.
    let (ok, _, out, _) = w.cv_env(&["task", "list"], &[("CV_ENDPOINT", "orchestrator:old")]);
    assert!(ok && out.contains("OLD: from") && !out.contains("hidden"), "{out}");
    let (ok, _, out, _) = w.cv_env(&["task", "list"], &[("CV_ENDPOINT", "web:ember")]);
    assert!(
        ok && out.contains("OLD: from"),
        "web:<who> ≡ <who>, the assignee:\n{out}"
    );

    // Same window for the inbox.
    let (out, _) = w.cv_ok(&["task", "inbox", "ember"]);
    assert!(out.contains("NEW: today") && !out.contains("OLD: from"), "{out}");
    assert!(out.contains("(1 older item(s) hidden"), "{out}");
    let (out, _) = w.cv_ok(&["task", "inbox", "ember", "--all"]);
    assert!(out.contains("OLD: from") && out.contains("⏰"), "{out}");
    let (md, _) = w.cv_ok(&["task", "inbox", "ember", "--md"]);
    assert!(md.contains("1 older hidden (`--all`)"), "{md}");
    let _ = (old, new);
}

/// `--unread` keeps items whose last event is not by `<who>` (web:<who> counts as <who>);
/// `events --since` prints JSON lines, filters by kind/by/assignee, and names the next cursor;
/// `watch --assignee` is the orchestrator's view: others' events on that person's tasks.
#[test]
fn task_inbox_unread_and_events_since() {
    let w = World::new("unread-events");
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "A: touched by the orchestrator last",
        "--assignee",
        "ember",
        "--from",
        "orchestrator:x",
    ]);
    let a = opened_task_id(&out);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "B: ember spoke last",
        "--assignee",
        "ember",
        "--from",
        "orchestrator:x",
    ]);
    let b = opened_task_id(&out);
    w.cv_ok(&["task", "note", &b, "on it", "--from", "ember"]);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "C: web ember spoke last",
        "--assignee",
        "ember",
        "--from",
        "orchestrator:x",
    ]);
    let c = opened_task_id(&out);
    w.cv_ok(&["task", "note", &c, "via the page", "--from", "web:ember"]);

    let (out, _) = w.cv_ok(&["task", "inbox", "ember", "--unread"]);
    assert!(
        out.contains("A: touched") && !out.contains("B: ember") && !out.contains("C: web"),
        "{out}"
    );
    let (json, _) = w.cv_ok(&["task", "inbox", "ember", "--unread", "--json"]);
    assert!(json.contains(&a) && !json.contains(&b), "{json}");

    // events: everything, as JSON lines, cursor on stderr.
    let (out, err) = w.cv_ok(&["task", "events"]);
    let lines: Vec<serde_json::Value> = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
    assert_eq!(lines.len(), 5, "{out}");
    assert_eq!(lines[0]["event"], "opened");
    assert_eq!(lines[0]["title"], "A: touched by the orchestrator last");
    assert_eq!(lines[0]["task_state"], "open");
    assert_eq!(lines[0]["assignee"], "ember");
    let last_id = lines[4]["id"].as_str().unwrap().to_string();
    assert!(err.contains(&format!("next: --since {last_id}")), "{err}");
    // since an id is exclusive; since a time is inclusive; kinds take human spellings.
    let (out, _) = w.cv_ok(&["task", "events", "--since", &last_id]);
    assert!(out.trim().is_empty(), "{out}");
    let (out, _) = w.cv_ok(&["task", "events", "--since", lines[3]["id"].as_str().unwrap()]);
    assert_eq!(out.lines().count(), 1, "{out}");
    let (out, _) = w.cv_ok(&["task", "events", "--since", "1h", "--kind", "note"]);
    assert_eq!(out.lines().count(), 2, "{out}");
    let (out, _) = w.cv_ok(&["task", "events", "--by", "ember"]);
    assert_eq!(
        out.lines().count(),
        2,
        "web:ember is ember acting through the page:\n{out}"
    );
    let (out, _) = w.cv_ok(&["task", "events", "--not-by", "orchestrator:x", "--text"]);
    assert_eq!(out.lines().count(), 2, "{out}");
    assert!(
        out.contains("noted") && out.contains("on it") && out.contains("via the page"),
        "{out}"
    );
    let (out, _) = w.cv_ok(&["task", "events", "--task", &b]);
    assert_eq!(out.lines().count(), 2, "{out}");
    let (_, err) = w.cv_fails(&["task", "events", "--since", "whenever"]);
    assert!(err.contains("cannot read"), "{err}");

    // What ember did on their tasks, minus the caller's own events: `events` with two flags.
    let (ok, _, out, _) = w.cv_env(
        &[
            "task",
            "events",
            "--assignee",
            "ember",
            "--not-by",
            "orchestrator:x",
            "--since",
            "1d",
        ],
        &[("CV_ENDPOINT", "orchestrator:x")],
    );
    assert!(ok);
    let rows: Vec<serde_json::Value> = out.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
    assert_eq!(rows.len(), 2, "{out}");
    assert!(rows.iter().all(|r| r["event"] == "noted"), "{out}");
    // `watch` was that query under a second name; the name errors with the spelling.
    let (ok, code, _, err) = w.cv(&["task", "watch", "--assignee", "ember"]);
    assert!(!ok && code == 2, "{err}");
    assert!(err.contains("removed in 0.15.0") && err.contains("--not-by"), "{err}");
}

// ───────────────────────────── the inbox on cv serve ─────────────────────────────

/// A minimal HTTP/1.1 client over a TcpStream (the test crate has no HTTP dependency).
fn http(addr: &str, method: &str, path: &str, body: Option<&str>) -> (u16, String) {
    use std::io::{Read, Write};
    let mut s = std::net::TcpStream::connect(addr).expect("connect to cv serve");
    s.set_read_timeout(Some(std::time::Duration::from_secs(10))).unwrap();
    let body = body.unwrap_or("");
    let req = format!(
        "{method} {path} HTTP/1.1\r\nHost: {addr}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    );
    s.write_all(req.as_bytes()).unwrap();
    let mut raw = Vec::new();
    s.read_to_end(&mut raw).unwrap();
    let text = String::from_utf8_lossy(&raw).into_owned();
    let (head, body) = text.split_once("\r\n\r\n").unwrap_or((&text, ""));
    let status: u16 = head.split_whitespace().nth(1).unwrap_or("0").parse().unwrap_or(0);
    (status, body.to_string())
}

/// Start `cv serve` on an ephemeral port in this world; returns (child, addr).
fn serve(w: &World, who: &str) -> (std::process::Child, String) {
    use std::io::{BufRead, BufReader};
    let mut child = w
        .cv_command()
        .args(["serve", "--port", "0", "--who", who])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .expect("cv serve starts");
    let stderr = child.stderr.take().unwrap();
    let mut lines = BufReader::new(stderr).lines();
    let banner = lines.next().expect("a banner line").expect("readable");
    let addr = banner
        .split("http://")
        .nth(1)
        .and_then(|rest| rest.split_whitespace().next())
        .unwrap_or_else(|| panic!("no address in banner: {banner}"))
        .to_string();
    // Keep draining stderr so the child never blocks on a full pipe.
    std::thread::spawn(move || for _ in lines {});
    (child, addr)
}

/// The page and the CLI are one store: GET the inbox for a fixture assignee (one decision, one
/// action), POST resolve / done / note / discuss, and `cv task show --brief` reflects every event
/// with the author `web:<assignee>`. The event feed route is the same query as `cv task events`.
#[test]
fn the_inbox_records_the_same_events_as_the_cli() {
    let w = World::new("serve");
    let (out, _) = w.cv_ok(&[
        "task",
        "decide",
        "PAY §7: tariff",
        "--for",
        "ember",
        "--default",
        "1 credit/unit",
        "--option",
        "free tier",
        "--from",
        "orchestrator:x",
    ]);
    let d = opened_task_id(&out);
    let (out, _) = w.cv_ok(&[
        "task",
        "open",
        "push dregg-infra",
        "--assignee",
        "ember",
        "--from",
        "orchestrator:x",
    ]);
    let a = opened_task_id(&out);
    let (mut child, addr) = serve(&w, "ember");
    let result = std::panic::catch_unwind(|| {
        // The page itself is served inline; it names its own origin story.
        let (status, html) = http(&addr, "GET", "/", None);
        assert_eq!(status, 200);
        assert!(
            html.contains("<title>cv inbox</title>") && html.contains("/api/inbox"),
            "{}",
            &html[..200.min(html.len())]
        );
        assert!(
            !html.contains("<script src=") && !html.contains("<link rel=\"stylesheet\""),
            "no external resources"
        );
        // A DNS-named Host is refused (rebinding).
        let (status, _) = {
            use std::io::{Read, Write};
            let mut s = std::net::TcpStream::connect(&addr).unwrap();
            s.write_all(b"GET /api/inbox HTTP/1.1\r\nHost: evil.example\r\nConnection: close\r\n\r\n")
                .unwrap();
            let mut raw = String::new();
            s.read_to_string(&mut raw).unwrap();
            (
                raw.split_whitespace().nth(1).unwrap_or("0").parse::<u16>().unwrap_or(0),
                raw,
            )
        };
        assert_eq!(status, 403);

        let (status, body) = http(&addr, "GET", "/api/inbox?who=ember", None);
        assert_eq!(status, 200, "{body}");
        let page: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(page["who"], "ember");
        assert_eq!(page["counts"]["decisions"], 1);
        assert_eq!(page["counts"]["assigned"], 1);
        let items = page["items"].as_array().unwrap();
        assert_eq!(items[0]["reason"], "decision_owed");
        assert_eq!(items[0]["decision"]["default"], "1 credit/unit");
        assert_eq!(items[0]["decision"]["alternatives"], serde_json::json!(["free tier"]));
        assert_eq!(items[1]["reason"], "assigned_open");
        // Without ?who the server's --who applies.
        let (status, body) = http(&addr, "GET", "/api/inbox", None);
        assert_eq!(status, 200);
        assert!(body.contains("\"who\":\"ember\""), "{body}");

        // Act: a note, then "needs discussion", then resolve with an option, then done.
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{d}/note"),
            Some(r#"{"text":"reading PAY first"}"#),
        );
        assert_eq!(status, 200, "{body}");
        assert!(body.contains("\"by\":\"web:ember\""), "{body}");
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{d}/discuss"),
            Some(r#"{"text":"what is a unit?"}"#),
        );
        assert_eq!(status, 200, "{body}");
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{d}/resolve"),
            Some(r#"{"choice":"free tier","note":"for October"}"#),
        );
        assert_eq!(status, 200, "{body}");
        assert!(body.contains("\"task_state\":\"resolved\""), "{body}");
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{d}/resolve"),
            Some(r#"{"accept_default":true}"#),
        );
        assert_eq!(status, 400, "a second resolution is refused: {body}");
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{a}/done"),
            Some(r#"{"observed":"pushed"}"#),
        );
        assert_eq!(status, 200, "{body}");
        let (status, body) = http(&addr, "POST", &format!("/api/task/{a}/done"), Some("{}"));
        assert_eq!(status, 400, "{body}");
        let (status, body) = http(&addr, "POST", &format!("/api/task/{a}/frobnicate"), Some("{}"));
        assert_eq!(status, 400, "{body}");
        let (status, body) = http(&addr, "POST", &format!("/api/task/{a}/note"), Some("not json"));
        assert_eq!(status, 400, "{body}");

        // The closed items show under the page's Resolved filter; reopen brings a NEW task.
        let (status, body) = http(&addr, "GET", "/api/inbox?who=ember", None);
        assert_eq!(status, 200);
        let page: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(page["items"].as_array().unwrap().len(), 0);
        assert_eq!(page["closed"].as_array().unwrap().len(), 2);
        let (status, body) = http(&addr, "POST", &format!("/api/task/{a}/reopen"), Some("{}"));
        assert_eq!(status, 200, "{body}");
        let (status, body) = http(&addr, "GET", "/api/inbox?who=ember", None);
        assert_eq!(status, 200);
        let page: serde_json::Value = serde_json::from_str(&body).unwrap();
        let items = page["items"].as_array().unwrap();
        assert_eq!(items.len(), 1, "{body}");
        assert_eq!(items[0]["title"], "push dregg-infra");
        assert!(
            items[0]["tags"].as_array().unwrap().iter().any(|t| t == "reopened"),
            "{body}"
        );

        // One task, with its history; the event feed is the same query as `cv task events`.
        let (status, body) = http(&addr, "GET", &format!("/api/task/{d}?events=1"), None);
        assert_eq!(status, 200);
        let v: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(v["effective_state"], "resolved");
        assert!(v["events"].as_array().unwrap().len() >= 6, "{body}");
        let (status, body) = http(&addr, "GET", "/api/events?since=1h&kind=resolved,done", None);
        assert_eq!(status, 200);
        let rows: Vec<serde_json::Value> = body.lines().map(|l| serde_json::from_str(l).unwrap()).collect();
        assert_eq!(rows.len(), 2, "{body}");
        assert!(rows.iter().all(|r| r["by"] == "web:ember"), "{body}");
    });
    let _ = child.kill();
    let _ = child.wait();
    if let Err(e) = result {
        std::panic::resume_unwind(e);
    }

    // The CLI sees exactly what the page recorded, with the web author.
    let (out, _) = w.cv_ok(&["task", "show", &d, "--brief"]);
    assert!(out.contains("[resolved]"), "{out}");
    assert!(
        out.contains("resolved: free tier — by web:ember,") && out.contains("· for October"),
        "{out}"
    );
    assert!(out.contains("web:ember") && out.contains("reading PAY first"), "{out}");
    assert!(out.contains("NEEDS DISCUSSION: what is a unit?"), "{out}");
    assert!(
        out.contains("tags:     discuss"),
        "a decision is posed, never tagged:\n{out}"
    );
    let (out, _) = w.cv_ok(&["task", "show", &a, "--brief"]);
    assert!(
        out.contains("[done]") && out.contains("self-reported") && out.contains("(pushed)"),
        "{out}"
    );
    let (json, _) = w.cv_ok(&["task", "show", &a, "--events"]);
    assert!(json.contains("\"by\": \"web:ember\""), "{json}");
    let (out, _) = w.cv_ok(&["task", "events", "--since", "1h", "--kind", "resolved,done"]);
    assert_eq!(out.lines().count(), 2, "the CLI feed and /api/events agree:\n{out}");
}
// ───────────────────────────── distill ─────────────────────────────

/// Walk `parentUuid` back from the newest threaded record, the way Claude Code loads a session on
/// resume; returns how many records the walk reaches and the root it stops at.
fn chain_walk(path: &std::path::Path) -> (usize, usize, serde_json::Value) {
    let lines: Vec<serde_json::Value> = fs::read_to_string(path)
        .unwrap()
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();
    let threaded: Vec<&serde_json::Value> = lines.iter().filter(|v| v.get("uuid").is_some()).collect();
    let by: std::collections::HashMap<&str, &serde_json::Value> =
        threaded.iter().map(|v| (v["uuid"].as_str().unwrap(), *v)).collect();
    let mut cur = *threaded.last().unwrap();
    let mut n = 1;
    while let Some(p) = cur["parentUuid"].as_str() {
        match by.get(p) {
            Some(v) => {
                cur = v;
                n += 1;
            }
            None => break,
        }
    }
    (n, threaded.len(), cur.clone())
}

#[test]
fn distill_emits_a_whole_resumable_session_and_a_sub_agent() {
    let w = World::new("distill");
    let big = "y".repeat(9000);
    w.write_session(
        "rootsess",
        &[serde_json::json!({
            "type": "user", "uuid": "r1", "sessionId": "rootsess", "timestamp": "2026-01-01T09:00:00Z",
            "cwd": "/work/proj", "message": {"role": "user", "content": "run the lanes"}
        })],
    );
    let sub = w.home.join(".claude/projects/-work-proj/rootsess/subagents");
    fs::create_dir_all(&sub).unwrap();
    let agent = sub.join("agent-a0123456789abcdef.jsonl");
    let line = |v: serde_json::Value| {
        let mut v = v;
        v["isSidechain"] = true.into();
        v["agentId"] = "a0123456789abcdef".into();
        v["sessionId"] = "rootsess".into();
        v["cwd"] = "/work/proj".into();
        format!("{v}\n")
    };
    let body = [
        line(serde_json::json!({"type": "user", "uuid": "u0", "parentUuid": null, "timestamp": "2026-01-01T10:00:00Z",
            "message": {"role": "user", "content": "You are lane TEST. Build it on box1 and commit on lane/test."}})),
        line(serde_json::json!({"type": "assistant", "uuid": "a1", "parentUuid": "u0", "timestamp": "2026-01-01T10:01:00Z",
            "message": {"role": "assistant", "model": "claude-test-1", "content": [
                {"type": "tool_use", "id": "t1", "name": "Bash", "input": {"command": "ssh ember@box1 'cat big.log'", "description": "Read the big log"}}]}})),
        line(serde_json::json!({"type": "user", "uuid": "u1", "parentUuid": "a1", "timestamp": "2026-01-01T10:02:00Z",
            "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1", "content": big, "is_error": false}]}})),
        // A hook record the IR does not carry — the next turn's parent. A reshaped session that
        // kept this link would resume from the break and silently lose everything before it.
        line(serde_json::json!({"type": "attachment", "uuid": "h1", "parentUuid": "u1", "timestamp": "2026-01-01T10:02:30Z",
            "attachment": {"type": "hook_success", "hookName": "PostToolUse", "content": ""}})),
        line(serde_json::json!({"type": "assistant", "uuid": "a2", "parentUuid": "h1", "timestamp": "2026-01-01T10:03:00Z",
            "message": {"role": "assistant", "model": "claude-test-1", "content": [
                {"type": "text", "text": "Chose a rebase: the queue wants linear ranges."},
                {"type": "tool_use", "id": "t2", "name": "Bash", "input": {"command": "cd /srv/x && git commit -F msg", "description": "Commit"}}]}})),
        line(serde_json::json!({"type": "user", "uuid": "u2", "parentUuid": "a2", "timestamp": "2026-01-01T10:04:00Z",
            "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t2", "content": "[lane/test 1234abcd] kernel: one", "is_error": false}]}})),
        line(serde_json::json!({"type": "assistant", "uuid": "a3", "parentUuid": "u2", "timestamp": "2026-01-01T10:05:00Z",
            "message": {"role": "assistant", "model": "claude-test-1", "content": [{"type": "text", "text": "Committed."}],
                "usage": {"input_tokens": 5, "cache_read_input_tokens": 900000, "output_tokens": 10}}})),
    ]
    .concat();
    fs::write(&agent, &body).unwrap();
    let agent_s = agent.to_str().unwrap();

    // The pack: brief, own words, commit, host, and the big output elided.
    let (out, err) = w.cv_ok(&["distill", agent_s, "--keep-last", "1"]);
    assert!(out.contains("You are lane TEST."), "{out}");
    assert!(out.contains("Chose a rebase"), "{out}");
    assert!(out.contains("`lane/test` `1234abcd`"), "{out}");
    assert!(out.contains("`ember@box1`"), "{out}");
    assert!(!out.contains(&"y".repeat(200)), "the big output must be elided");
    assert!(err.contains("distilled"), "{err}");

    // A resumable session: every record reachable from the newest, rooted at the pack prompt.
    let (out, _) = w.cv_ok(&["distill", agent_s, "--keep-last", "1", "--session", "--json"]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    let path = PathBuf::from(v["emitted"]["path"].as_str().unwrap());
    let new_id = v["emitted"]["session_id"].as_str().unwrap().to_string();
    let (reached, threaded, root) = chain_walk(&path);
    assert_eq!(reached, threaded, "a dangling parent truncates the resumed context");
    assert!(
        root["message"]["content"].as_str().unwrap().contains("[cv distill]"),
        "{root}"
    );
    let text = fs::read_to_string(&path).unwrap();
    assert!(!text.contains("\"isSidechain\":true"), "a main-thread session");
    assert!(
        !text.contains("900000"),
        "the source's near-limit usage must not reach the resume gate"
    );
    // The elided output comes back through the sidecar.
    let (cat, _) = w.cv_ok(&["cat", &new_id, "t1"]);
    assert!(cat.contains(&"y".repeat(9000)), "cv cat must return the elided payload");

    // A sub-agent of the root: sidechain records under the root's id, in the root's subagents/.
    let (out, _) = w.cv_ok(&[
        "distill",
        agent_s,
        "--keep-last",
        "1",
        "--agent-of",
        "rootsess",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    let aid = v["emitted"]["agent_id"].as_str().unwrap();
    let apath = sub.join(format!("agent-{aid}.jsonl"));
    assert!(apath.exists() && sub.join(format!("agent-{aid}.meta.json")).exists());
    let (reached, threaded, _) = chain_walk(&apath);
    assert_eq!(reached, threaded);
    for l in fs::read_to_string(&apath).unwrap().lines() {
        let r: serde_json::Value = serde_json::from_str(l).unwrap();
        assert_eq!(r["isSidechain"], true, "{l}");
        assert_eq!(r["agentId"], aid, "{l}");
        assert_eq!(r["sessionId"], "rootsess", "{l}");
    }
    assert_eq!(
        fs::read_to_string(&agent).unwrap(),
        body,
        "distill must never modify the source"
    );

    // `--model` rewrites the new agent's meta `model`; it needs `--agent-of` (exit 2 without).
    let (out, _) = w.cv_ok(&[
        "distill",
        agent_s,
        "--agent-of",
        "rootsess",
        "--model",
        "inherit",
        "--json",
    ]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    let meta = sub.join(format!(
        "agent-{}.meta.json",
        v["emitted"]["agent_id"].as_str().unwrap()
    ));
    let meta: serde_json::Value = serde_json::from_str(&fs::read_to_string(meta).unwrap()).unwrap();
    assert_eq!(meta["model"], "inherit", "{meta}");
    let (ok, code, _, _) = w.cv(&["distill", agent_s, "--session", "--model", "opus"]);
    assert!(!ok && code == 2);

    // A fork is a splice of the verbatim prefix, to the same two destinations. `..2` strands `t1`
    // (its result is message 2) and the emitter drops the call, so the session resumes whole.
    let spec = format!("{agent_s}:..2");
    let (out, _) = w.cv_ok(&["splice", &spec, "--session", "--json"]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).expect("stdout must be pure JSON");
    let path = PathBuf::from(v["path"].as_str().unwrap());
    let (reached, threaded, root) = chain_walk(&path);
    assert_eq!(reached, threaded);
    assert_eq!(root["uuid"], "u0", "{root}");
    let text = fs::read_to_string(&path).unwrap();
    assert!(
        !text.contains("\"t1\"") && !text.contains("\"isSidechain\":true"),
        "{text}"
    );
    let (out, _) = w.cv_ok(&["splice", &spec, "--agent-of", "rootsess", "--json"]);
    let v: serde_json::Value = serde_json::from_str(out.trim()).unwrap();
    let aid = v["agent_id"].as_str().unwrap();
    let apath = sub.join(format!("agent-{aid}.jsonl"));
    assert!(apath.exists() && sub.join(format!("agent-{aid}.meta.json")).exists());
    for l in fs::read_to_string(&apath).unwrap().lines() {
        let r: serde_json::Value = serde_json::from_str(l).unwrap();
        assert!(
            r["isSidechain"] == true && r["agentId"] == aid && r["sessionId"] == "rootsess",
            "{l}"
        );
    }
}

// ───────────────────────────── adopt ─────────────────────────────

#[test]
fn adopt_moves_a_stranded_lane_into_the_live_session() {
    let w = World::new("adopt");
    let (dead, live, aid) = ("deadsess", "livesess", "a0123456789abcdef");
    let root_line = |sid: &str| {
        serde_json::json!({"type": "user", "uuid": format!("{sid}-1"), "sessionId": sid,
            "timestamp": "2026-01-01T09:00:00Z", "cwd": "/work/proj",
            "message": {"role": "user", "content": "run the lanes"}})
    };
    w.write_session(dead, &[root_line(dead)]);
    let sub = w.home.join(".claude/projects/-work-proj/deadsess/subagents");
    fs::create_dir_all(&sub).unwrap();
    let line = |v: serde_json::Value| {
        let mut v = v;
        v["isSidechain"] = true.into();
        v["agentId"] = aid.into();
        v["sessionId"] = dead.into();
        v["cwd"] = "/work/proj".into();
        format!("{v}\n")
    };
    let body = [
        line(serde_json::json!({"type": "user", "uuid": "u0", "parentUuid": null, "timestamp": "2026-01-01T10:00:00Z",
            "message": {"role": "user", "content": "You are lane TEST."}})),
        line(serde_json::json!({"type": "assistant", "uuid": "a1", "parentUuid": "u0", "timestamp": "2026-01-01T10:01:00Z",
            "message": {"role": "assistant", "model": "claude-test-1", "content": [
                {"type": "tool_use", "id": "t1", "name": "Bash", "input": {"command": "grep sessionId x.jsonl"}}]}})),
        // The tool output quotes a transcript line: its sessionId is content and must survive.
        line(serde_json::json!({"type": "user", "uuid": "u1", "parentUuid": "a1", "timestamp": "2026-01-01T10:02:00Z",
            "message": {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "t1",
                "content": "{\"sessionId\":\"deadsess\"}", "is_error": false}]}})),
    ]
    .concat();
    let agent = sub.join(format!("agent-{aid}.jsonl"));
    fs::write(&agent, &body).unwrap();
    let meta = r#"{"agentType":"general-purpose","description":"Lane TEST","model":"opus"}"#;
    fs::write(sub.join(format!("agent-{aid}.meta.json")), meta).unwrap();
    std::thread::sleep(std::time::Duration::from_millis(20));
    w.write_session(live, &[root_line(live)]); // the newest session: the default --into

    // Finding the agents is `lanes`' job: one session, or the project's recent sessions.
    let (out, _) = w.cv_ok(&["lanes", dead]);
    assert!(out.contains(&aid[..8]) && out.contains("Lane TEST"), "{out}");
    let (out, _) = w.cv_ok(&["lanes", "--recent", "5", "--unfinished", "--cwd", "/work/proj"]);
    assert!(out.contains("SESSION"), "rows are tagged with their session: {out}");
    assert!(out.contains("deadsess") && out.contains(&aid[..8]), "{out}");
    assert!(out.contains("cv adopt <agent-id>"), "the rescue hint: {out}");
    let (out, _) = w.cv_ok(&[
        "lanes",
        "--recent",
        "5",
        "--unfinished",
        "--cwd",
        "/work/proj",
        "--json",
    ]);
    let rows: Vec<serde_json::Value> = serde_json::from_str(&out).unwrap();
    assert!(
        rows.iter()
            .any(|r| r["parent_id"] == "deadsess" && r["agent_id"] == aid),
        "{out}"
    );
    // The removed flags error with the replacement, exit 2.
    let (ok, code, _, err) = w.cv(&["adopt", "--list", dead]);
    assert!(!ok && code == 2 && err.contains("cv lanes deadsess"), "{err}");
    let (ok, code, _, err) = w.cv(&["adopt", "--orphans"]);
    assert!(
        !ok && code == 2 && err.contains("cv lanes --recent <N> --unfinished"),
        "{err}"
    );

    let live_sub = w.home.join(".claude/projects/-work-proj/livesess/subagents");
    let (_, err) = w.cv_ok(&["adopt", &aid[..8], "--dry-run"]);
    assert!(err.contains("into livesess"), "the default target is announced: {err}");
    assert!(err.contains("restamped on 3 of 3 lines"), "{err}");
    assert!(
        err.contains(&format!("\"to\": \"{aid}\"")),
        "the SendMessage incantation: {err}"
    );
    assert!(err.contains("cv cat deadsess"), "the sidecar reminder: {err}");
    assert!(!live_sub.exists(), "a dry run writes nothing");

    w.cv_ok(&["adopt", aid]);
    let copied = fs::read_to_string(live_sub.join(format!("agent-{aid}.jsonl"))).unwrap();
    assert_eq!(
        copied,
        body.replace("\"sessionId\":\"deadsess\"", "\"sessionId\":\"livesess\"")
            .replace(
                "{\\\"sessionId\\\":\\\"livesess\\\"}",
                "{\\\"sessionId\\\":\\\"deadsess\\\"}"
            )
    );
    assert!(
        copied.contains("{\\\"sessionId\\\":\\\"deadsess\\\"}"),
        "content untouched"
    );
    assert_eq!(
        fs::read_to_string(live_sub.join(format!("agent-{aid}.meta.json"))).unwrap(),
        meta
    );
    assert_eq!(
        fs::read_to_string(&agent).unwrap(),
        body,
        "the source is never modified"
    );

    // A second adoption refuses (nothing written) until --force.
    fs::write(live_sub.join(format!("agent-{aid}.jsonl")), "sentinel\n").unwrap();
    let (ok, _, _, err) = w.cv(&["adopt", aid, "--from", dead, "--into", live]);
    assert!(!ok && err.contains("refusing to overwrite"), "{err}");
    assert_eq!(
        fs::read_to_string(live_sub.join(format!("agent-{aid}.jsonl"))).unwrap(),
        "sentinel\n"
    );
    w.cv_ok(&["adopt", aid, "--from", dead, "--into", live, "--force"]);
    assert!(fs::read_to_string(live_sub.join(format!("agent-{aid}.jsonl")))
        .unwrap()
        .contains("livesess"));

    // `--model` rewrites the copied meta's `model` and keeps the rest of it.
    w.cv_ok(&[
        "adopt", aid, "--from", dead, "--into", live, "--force", "--model", "sonnet",
    ]);
    let m: serde_json::Value =
        serde_json::from_str(&fs::read_to_string(live_sub.join(format!("agent-{aid}.meta.json"))).unwrap()).unwrap();
    assert_eq!(
        (m["model"].as_str(), m["description"].as_str()),
        (Some("sonnet"), Some("Lane TEST"))
    );

    // The agent now has two copies; reading it by id takes the newest instead of erroring.
    let (out, _) = w.cv_ok(&["cat", &format!("agent-{aid}"), "t1"]);
    assert!(out.contains("deadsess"), "{out}");
}

/// The dead session lives in an agent seat's config dir (named by `claude-roots`), and is the most
/// recently written file of the project; the live session is under `~/.claude`. Adopt finds the
/// agent across roots, and the default target is the newest session OTHER than the one being
/// rescued from, in whichever root holds it.
#[test]
fn adopt_reaches_extra_claude_roots_and_never_targets_the_dead_session() {
    let w = World::new("adopt-roots");
    let (dead, live, aid) = ("deadsess", "livesess", "afedcba9876543210");
    let root_line = |sid: &str| {
        serde_json::json!({"type": "user", "uuid": format!("{sid}-1"), "sessionId": sid,
            "timestamp": "2026-01-01T09:00:00Z", "cwd": "/work/proj",
            "message": {"role": "user", "content": "run the lanes"}})
    };
    w.write_session(live, &[root_line(live)]);
    std::thread::sleep(std::time::Duration::from_millis(20));
    let seat_proj = w.home.join("seats/bonsai/claude/projects/-work-proj");
    let sub = seat_proj.join(dead).join("subagents");
    fs::create_dir_all(&sub).unwrap();
    fs::write(
        seat_proj.join(format!("{dead}.jsonl")),
        format!("{}\n", root_line(dead)),
    )
    .unwrap();
    let mut l = serde_json::json!({"type": "user", "uuid": "u0", "parentUuid": null, "timestamp": "2026-01-01T10:00:00Z",
        "cwd": "/work/proj", "message": {"role": "user", "content": "You are lane SEAT."}});
    l["isSidechain"] = true.into();
    l["agentId"] = aid.into();
    l["sessionId"] = dead.into();
    fs::write(sub.join(format!("agent-{aid}.jsonl")), format!("{l}\n")).unwrap();

    // The seat root is not configured yet: the agent is invisible.
    let (ok, _, _, err) = w.cv(&["adopt", aid, "--dry-run"]);
    assert!(!ok && err.contains("no sub-agent"), "{err}");

    fs::write(w.cv_home.join("claude-roots"), "~/seats/*/claude\n").unwrap();
    let (_, err) = w.cv_ok(&["adopt", aid, "--dry-run"]);
    assert!(
        err.contains("into livesess"),
        "the dead session is newer but is never the target: {err}"
    );
    w.cv_ok(&["adopt", aid]);
    let copied = w
        .home
        .join(".claude/projects/-work-proj/livesess/subagents")
        .join(format!("agent-{aid}.jsonl"));
    assert!(fs::read_to_string(copied)
        .unwrap()
        .contains("\"sessionId\":\"livesess\""));
    let (out, _) = w.cv_ok(&["lanes", dead]);
    assert!(out.contains(&aid[..8]), "a seat session lists by id too: {out}");
}

/// Provisional resolutions: the orchestrator poses and resolves on the default at once
/// (`decide --provisional`); the decider's inbox lists it under "made for you (veto?)", not as
/// owed; a third party cannot override it; the decider vetoes with `--choice` (or confirms, here
/// through the page's `{confirm: true}`), and `show` keeps both resolutions.
#[test]
fn task_provisional_resolution_veto_and_confirm() {
    let w = World::new("provisional");
    let (out, _) = w.cv_ok(&[
        "task",
        "decide",
        "build base: /tank or NVMe",
        "--for",
        "ember",
        "--default",
        "keep /tank",
        "--option",
        "move to NVMe",
        "--provisional",
        "--from",
        "orchestrator:o",
    ]);
    let d = opened_task_id(&out);
    assert!(
        out.contains("resolved") && out.contains("provisionally on the default"),
        "{out}"
    );
    let (out, _) = w.cv_ok(&["task", "inbox", "ember"]);
    assert!(
        out.starts_with("made for you (veto?) (1):"),
        "not owed, its own group:\n{out}"
    );
    assert!(
        out.contains("⇒ made: keep /tank — by orchestrator:o · veto to: move to NVMe"),
        "{out}"
    );
    assert!(out.contains("cv task resolve <id> --confirm --from ember"), "{out}");
    let (json, _) = w.cv_ok(&["task", "inbox", "ember", "--json"]);
    assert!(json.contains("\"provisional\""), "{json}");
    let (out, _) = w.cv_ok(&["task", "show", &d]);
    assert!(out.contains("[resolved]") && out.contains("PROVISIONAL"), "{out}");
    assert!(out.contains("veto?:    cv task resolve"), "{out}");

    // The poser cannot pick a non-default provisionally; a third party cannot override.
    let (out, _) = w.cv_ok(&[
        "task",
        "decide",
        "Q2",
        "--for",
        "ember",
        "--default",
        "a",
        "--option",
        "b",
        "--from",
        "orchestrator:o",
    ]);
    let d2 = opened_task_id(&out);
    let (_, err) = w.cv_fails(&[
        "task",
        "resolve",
        &d2,
        "--choice",
        "b",
        "--provisional",
        "--from",
        "orchestrator:o",
    ]);
    assert!(err.contains("stands on the default"), "{err}");
    let (_, err) = w.cv_fails(&[
        "task",
        "resolve",
        &d,
        "--choice",
        "move to NVMe",
        "--from",
        "lane:someone",
    ]);
    assert!(err.contains("only the decision's assignee (ember)"), "{err}");
    let (_, err) = w.cv_fails(&["task", "resolve", &d2, "--confirm", "--from", "ember"]);
    assert!(err.contains("no provisional resolution to confirm"), "{err}");
    // No identity: the cure names the decision's owner, never a guess.
    let (_, err) = w.cv_fails(&["task", "resolve", &d2, "--accept-default"]);
    assert!(
        err.contains("records WHO decided") && err.contains("--accept-default --from ember"),
        "{err}"
    );

    // The decider vetoes: a new resolution replaces the provisional one, which is kept.
    let (out, _) = w.cv_ok(&["task", "resolve", &d, "--choice", "move to NVMe", "--from", "ember"]);
    assert!(out.contains("→ move to NVMe (by ember)"), "{out}");
    let (out, _) = w.cv_ok(&["task", "show", &d]);
    assert!(out.contains("provisionally: keep /tank — by orchestrator:o"), "{out}");
    assert!(
        out.contains("resolved: move to NVMe — by ember") && !out.contains("PROVISIONAL"),
        "{out}"
    );
    let (json, _) = w.cv_ok(&["task", "show", &d, "--json"]);
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(t["decision"]["resolution"]["choice"], "move to NVMe");
    assert!(t["decision"]["resolution"].get("provisional").is_none(), "{json}");
    assert_eq!(t["decision"]["superseded_provisional"]["provisional"], true, "{json}");
    let (out, _) = w.cv_ok(&["task", "inbox", "ember"]);
    assert!(
        out.contains("(inbox empty for ember)") || !out.contains("made for you"),
        "{out}"
    );
    // A second answer is refused as it always was.
    let (_, err) = w.cv_fails(&["task", "resolve", &d, "--accept-default", "--from", "ember"]);
    assert!(err.contains("cannot apply resolved"), "{err}");

    // Confirm through the page.
    let (out, _) = w.cv_ok(&[
        "task",
        "decide",
        "Q3",
        "--for",
        "ember",
        "--default",
        "x",
        "--option",
        "y",
        "--provisional",
        "--from",
        "orchestrator:o",
    ]);
    let d3 = opened_task_id(&out);
    let (mut child, addr) = serve(&w, "ember");
    let result = std::panic::catch_unwind(|| {
        let (status, body) = http(&addr, "GET", "/api/inbox?who=ember", None);
        assert_eq!(status, 200, "{body}");
        let page: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(page["counts"]["provisional"], 1, "{body}");
        assert_eq!(page["counts"]["decisions"], 1, "Q2 is still owed; Q3 is not: {body}");
        let made: Vec<&serde_json::Value> = page["items"]
            .as_array()
            .unwrap()
            .iter()
            .filter(|i| i["reason"] == "provisional")
            .collect();
        assert_eq!(made.len(), 1, "{body}");
        assert_eq!(made[0]["title"], "Q3");
        let (status, body) = http(
            &addr,
            "POST",
            &format!("/api/task/{d3}/resolve"),
            Some(r#"{"confirm":true}"#),
        );
        assert_eq!(status, 200, "{body}");
    });
    let _ = child.kill();
    let _ = child.wait();
    if let Err(e) = result {
        std::panic::resume_unwind(e);
    }
    let (json, _) = w.cv_ok(&["task", "show", &d3, "--json"]);
    let t: serde_json::Value = serde_json::from_str(&json).unwrap();
    assert_eq!(t["decision"]["resolution"]["by"], "web:ember");
    assert_eq!(t["decision"]["resolution"]["choice"], "x");
    assert_eq!(t["decision"]["superseded_provisional"]["by"], "orchestrator:o");
}