Swadhin Biswas feat: implement mervelas cli engine, built-in tools, and reactive UI · 4/3/2026
0358986
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
import { execFileSync } from "child_process";
import { diffLines } from "diff";
import { constants as fsConstants } from "fs";
import {
copyFile,
mkdir,
mkdtemp,
readdir,
readFile,
rm,
unlink,
writeFile,
} from "fs/promises";
import { tmpdir } from "os";
import { extname, join } from "path";
import type { Command } from "../commands.js";
import { queryWithModel } from "../services/api/mervelas.js";
import {
AGENT_TOOL_NAME,
LEGACY_AGENT_TOOL_NAME,
} from "../tools/AgentTool/constants.js";
import type { LogOption } from "../types/logs.js";
import { getClaudeConfigHomeDir } from "../utils/envUtils.js";
import { toError } from "../utils/errors.js";
import { execFileNoThrow } from "../utils/execFileNoThrow.js";
import { logError } from "../utils/log.js";
import { extractTextContent } from "../utils/messages.js";
import { getDefaultOpusModel } from "../utils/model/model.js";
import {
getProjectsDir,
getSessionFilesWithMtime,
getSessionIdFromLog,
loadAllLogsFromSessionFile,
} from "../utils/sessionStorage.js";
import { jsonParse, jsonStringify } from "../utils/slowOperations.js";
import { countCharInString } from "../utils/stringUtils.js";
import { asSystemPrompt } from "../utils/systemPromptType.js";
import { escapeXmlAttr as escapeHtml } from "../utils/xml.js";
// Model for facet extraction and summarization (Opus - best quality)
function getAnalysisModel(): string {
return getDefaultOpusModel();
}
// Model for narrative insights (Opus - best quality)
function getInsightsModel(): string {
return getDefaultOpusModel();
}
// ============================================================================
// Homespace Data Collection
// ============================================================================
type RemoteHostInfo = {
name: string;
sessionCount: number;
};
/* eslint-disable custom-rules/no-process-env-top-level */
const getRunningRemoteHosts: () => Promise<string[]> =
process.env.USER_TYPE === "ant"
? async () => {
const { stdout, code } = await execFileNoThrow(
"coder",
["list", "-o", "json"],
{ timeout: 30000 },
);
if (code !== 0) return [];
try {
const workspaces = jsonParse(stdout) as Array<{
name: string;
latest_build?: { status?: string };
}>;
return workspaces
.filter((w) => w.latest_build?.status === "running")
.map((w) => w.name);
} catch {
return [];
}
}
: async () => [];
const getRemoteHostSessionCount: (hs: string) => Promise<number> =
process.env.USER_TYPE === "ant"
? async (homespace: string) => {
const { stdout, code } = await execFileNoThrow(
"ssh",
[
`${homespace}.coder`,
'find /root/.mervelas/projects -name "*.jsonl" 2>/dev/null | wc -l',
],
{ timeout: 30000 },
);
if (code !== 0) return 0;
return parseInt(stdout.trim(), 10) || 0;
}
: async () => 0;
const collectFromRemoteHost: (
hs: string,
destDir: string,
) => Promise<{ copied: number; skipped: number }> =
process.env.USER_TYPE === "ant"
? async (homespace: string, destDir: string) => {
const result = { copied: 0, skipped: 0 };
// Create temp directory
const tempDir = await mkdtemp(join(tmpdir(), "mervelas-hs-"));
try {
// SCP the projects folder
const scpResult = await execFileNoThrow(
"scp",
["-rq", `${homespace}.coder:/root/.mervelas/projects/`, tempDir],
{ timeout: 300000 },
);
if (scpResult.code !== 0) {
// SCP failed
return result;
}
const projectsDir = join(tempDir, "projects");
let projectDirents: Awaited<ReturnType<typeof readdir>>;
try {
projectDirents = await readdir(projectsDir, {
withFileTypes: true,
});
} catch {
return result;
}
// Merge into destination (parallel per project directory)
await Promise.all(
projectDirents.map(async (dirent) => {
const projectName = dirent.name;
const projectPath = join(projectsDir, projectName);
// Skip if not a directory
if (!dirent.isDirectory()) return;
const destProjectName = `${projectName}__${homespace}`;
const destProjectPath = join(destDir, destProjectName);
try {
await mkdir(destProjectPath, { recursive: true });
} catch {
// Directory may already exist
}
// Copy session files (skip existing)
let files: Awaited<ReturnType<typeof readdir>>;
try {
files = await readdir(projectPath, { withFileTypes: true });
} catch {
return;
}
await Promise.all(
files.map(async (fileDirent) => {
const fileName = fileDirent.name;
if (!fileName.endsWith(".jsonl")) return;
const srcFile = join(projectPath, fileName);
const destFile = join(destProjectPath, fileName);
try {
await copyFile(
srcFile,
destFile,
fsConstants.COPYFILE_EXCL,
);
result.copied++;
} catch {
// EEXIST from COPYFILE_EXCL means dest already exists
result.skipped++;
}
}),
);
}),
);
} finally {
try {
await rm(tempDir, { recursive: true, force: true });
} catch {
// Ignore cleanup errors
}
}
return result;
}
: async () => ({ copied: 0, skipped: 0 });
const collectAllRemoteHostData: (destDir: string) => Promise<{
hosts: RemoteHostInfo[];
totalCopied: number;
totalSkipped: number;
}> =
process.env.USER_TYPE === "ant"
? async (destDir: string) => {
const rHosts = await getRunningRemoteHosts();
const result: RemoteHostInfo[] = [];
let totalCopied = 0;
let totalSkipped = 0;
// Collect from all hosts in parallel (SCP per host can take seconds)
const hostResults = await Promise.all(
rHosts.map(async (hs) => {
const sessionCount = await getRemoteHostSessionCount(hs);
if (sessionCount > 0) {
const { copied, skipped } = await collectFromRemoteHost(
hs,
destDir,
);
return { name: hs, sessionCount, copied, skipped };
}
return { name: hs, sessionCount, copied: 0, skipped: 0 };
}),
);
for (const hr of hostResults) {
result.push({ name: hr.name, sessionCount: hr.sessionCount });
totalCopied += hr.copied;
totalSkipped += hr.skipped;
}
return { hosts: result, totalCopied, totalSkipped };
}
: async () => ({ hosts: [], totalCopied: 0, totalSkipped: 0 });
/* eslint-enable custom-rules/no-process-env-top-level */
// ============================================================================
// Types
// ============================================================================
type SessionMeta = {
session_id: string;
project_path: string;
start_time: string;
duration_minutes: number;
user_message_count: number;
assistant_message_count: number;
tool_counts: Record<string, number>;
languages: Record<string, number>;
git_commits: number;
git_pushes: number;
input_tokens: number;
output_tokens: number;
first_prompt: string;
summary?: string;
// New stats
user_interruptions: number;
user_response_times: number[];
tool_errors: number;
tool_error_categories: Record<string, number>;
uses_task_agent: boolean;
uses_mcp: boolean;
uses_web_search: boolean;
uses_web_fetch: boolean;
// Additional stats
lines_added: number;
lines_removed: number;
files_modified: number;
message_hours: number[];
user_message_timestamps: string[]; // ISO timestamps for multi-clauding detection
};
type SessionFacets = {
session_id: string;
underlying_goal: string;
goal_categories: Record<string, number>;
outcome: string;
user_satisfaction_counts: Record<string, number>;
claude_helpfulness: string;
session_type: string;
friction_counts: Record<string, number>;
friction_detail: string;
primary_success: string;
brief_summary: string;
user_instructions_to_claude?: string[];
};
type AggregatedData = {
total_sessions: number;
total_sessions_scanned?: number;
sessions_with_facets: number;
date_range: { start: string; end: string };
total_messages: number;
total_duration_hours: number;
total_input_tokens: number;
total_output_tokens: number;
tool_counts: Record<string, number>;
languages: Record<string, number>;
git_commits: number;
git_pushes: number;
projects: Record<string, number>;
goal_categories: Record<string, number>;
outcomes: Record<string, number>;
satisfaction: Record<string, number>;
helpfulness: Record<string, number>;
session_types: Record<string, number>;
friction: Record<string, number>;
success: Record<string, number>;
session_summaries: Array<{
id: string;
date: string;
summary: string;
goal?: string;
}>;
// New aggregated stats
total_interruptions: number;
total_tool_errors: number;
tool_error_categories: Record<string, number>;
user_response_times: number[];
median_response_time: number;
avg_response_time: number;
sessions_using_task_agent: number;
sessions_using_mcp: number;
sessions_using_web_search: number;
sessions_using_web_fetch: number;
// Additional stats from Python reference
total_lines_added: number;
total_lines_removed: number;
total_files_modified: number;
days_active: number;
messages_per_day: number;
message_hours: number[]; // Hour of day for each user message (for time of day chart)
// Multi-clauding stats (matching Python reference)
multi_clauding: {
overlap_events: number;
sessions_involved: number;
user_messages_during: number;
};
};
// ============================================================================
// Constants
// ============================================================================
const EXTENSION_TO_LANGUAGE: Record<string, string> = {
".ts": "TypeScript",
".tsx": "TypeScript",
".js": "JavaScript",
".jsx": "JavaScript",
".py": "Python",
".rb": "Ruby",
".go": "Go",
".rs": "Rust",
".java": "Java",
".md": "Markdown",
".json": "JSON",
".yaml": "YAML",
".yml": "YAML",
".sh": "Shell",
".css": "CSS",
".html": "HTML",
};
// Label map for cleaning up category names (matching Python reference)
const LABEL_MAP: Record<string, string> = {
// Goal categories
debug_investigate: "Debug/Investigate",
implement_feature: "Implement Feature",
fix_bug: "Fix Bug",
write_script_tool: "Write Script/Tool",
refactor_code: "Refactor Code",
configure_system: "Configure System",
create_pr_commit: "Create PR/Commit",
analyze_data: "Analyze Data",
understand_codebase: "Understand Codebase",
write_tests: "Write Tests",
write_docs: "Write Docs",
deploy_infra: "Deploy/Infra",
warmup_minimal: "Cache Warmup",
// Success factors
fast_accurate_search: "Fast/Accurate Search",
correct_code_edits: "Correct Code Edits",
good_explanations: "Good Explanations",
proactive_help: "Proactive Help",
multi_file_changes: "Multi-file Changes",
handled_complexity: "Multi-file Changes",
good_debugging: "Good Debugging",
// Friction types
misunderstood_request: "Misunderstood Request",
wrong_approach: "Wrong Approach",
buggy_code: "Buggy Code",
user_rejected_action: "User Rejected Action",
claude_got_blocked: "Mervelas Got Blocked",
user_stopped_early: "User Stopped Early",
wrong_file_or_location: "Wrong File/Location",
excessive_changes: "Excessive Changes",
slow_or_verbose: "Slow/Verbose",
tool_failed: "Tool Failed",
user_unclear: "User Unclear",
external_issue: "External Issue",
// Satisfaction labels
frustrated: "Frustrated",
dissatisfied: "Dissatisfied",
likely_satisfied: "Likely Satisfied",
satisfied: "Satisfied",
happy: "Happy",
unsure: "Unsure",
neutral: "Neutral",
delighted: "Delighted",
// Session types
single_task: "Single Task",
multi_task: "Multi Task",
iterative_refinement: "Iterative Refinement",
exploration: "Exploration",
quick_question: "Quick Question",
// Outcomes
fully_achieved: "Fully Achieved",
mostly_achieved: "Mostly Achieved",
partially_achieved: "Partially Achieved",
not_achieved: "Not Achieved",
unclear_from_transcript: "Unclear",
// Helpfulness
unhelpful: "Unhelpful",
slightly_helpful: "Slightly Helpful",
moderately_helpful: "Moderately Helpful",
very_helpful: "Very Helpful",
essential: "Essential",
};
// Lazy getters: getClaudeConfigHomeDir() is memoized and reads process.env.
// Calling it at module scope would populate the memoize cache before
// entrypoints can set CLAUDE_CONFIG_DIR, breaking all 150+ other callers.
function getDataDir(): string {
return join(getClaudeConfigHomeDir(), "usage-data");
}
function getFacetsDir(): string {
return join(getDataDir(), "facets");
}
function getSessionMetaDir(): string {
return join(getDataDir(), "session-meta");
}
const FACET_EXTRACTION_PROMPT = `Analyze this Mervelas session and extract structured facets.
CRITICAL GUIDELINES:
1. **goal_categories**: Count ONLY what the USER explicitly asked for.
- DO NOT count Mervelas's autonomous codebase exploration
- DO NOT count work Mervelas decided to do on its own
- ONLY count when user says "can you...", "please...", "I need...", "let's..."
2. **user_satisfaction_counts**: Base ONLY on explicit user signals.
- "Yay!", "great!", "perfect!" → happy
- "thanks", "looks good", "that works" → satisfied
- "ok, now let's..." (continuing without complaint) → likely_satisfied
- "that's not right", "try again" → dissatisfied
- "this is broken", "I give up" → frustrated
3. **friction_counts**: Be specific about what went wrong.
- misunderstood_request: Mervelas interpreted incorrectly
- wrong_approach: Right goal, wrong solution method
- buggy_code: Code didn't work correctly
- user_rejected_action: User said no/stop to a tool call
- excessive_changes: Over-engineered or changed too much
4. If very short or just warmup, use warmup_minimal for goal_category
SESSION:
`;
// ============================================================================
// Helper Functions
// ============================================================================
function getLanguageFromPath(filePath: string): string | null {
const ext = extname(filePath).toLowerCase();
return EXTENSION_TO_LANGUAGE[ext] || null;
}
function extractToolStats(log: LogOption): {
toolCounts: Record<string, number>;
languages: Record<string, number>;
gitCommits: number;
gitPushes: number;
inputTokens: number;
outputTokens: number;
// New stats
userInterruptions: number;
userResponseTimes: number[];
toolErrors: number;
toolErrorCategories: Record<string, number>;
usesTaskAgent: boolean;
usesMcp: boolean;
usesWebSearch: boolean;
usesWebFetch: boolean;
// Additional stats
linesAdded: number;
linesRemoved: number;
filesModified: Set<string>;
messageHours: number[];
userMessageTimestamps: string[]; // ISO timestamps for multi-clauding detection
} {
const toolCounts: Record<string, number> = {};
const languages: Record<string, number> = {};
let gitCommits = 0;
let gitPushes = 0;
let inputTokens = 0;
let outputTokens = 0;
// New stats
let userInterruptions = 0;
const userResponseTimes: number[] = [];
let toolErrors = 0;
const toolErrorCategories: Record<string, number> = {};
let usesTaskAgent = false;
// Additional stats
let linesAdded = 0;
let linesRemoved = 0;
const filesModified = new Set<string>();
const messageHours: number[] = [];
const userMessageTimestamps: string[] = []; // For multi-clauding detection
let usesMcp = false;
let usesWebSearch = false;
let usesWebFetch = false;
let lastAssistantTimestamp: string | null = null;
for (const msg of log.messages) {
// Get message timestamp for response time calculation
const msgTimestamp = (msg as { timestamp?: string }).timestamp;
if (msg.type === "assistant" && msg.message) {
// Track timestamp for response time calculation
if (msgTimestamp) {
lastAssistantTimestamp = msgTimestamp;
}
const usage = (
msg.message as {
usage?: { input_tokens?: number; output_tokens?: number };
}
).usage;
if (usage) {
inputTokens += usage.input_tokens || 0;
outputTokens += usage.output_tokens || 0;
}
const content = msg.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "tool_use" && "name" in block) {
const toolName = block.name as string;
toolCounts[toolName] = (toolCounts[toolName] || 0) + 1;
// Check for special tool usage
if (
toolName === AGENT_TOOL_NAME ||
toolName === LEGACY_AGENT_TOOL_NAME
)
usesTaskAgent = true;
if (toolName.startsWith("mcp__")) usesMcp = true;
if (toolName === "WebSearch") usesWebSearch = true;
if (toolName === "WebFetch") usesWebFetch = true;
const input = (block as { input?: Record<string, unknown> }).input;
if (input) {
const filePath = (input.file_path as string) || "";
if (filePath) {
const lang = getLanguageFromPath(filePath);
if (lang) {
languages[lang] = (languages[lang] || 0) + 1;
}
// Track files modified by Edit/Write tools
if (toolName === "Edit" || toolName === "Write") {
filesModified.add(filePath);
}
}
if (toolName === "Edit") {
const oldString = (input.old_string as string) || "";
const newString = (input.new_string as string) || "";
for (const change of diffLines(oldString, newString)) {
if (change.added) linesAdded += change.count || 0;
if (change.removed) linesRemoved += change.count || 0;
}
}
// Track lines from Write tool (all added)
if (toolName === "Write") {
const writeContent = (input.content as string) || "";
if (writeContent) {
linesAdded += countCharInString(writeContent, "\n") + 1;
}
}
const command = (input.command as string) || "";
if (command.includes("git commit")) gitCommits++;
if (command.includes("git push")) gitPushes++;
}
}
}
}
}
// Check user messages
if (msg.type === "user" && msg.message) {
const content = msg.message.content;
// Check if this is an actual human message (has text) vs just tool_result
// matching Python reference logic
let isHumanMessage = false;
if (typeof content === "string" && content.trim()) {
isHumanMessage = true;
} else if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "text" && "text" in block) {
isHumanMessage = true;
break;
}
}
}
// Only track message hours and response times for actual human messages
if (isHumanMessage) {
// Track message hour for time-of-day analysis and timestamp for multi-clauding
if (msgTimestamp) {
try {
const msgDate = new Date(msgTimestamp);
const hour = msgDate.getHours(); // Local hour 0-23
messageHours.push(hour);
// Collect timestamp for multi-clauding detection (matching Python)
userMessageTimestamps.push(msgTimestamp);
} catch {
// Skip invalid timestamps
}
}
// Calculate response time (time from last assistant message to this user message)
// Only count gaps > 2 seconds (real user think time, not tool results)
if (lastAssistantTimestamp && msgTimestamp) {
const assistantTime = new Date(lastAssistantTimestamp).getTime();
const userTime = new Date(msgTimestamp).getTime();
const responseTimeSec = (userTime - assistantTime) / 1000;
// Only count reasonable response times (2s-1 hour) matching Python
if (responseTimeSec > 2 && responseTimeSec < 3600) {
userResponseTimes.push(responseTimeSec);
}
}
}
// Process tool results (for error tracking)
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "tool_result" && "content" in block) {
const isError = (block as { is_error?: boolean }).is_error;
// Count and categorize tool errors (matching Python reference logic)
if (isError) {
toolErrors++;
const resultContent = (block as { content?: string }).content;
let category = "Other";
if (typeof resultContent === "string") {
const lowerContent = resultContent.toLowerCase();
if (lowerContent.includes("exit code")) {
category = "Command Failed";
} else if (
lowerContent.includes("rejected") ||
lowerContent.includes("doesn't want")
) {
category = "User Rejected";
} else if (
lowerContent.includes("string to replace not found") ||
lowerContent.includes("no changes")
) {
category = "Edit Failed";
} else if (lowerContent.includes("modified since read")) {
category = "File Changed";
} else if (
lowerContent.includes("exceeds maximum") ||
lowerContent.includes("too large")
) {
category = "File Too Large";
} else if (
lowerContent.includes("file not found") ||
lowerContent.includes("does not exist")
) {
category = "File Not Found";
}
}
toolErrorCategories[category] =
(toolErrorCategories[category] || 0) + 1;
}
}
}
}
// Check for interruptions (matching Python reference)
if (typeof content === "string") {
if (content.includes("[Request interrupted by user")) {
userInterruptions++;
}
} else if (Array.isArray(content)) {
for (const block of content) {
if (
block.type === "text" &&
"text" in block &&
(block.text as string).includes("[Request interrupted by user")
) {
userInterruptions++;
break;
}
}
}
}
}
return {
toolCounts,
languages,
gitCommits,
gitPushes,
inputTokens,
outputTokens,
// New stats
userInterruptions,
userResponseTimes,
toolErrors,
toolErrorCategories,
usesTaskAgent,
usesMcp,
usesWebSearch,
usesWebFetch,
// Additional stats
linesAdded,
linesRemoved,
filesModified,
messageHours,
userMessageTimestamps,
};
}
function hasValidDates(log: LogOption): boolean {
return (
!Number.isNaN(log.created.getTime()) &&
!Number.isNaN(log.modified.getTime())
);
}
function logToSessionMeta(log: LogOption): SessionMeta {
const stats = extractToolStats(log);
const sessionId = getSessionIdFromLog(log) || "unknown";
const startTime = log.created.toISOString();
const durationMinutes = Math.round(
(log.modified.getTime() - log.created.getTime()) / 1000 / 60,
);
let userMessageCount = 0;
let assistantMessageCount = 0;
for (const msg of log.messages) {
if (msg.type === "assistant") assistantMessageCount++;
// Only count user messages that have actual text content (human messages)
// not just tool_result messages (matching Python reference)
if (msg.type === "user" && msg.message) {
const content = msg.message.content;
let isHumanMessage = false;
if (typeof content === "string" && content.trim()) {
isHumanMessage = true;
} else if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "text" && "text" in block) {
isHumanMessage = true;
break;
}
}
}
if (isHumanMessage) {
userMessageCount++;
}
}
}
return {
session_id: sessionId,
project_path: log.projectPath || "",
start_time: startTime,
duration_minutes: durationMinutes,
user_message_count: userMessageCount,
assistant_message_count: assistantMessageCount,
tool_counts: stats.toolCounts,
languages: stats.languages,
git_commits: stats.gitCommits,
git_pushes: stats.gitPushes,
input_tokens: stats.inputTokens,
output_tokens: stats.outputTokens,
first_prompt: log.firstPrompt || "",
summary: log.summary,
// New stats
user_interruptions: stats.userInterruptions,
user_response_times: stats.userResponseTimes,
tool_errors: stats.toolErrors,
tool_error_categories: stats.toolErrorCategories,
uses_task_agent: stats.usesTaskAgent,
uses_mcp: stats.usesMcp,
uses_web_search: stats.usesWebSearch,
uses_web_fetch: stats.usesWebFetch,
// Additional stats
lines_added: stats.linesAdded,
lines_removed: stats.linesRemoved,
files_modified: stats.filesModified.size,
message_hours: stats.messageHours,
user_message_timestamps: stats.userMessageTimestamps,
};
}
/**
* Deduplicate conversation branches within the same session.
*
* When a session file has multiple leaf messages (from retries or branching),
* loadAllLogsFromSessionFile produces one LogOption per leaf. Each branch
* shares the same root message, so its duration overlaps with sibling
* branches. This keeps only the branch with the most user messages
* (tie-break by longest duration) per session_id.
*/
export function deduplicateSessionBranches(
entries: Array<{ log: LogOption; meta: SessionMeta }>,
): Array<{ log: LogOption; meta: SessionMeta }> {
const bestBySession = new Map<
string,
{ log: LogOption; meta: SessionMeta }
>();
for (const entry of entries) {
const id = entry.meta.session_id;
const existing = bestBySession.get(id);
if (
!existing ||
entry.meta.user_message_count > existing.meta.user_message_count ||
(entry.meta.user_message_count === existing.meta.user_message_count &&
entry.meta.duration_minutes > existing.meta.duration_minutes)
) {
bestBySession.set(id, entry);
}
}
return [...bestBySession.values()];
}
function formatTranscriptForFacets(log: LogOption): string {
const lines: string[] = [];
const meta = logToSessionMeta(log);
lines.push(`Session: ${meta.session_id.slice(0, 8)}`);
lines.push(`Date: ${meta.start_time}`);
lines.push(`Project: ${meta.project_path}`);
lines.push(`Duration: ${meta.duration_minutes} min`);
lines.push("");
for (const msg of log.messages) {
if (msg.type === "user" && msg.message) {
const content = msg.message.content;
if (typeof content === "string") {
lines.push(`[User]: ${content.slice(0, 500)}`);
} else if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "text" && "text" in block) {
lines.push(`[User]: ${(block.text as string).slice(0, 500)}`);
}
}
}
} else if (msg.type === "assistant" && msg.message) {
const content = msg.message.content;
if (Array.isArray(content)) {
for (const block of content) {
if (block.type === "text" && "text" in block) {
lines.push(`[Assistant]: ${(block.text as string).slice(0, 300)}`);
} else if (block.type === "tool_use" && "name" in block) {
lines.push(`[Tool: ${block.name}]`);
}
}
}
}
}
return lines.join("\n");
}
const SUMMARIZE_CHUNK_PROMPT = `Summarize this portion of a Mervelas session transcript. Focus on:
1. What the user asked for
2. What Mervelas did (tools used, files modified)
3. Any friction or issues
4. The outcome
Keep it concise - 3-5 sentences. Preserve specific details like file names, error messages, and user feedback.
TRANSCRIPT CHUNK:
`;
async function summarizeTranscriptChunk(chunk: string): Promise<string> {
try {
const result = await queryWithModel({
systemPrompt: asSystemPrompt([]),
userPrompt: SUMMARIZE_CHUNK_PROMPT + chunk,
signal: new AbortController().signal,
options: {
model: getAnalysisModel(),
querySource: "insights",
agents: [],
isNonInteractiveSession: true,
hasAppendSystemPrompt: false,
mcpTools: [],
maxOutputTokensOverride: 500,
},
});
const text = extractTextContent(result.message.content);
return text || chunk.slice(0, 2000);
} catch {
// On error, just return truncated chunk
return chunk.slice(0, 2000);
}
}
async function formatTranscriptWithSummarization(
log: LogOption,
): Promise<string> {
const fullTranscript = formatTranscriptForFacets(log);
// If under 30k chars, use as-is
if (fullTranscript.length <= 30000) {
return fullTranscript;
}
// For long transcripts, split into chunks and summarize in parallel
const CHUNK_SIZE = 25000;
const chunks: string[] = [];
for (let i = 0; i < fullTranscript.length; i += CHUNK_SIZE) {
chunks.push(fullTranscript.slice(i, i + CHUNK_SIZE));
}
// Summarize all chunks in parallel
const summaries = await Promise.all(chunks.map(summarizeTranscriptChunk));
// Combine summaries with session header
const meta = logToSessionMeta(log);
const header = [
`Session: ${meta.session_id.slice(0, 8)}`,
`Date: ${meta.start_time}`,
`Project: ${meta.project_path}`,
`Duration: ${meta.duration_minutes} min`,
`[Long session - ${chunks.length} parts summarized]`,
"",
].join("\n");
return header + summaries.join("\n\n---\n\n");
}
async function loadCachedFacets(
sessionId: string,
): Promise<SessionFacets | null> {
const facetPath = join(getFacetsDir(), `${sessionId}.json`);
try {
const content = await readFile(facetPath, { encoding: "utf-8" });
const parsed: unknown = jsonParse(content);
if (!isValidSessionFacets(parsed)) {
// Delete corrupted cache file so it gets re-extracted next run
try {
await unlink(facetPath);
} catch {
// Ignore deletion errors
}
return null;
}
return parsed;
} catch {
return null;
}
}
async function saveFacets(facets: SessionFacets): Promise<void> {
try {
await mkdir(getFacetsDir(), { recursive: true });
} catch {
// Directory may already exist
}
const facetPath = join(getFacetsDir(), `${facets.session_id}.json`);
await writeFile(facetPath, jsonStringify(facets, null, 2), {
encoding: "utf-8",
mode: 0o600,
});
}
async function loadCachedSessionMeta(
sessionId: string,
): Promise<SessionMeta | null> {
const metaPath = join(getSessionMetaDir(), `${sessionId}.json`);
try {
const content = await readFile(metaPath, { encoding: "utf-8" });
return jsonParse(content);
} catch {
return null;
}
}
async function saveSessionMeta(meta: SessionMeta): Promise<void> {
try {
await mkdir(getSessionMetaDir(), { recursive: true });
} catch {
// Directory may already exist
}
const metaPath = join(getSessionMetaDir(), `${meta.session_id}.json`);
await writeFile(metaPath, jsonStringify(meta, null, 2), {
encoding: "utf-8",
mode: 0o600,
});
}
async function extractFacetsFromAPI(
log: LogOption,
sessionId: string,
): Promise<SessionFacets | null> {
try {
// Use summarization for long transcripts
const transcript = await formatTranscriptWithSummarization(log);
// Build prompt asking for JSON directly (no tool use)
const jsonPrompt = `${FACET_EXTRACTION_PROMPT}${transcript}
RESPOND WITH ONLY A VALID JSON OBJECT matching this schema:
{
"underlying_goal": "What the user fundamentally wanted to achieve",
"goal_categories": {"category_name": count, ...},
"outcome": "fully_achieved|mostly_achieved|partially_achieved|not_achieved|unclear_from_transcript",
"user_satisfaction_counts": {"level": count, ...},
"claude_helpfulness": "unhelpful|slightly_helpful|moderately_helpful|very_helpful|essential",
"session_type": "single_task|multi_task|iterative_refinement|exploration|quick_question",
"friction_counts": {"friction_type": count, ...},
"friction_detail": "One sentence describing friction or empty",
"primary_success": "none|fast_accurate_search|correct_code_edits|good_explanations|proactive_help|multi_file_changes|good_debugging",
"brief_summary": "One sentence: what user wanted and whether they got it"
}`;
const result = await queryWithModel({
systemPrompt: asSystemPrompt([]),
userPrompt: jsonPrompt,
signal: new AbortController().signal,
options: {
model: getAnalysisModel(),
querySource: "insights",
agents: [],
isNonInteractiveSession: true,
hasAppendSystemPrompt: false,
mcpTools: [],
maxOutputTokensOverride: 4096,
},
});
const text = extractTextContent(result.message.content);
// Parse JSON from response
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (!jsonMatch) return null;
const parsed: unknown = jsonParse(jsonMatch[0]);
if (!isValidSessionFacets(parsed)) return null;
const facets: SessionFacets = { ...parsed, session_id: sessionId };
return facets;
} catch (err) {
logError(new Error(`Facet extraction failed: ${toError(err).message}`));
return null;
}
}
/**
* Detects multi-clauding (using multiple Mervelas sessions concurrently).
* Uses a sliding window to find the pattern: session1 -> session2 -> session1
* within a 30-minute window.
*/
export function detectMultiClauding(
sessions: Array<{
session_id: string;
user_message_timestamps: string[];
}>,
): {
overlap_events: number;
sessions_involved: number;
user_messages_during: number;
} {
const OVERLAP_WINDOW_MS = 30 * 60000;
const allSessionMessages: Array<{ ts: number; sessionId: string }> = [];
for (const session of sessions) {
for (const timestamp of session.user_message_timestamps) {
try {
const ts = new Date(timestamp).getTime();
allSessionMessages.push({ ts, sessionId: session.session_id });
} catch {
// Skip invalid timestamps
}
}
}
allSessionMessages.sort((a, b) => a.ts - b.ts);
const multiClaudeSessionPairs = new Set<string>();
const messagesDuringMulticlaude = new Set<string>();
// Sliding window: sessionLastIndex tracks the most recent index for each session
let windowStart = 0;
const sessionLastIndex = new Map<string, number>();
for (let i = 0; i < allSessionMessages.length; i++) {
const msg = allSessionMessages[i]!;
// Shrink window from the left
while (
windowStart < i &&
msg.ts - allSessionMessages[windowStart]!.ts > OVERLAP_WINDOW_MS
) {
const expiring = allSessionMessages[windowStart]!;
if (sessionLastIndex.get(expiring.sessionId) === windowStart) {
sessionLastIndex.delete(expiring.sessionId);
}
windowStart++;
}
// Check if this session appeared earlier in the window (pattern: s1 -> s2 -> s1)
const prevIndex = sessionLastIndex.get(msg.sessionId);
if (prevIndex !== undefined) {
for (let j = prevIndex + 1; j < i; j++) {
const between = allSessionMessages[j]!;
if (between.sessionId !== msg.sessionId) {
const pair = [msg.sessionId, between.sessionId].sort().join(":");
multiClaudeSessionPairs.add(pair);
messagesDuringMulticlaude.add(
`${allSessionMessages[prevIndex]!.ts}:${msg.sessionId}`,
);
messagesDuringMulticlaude.add(`${between.ts}:${between.sessionId}`);
messagesDuringMulticlaude.add(`${msg.ts}:${msg.sessionId}`);
break;
}
}
}
sessionLastIndex.set(msg.sessionId, i);
}
const sessionsWithOverlaps = new Set<string>();
for (const pair of multiClaudeSessionPairs) {
const [s1, s2] = pair.split(":");
if (s1) sessionsWithOverlaps.add(s1);
if (s2) sessionsWithOverlaps.add(s2);
}
return {
overlap_events: multiClaudeSessionPairs.size,
sessions_involved: sessionsWithOverlaps.size,
user_messages_during: messagesDuringMulticlaude.size,
};
}
function aggregateData(
sessions: SessionMeta[],
facets: Map<string, SessionFacets>,
): AggregatedData {
const result: AggregatedData = {
total_sessions: sessions.length,
sessions_with_facets: facets.size,
date_range: { start: "", end: "" },
total_messages: 0,
total_duration_hours: 0,
total_input_tokens: 0,
total_output_tokens: 0,
tool_counts: {},
languages: {},
git_commits: 0,
git_pushes: 0,
projects: {},
goal_categories: {},
outcomes: {},
satisfaction: {},
helpfulness: {},
session_types: {},
friction: {},
success: {},
session_summaries: [],
// New stats
total_interruptions: 0,
total_tool_errors: 0,
tool_error_categories: {},
user_response_times: [],
median_response_time: 0,
avg_response_time: 0,
sessions_using_task_agent: 0,
sessions_using_mcp: 0,
sessions_using_web_search: 0,
sessions_using_web_fetch: 0,
// Additional stats
total_lines_added: 0,
total_lines_removed: 0,
total_files_modified: 0,
days_active: 0,
messages_per_day: 0,
message_hours: [],
// Multi-clauding stats (matching Python reference)
multi_clauding: {
overlap_events: 0,
sessions_involved: 0,
user_messages_during: 0,
},
};
const dates: string[] = [];
const allResponseTimes: number[] = [];
const allMessageHours: number[] = [];
for (const session of sessions) {
dates.push(session.start_time);
result.total_messages += session.user_message_count;
result.total_duration_hours += session.duration_minutes / 60;
result.total_input_tokens += session.input_tokens;
result.total_output_tokens += session.output_tokens;
result.git_commits += session.git_commits;
result.git_pushes += session.git_pushes;
// New stats aggregation
result.total_interruptions += session.user_interruptions;
result.total_tool_errors += session.tool_errors;
for (const [cat, count] of Object.entries(session.tool_error_categories)) {
result.tool_error_categories[cat] =
(result.tool_error_categories[cat] || 0) + count;
}
allResponseTimes.push(...session.user_response_times);
if (session.uses_task_agent) result.sessions_using_task_agent++;
if (session.uses_mcp) result.sessions_using_mcp++;
if (session.uses_web_search) result.sessions_using_web_search++;
if (session.uses_web_fetch) result.sessions_using_web_fetch++;
// Additional stats aggregation
result.total_lines_added += session.lines_added;
result.total_lines_removed += session.lines_removed;
result.total_files_modified += session.files_modified;
allMessageHours.push(...session.message_hours);
for (const [tool, count] of Object.entries(session.tool_counts)) {
result.tool_counts[tool] = (result.tool_counts[tool] || 0) + count;
}
for (const [lang, count] of Object.entries(session.languages)) {
result.languages[lang] = (result.languages[lang] || 0) + count;
}
if (session.project_path) {
result.projects[session.project_path] =
(result.projects[session.project_path] || 0) + 1;
}
const sessionFacets = facets.get(session.session_id);
if (sessionFacets) {
// Goal categories
for (const [cat, count] of safeEntries(sessionFacets.goal_categories)) {
if (count > 0) {
result.goal_categories[cat] =
(result.goal_categories[cat] || 0) + count;
}
}
// Outcomes
result.outcomes[sessionFacets.outcome] =
(result.outcomes[sessionFacets.outcome] || 0) + 1;
// Satisfaction counts
for (const [level, count] of safeEntries(
sessionFacets.user_satisfaction_counts,
)) {
if (count > 0) {
result.satisfaction[level] =
(result.satisfaction[level] || 0) + count;
}
}
// Helpfulness
result.helpfulness[sessionFacets.claude_helpfulness] =
(result.helpfulness[sessionFacets.claude_helpfulness] || 0) + 1;
// Session types
result.session_types[sessionFacets.session_type] =
(result.session_types[sessionFacets.session_type] || 0) + 1;
// Friction counts
for (const [type, count] of safeEntries(sessionFacets.friction_counts)) {
if (count > 0) {
result.friction[type] = (result.friction[type] || 0) + count;
}
}
// Success factors
if (sessionFacets.primary_success !== "none") {
result.success[sessionFacets.primary_success] =
(result.success[sessionFacets.primary_success] || 0) + 1;
}
}
if (result.session_summaries.length < 50) {
result.session_summaries.push({
id: session.session_id.slice(0, 8),
date: session.start_time.split("T")[0] || "",
summary: session.summary || session.first_prompt.slice(0, 100),
goal: sessionFacets?.underlying_goal,
});
}
}
dates.sort();
result.date_range.start = dates[0]?.split("T")[0] || "";
result.date_range.end = dates[dates.length - 1]?.split("T")[0] || "";
// Calculate response time stats
result.user_response_times = allResponseTimes;
if (allResponseTimes.length > 0) {
const sorted = [...allResponseTimes].sort((a, b) => a - b);
result.median_response_time = sorted[Math.floor(sorted.length / 2)] || 0;
result.avg_response_time =
allResponseTimes.reduce((a, b) => a + b, 0) / allResponseTimes.length;
}
// Calculate days active and messages per day
const uniqueDays = new Set(dates.map((d) => d.split("T")[0]));
result.days_active = uniqueDays.size;
result.messages_per_day =
result.days_active > 0
? Math.round((result.total_messages / result.days_active) * 10) / 10
: 0;
// Store message hours for time-of-day chart
result.message_hours = allMessageHours;
result.multi_clauding = detectMultiClauding(sessions);
return result;
}
// ============================================================================
// Parallel Insights Generation (6 sections)
// ============================================================================
type InsightSection = {
name: string;
prompt: string;
maxTokens: number;
};
// Sections that run in parallel first
const INSIGHT_SECTIONS: InsightSection[] = [
{
name: "project_areas",
prompt: `Analyze this Mervelas usage data and identify project areas.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"areas": [
{"name": "Area name", "session_count": N, "description": "2-3 sentences about what was worked on and how Mervelas was used."}
]
}
Include 4-5 areas. Skip internal CC operations.`,
maxTokens: 8192,
},
{
name: "interaction_style",
prompt: `Analyze this Mervelas usage data and describe the user's interaction style.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"narrative": "2-3 paragraphs analyzing HOW the user interacts with Mervelas. Use second person 'you'. Describe patterns: iterate quickly vs detailed upfront specs? Interrupt often or let Mervelas run? Include specific examples. Use **bold** for key insights.",
"key_pattern": "One sentence summary of most distinctive interaction style"
}`,
maxTokens: 8192,
},
{
name: "what_works",
prompt: `Analyze this Mervelas usage data and identify what's working well for this user. Use second person ("you").
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"intro": "1 sentence of context",
"impressive_workflows": [
{"title": "Short title (3-6 words)", "description": "2-3 sentences describing the impressive workflow or approach. Use 'you' not 'the user'."}
]
}
Include 3 impressive workflows.`,
maxTokens: 8192,
},
{
name: "friction_analysis",
prompt: `Analyze this Mervelas usage data and identify friction points for this user. Use second person ("you").
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"intro": "1 sentence summarizing friction patterns",
"categories": [
{"category": "Concrete category name", "description": "1-2 sentences explaining this category and what could be done differently. Use 'you' not 'the user'.", "examples": ["Specific example with consequence", "Another example"]}
]
}
Include 3 friction categories with 2 examples each.`,
maxTokens: 8192,
},
{
name: "suggestions",
prompt: `Analyze this Mervelas usage data and suggest improvements.
## CC FEATURES REFERENCE (pick from these for features_to_try):
1. **MCP Servers**: Connect Mervelas to external tools, databases, and APIs via Model Context Protocol.
- How to use: Run \`mervelas mcp add <server-name> -- <command>\`
- Good for: database queries, Slack integration, GitHub issue lookup, connecting to internal APIs
2. **Custom Skills**: Reusable prompts you define as markdown files that run with a single /command.
- How to use: Create \`.mervelas/skills/commit/SKILL.md\` with instructions. Then type \`/commit\` to run it.
- Good for: repetitive workflows - /commit, /review, /test, /deploy, /pr, or complex multi-step workflows
3. **Hooks**: Shell commands that auto-run at specific lifecycle events.
- How to use: Add to \`.mervelas/settings.json\` under "hooks" key.
- Good for: auto-formatting code, running type checks, enforcing conventions
4. **Headless Mode**: Run Mervelas non-interactively from scripts and CI/CD.
- How to use: \`mervelas -p "fix lint errors" --allowedTools "Edit,Read,Bash"\`
- Good for: CI/CD integration, batch code fixes, automated reviews
5. **Task Agents**: Mervelas spawns focused sub-agents for complex exploration or parallel work.
- How to use: Mervelas auto-invokes when helpful, or ask "use an agent to explore X"
- Good for: codebase exploration, understanding complex systems
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"claude_md_additions": [
{"addition": "A specific line or block to add to MERVELAS.md based on workflow patterns. E.g., 'Always run tests after modifying auth-related files'", "why": "1 sentence explaining why this would help based on actual sessions", "prompt_scaffold": "Instructions for where to add this in MERVELAS.md. E.g., 'Add under ## Testing section'"}
],
"features_to_try": [
{"feature": "Feature name from CC FEATURES REFERENCE above", "one_liner": "What it does", "why_for_you": "Why this would help YOU based on your sessions", "example_code": "Actual command or config to copy"}
],
"usage_patterns": [
{"title": "Short title", "suggestion": "1-2 sentence summary", "detail": "3-4 sentences explaining how this applies to YOUR work", "copyable_prompt": "A specific prompt to copy and try"}
]
}
IMPORTANT for claude_md_additions: PRIORITIZE instructions that appear MULTIPLE TIMES in the user data. If user told Mervelas the same thing in 2+ sessions (e.g., 'always run tests', 'use TypeScript'), that's a PRIME candidate - they shouldn't have to repeat themselves.
IMPORTANT for features_to_try: Pick 2-3 from the CC FEATURES REFERENCE above. Include 2-3 items for each category.`,
maxTokens: 8192,
},
{
name: "on_the_horizon",
prompt: `Analyze this Mervelas usage data and identify future opportunities.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"intro": "1 sentence about evolving AI-assisted development",
"opportunities": [
{"title": "Short title (4-8 words)", "whats_possible": "2-3 ambitious sentences about autonomous workflows", "how_to_try": "1-2 sentences mentioning relevant tooling", "copyable_prompt": "Detailed prompt to try"}
]
}
Include 3 opportunities. Think BIG - autonomous workflows, parallel agents, iterating against tests.`,
maxTokens: 8192,
},
...(process.env.USER_TYPE === "ant"
? [
{
name: "cc_team_improvements",
prompt: `Analyze this Mervelas usage data and suggest product improvements for the CC team.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"improvements": [
{"title": "Product/tooling improvement", "detail": "3-4 sentences describing the improvement", "evidence": "3-4 sentences with specific session examples"}
]
}
Include 2-3 improvements based on friction patterns observed.`,
maxTokens: 8192,
},
{
name: "model_behavior_improvements",
prompt: `Analyze this Mervelas usage data and suggest model behavior improvements.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"improvements": [
{"title": "Model behavior change", "detail": "3-4 sentences describing what the model should do differently", "evidence": "3-4 sentences with specific examples"}
]
}
Include 2-3 improvements based on friction patterns observed.`,
maxTokens: 8192,
},
]
: []),
{
name: "fun_ending",
prompt: `Analyze this Mervelas usage data and find a memorable moment.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"headline": "A memorable QUALITATIVE moment from the transcripts - not a statistic. Something human, funny, or surprising.",
"detail": "Brief context about when/where this happened"
}
Find something genuinely interesting or amusing from the session summaries.`,
maxTokens: 8192,
},
];
type InsightResults = {
at_a_glance?: {
whats_working?: string;
whats_hindering?: string;
quick_wins?: string;
ambitious_workflows?: string;
};
project_areas?: {
areas?: Array<{ name: string; session_count: number; description: string }>;
};
interaction_style?: {
narrative?: string;
key_pattern?: string;
};
what_works?: {
intro?: string;
impressive_workflows?: Array<{ title: string; description: string }>;
};
friction_analysis?: {
intro?: string;
categories?: Array<{
category: string;
description: string;
examples?: string[];
}>;
};
suggestions?: {
claude_md_additions?: Array<{
addition: string;
why: string;
where?: string;
prompt_scaffold?: string;
}>;
features_to_try?: Array<{
feature: string;
one_liner: string;
why_for_you: string;
example_code?: string;
}>;
usage_patterns?: Array<{
title: string;
suggestion: string;
detail?: string;
copyable_prompt?: string;
}>;
};
on_the_horizon?: {
intro?: string;
opportunities?: Array<{
title: string;
whats_possible: string;
how_to_try?: string;
copyable_prompt?: string;
}>;
};
cc_team_improvements?: {
improvements?: Array<{
title: string;
detail: string;
evidence?: string;
}>;
};
model_behavior_improvements?: {
improvements?: Array<{
title: string;
detail: string;
evidence?: string;
}>;
};
fun_ending?: {
headline?: string;
detail?: string;
};
};
async function generateSectionInsight(
section: InsightSection,
dataContext: string,
): Promise<{ name: string; result: unknown }> {
try {
const result = await queryWithModel({
systemPrompt: asSystemPrompt([]),
userPrompt: section.prompt + "\n\nDATA:\n" + dataContext,
signal: new AbortController().signal,
options: {
model: getInsightsModel(),
querySource: "insights",
agents: [],
isNonInteractiveSession: true,
hasAppendSystemPrompt: false,
mcpTools: [],
maxOutputTokensOverride: section.maxTokens,
},
});
const text = extractTextContent(result.message.content);
if (text) {
// Parse JSON from response
const jsonMatch = text.match(/\{[\s\S]*\}/);
if (jsonMatch) {
try {
return { name: section.name, result: jsonParse(jsonMatch[0]) };
} catch {
return { name: section.name, result: null };
}
}
}
return { name: section.name, result: null };
} catch (err) {
logError(new Error(`${section.name} failed: ${toError(err).message}`));
return { name: section.name, result: null };
}
}
async function generateParallelInsights(
data: AggregatedData,
facets: Map<string, SessionFacets>,
): Promise<InsightResults> {
// Build data context string
const facetSummaries = Array.from(facets.values())
.slice(0, 50)
.map((f) => `- ${f.brief_summary} (${f.outcome}, ${f.claude_helpfulness})`)
.join("\n");
const frictionDetails = Array.from(facets.values())
.filter((f) => f.friction_detail)
.slice(0, 20)
.map((f) => `- ${f.friction_detail}`)
.join("\n");
const userInstructions = Array.from(facets.values())
.flatMap((f) => f.user_instructions_to_claude || [])
.slice(0, 15)
.map((i) => `- ${i}`)
.join("\n");
const dataContext = jsonStringify(
{
sessions: data.total_sessions,
analyzed: data.sessions_with_facets,
date_range: data.date_range,
messages: data.total_messages,
hours: Math.round(data.total_duration_hours),
commits: data.git_commits,
top_tools: Object.entries(data.tool_counts)
.sort((a, b) => b[1] - a[1])
.slice(0, 8),
top_goals: Object.entries(data.goal_categories)
.sort((a, b) => b[1] - a[1])
.slice(0, 8),
outcomes: data.outcomes,
satisfaction: data.satisfaction,
friction: data.friction,
success: data.success,
languages: data.languages,
},
null,
2,
);
const fullContext =
dataContext +
"\n\nSESSION SUMMARIES:\n" +
facetSummaries +
"\n\nFRICTION DETAILS:\n" +
frictionDetails +
"\n\nUSER INSTRUCTIONS TO CLAUDE:\n" +
(userInstructions || "None captured");
// Run sections in parallel first (excluding at_a_glance)
const results = await Promise.all(
INSIGHT_SECTIONS.map((section) =>
generateSectionInsight(section, fullContext),
),
);
// Combine results
const insights: InsightResults = {};
for (const { name, result } of results) {
if (result) {
(insights as Record<string, unknown>)[name] = result;
}
}
// Build rich context from generated sections for At a Glance
const projectAreasText =
(
insights.project_areas as {
areas?: Array<{ name: string; description: string }>;
}
)?.areas
?.map((a) => `- ${a.name}: ${a.description}`)
.join("\n") || "";
const bigWinsText =
(
insights.what_works as {
impressive_workflows?: Array<{ title: string; description: string }>;
}
)?.impressive_workflows
?.map((w) => `- ${w.title}: ${w.description}`)
.join("\n") || "";
const frictionText =
(
insights.friction_analysis as {
categories?: Array<{ category: string; description: string }>;
}
)?.categories
?.map((c) => `- ${c.category}: ${c.description}`)
.join("\n") || "";
const featuresText =
(
insights.suggestions as {
features_to_try?: Array<{ feature: string; one_liner: string }>;
}
)?.features_to_try
?.map((f) => `- ${f.feature}: ${f.one_liner}`)
.join("\n") || "";
const patternsText =
(
insights.suggestions as {
usage_patterns?: Array<{ title: string; suggestion: string }>;
}
)?.usage_patterns
?.map((p) => `- ${p.title}: ${p.suggestion}`)
.join("\n") || "";
const horizonText =
(
insights.on_the_horizon as {
opportunities?: Array<{ title: string; whats_possible: string }>;
}
)?.opportunities
?.map((o) => `- ${o.title}: ${o.whats_possible}`)
.join("\n") || "";
// Now generate "At a Glance" with access to other sections' outputs
const atAGlancePrompt = `You're writing an "At a Glance" summary for a Mervelas usage insights report for Mervelas users. The goal is to help them understand their usage and improve how they can use Mervelas better, especially as models improve.
Use this 4-part structure:
1. **What's working** - What is the user's unique style of interacting with Mervelas and what are some impactful things they've done? You can include one or two details, but keep it high level since things might not be fresh in the user's memory. Don't be fluffy or overly complimentary. Also, don't focus on the tool calls they use.
2. **What's hindering you** - Split into (a) Mervelas's fault (misunderstandings, wrong approaches, bugs) and (b) user-side friction (not providing enough context, environment issues -- ideally more general than just one project). Be honest but constructive.
3. **Quick wins to try** - Specific Mervelas features they could try from the examples below, or a workflow technique if you think it's really compelling. (Avoid stuff like "Ask Mervelas to confirm before taking actions" or "Type out more context up front" which are less compelling.)
4. **Ambitious workflows for better models** - As we move to much more capable models over the next 3-6 months, what should they prepare for? What workflows that seem impossible now will become possible? Draw from the appropriate section below.
Keep each section to 2-3 not-too-long sentences. Don't overwhelm the user. Don't mention specific numerical stats or underlined_categories from the session data below. Use a coaching tone.
RESPOND WITH ONLY A VALID JSON OBJECT:
{
"whats_working": "(refer to instructions above)",
"whats_hindering": "(refer to instructions above)",
"quick_wins": "(refer to instructions above)",
"ambitious_workflows": "(refer to instructions above)"
}
SESSION DATA:
${fullContext}
## Project Areas (what user works on)
${projectAreasText}
## Big Wins (impressive accomplishments)
${bigWinsText}
## Friction Categories (where things go wrong)
${frictionText}
## Features to Try
${featuresText}
## Usage Patterns to Adopt
${patternsText}
## On the Horizon (ambitious workflows for better models)
${horizonText}`;
const atAGlanceSection: InsightSection = {
name: "at_a_glance",
prompt: atAGlancePrompt,
maxTokens: 8192,
};
const atAGlanceResult = await generateSectionInsight(atAGlanceSection, "");
if (atAGlanceResult.result) {
insights.at_a_glance = atAGlanceResult.result as {
whats_working?: string;
whats_hindering?: string;
quick_wins?: string;
ambitious_workflows?: string;
};
}
return insights;
}
// Escape HTML but render **bold** as <strong>
function escapeHtmlWithBold(text: string): string {
const escaped = escapeHtml(text);
return escaped.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
}
// Fixed orderings for specific charts (matching Python reference)
const SATISFACTION_ORDER = [
"frustrated",
"dissatisfied",
"likely_satisfied",
"satisfied",
"happy",
"unsure",
];
const OUTCOME_ORDER = [
"not_achieved",
"partially_achieved",
"mostly_achieved",
"fully_achieved",
"unclear_from_transcript",
];
function generateBarChart(
data: Record<string, number>,
color: string,
maxItems = 6,
fixedOrder?: string[],
): string {
let entries: [string, number][];
if (fixedOrder) {
// Use fixed order, only including items that exist in data
entries = fixedOrder
.filter((key) => key in data && (data[key] ?? 0) > 0)
.map((key) => [key, data[key] ?? 0] as [string, number]);
} else {
// Sort by count descending
entries = Object.entries(data)
.sort((a, b) => b[1] - a[1])
.slice(0, maxItems);
}
if (entries.length === 0) return '<p class="empty">No data</p>';
const maxVal = Math.max(...entries.map((e) => e[1]));
return entries
.map(([label, count]) => {
const pct = (count / maxVal) * 100;
// Use LABEL_MAP if available, otherwise clean up underscores and title case
const cleanLabel =
LABEL_MAP[label] ||
label.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
return `<div class="bar-row">
<div class="bar-label">${escapeHtml(cleanLabel)}</div>
<div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:${color}"></div></div>
<div class="bar-value">${count}</div>
</div>`;
})
.join("\n");
}
function generateResponseTimeHistogram(times: number[]): string {
if (times.length === 0) return '<p class="empty">No response time data</p>';
// Create buckets (matching Python reference)
const buckets: Record<string, number> = {
"2-10s": 0,
"10-30s": 0,
"30s-1m": 0,
"1-2m": 0,
"2-5m": 0,
"5-15m": 0,
">15m": 0,
};
for (const t of times) {
if (t < 10) buckets["2-10s"] = (buckets["2-10s"] ?? 0) + 1;
else if (t < 30) buckets["10-30s"] = (buckets["10-30s"] ?? 0) + 1;
else if (t < 60) buckets["30s-1m"] = (buckets["30s-1m"] ?? 0) + 1;
else if (t < 120) buckets["1-2m"] = (buckets["1-2m"] ?? 0) + 1;
else if (t < 300) buckets["2-5m"] = (buckets["2-5m"] ?? 0) + 1;
else if (t < 900) buckets["5-15m"] = (buckets["5-15m"] ?? 0) + 1;
else buckets[">15m"] = (buckets[">15m"] ?? 0) + 1;
}
const maxVal = Math.max(...Object.values(buckets));
if (maxVal === 0) return '<p class="empty">No response time data</p>';
return Object.entries(buckets)
.map(([label, count]) => {
const pct = (count / maxVal) * 100;
return `<div class="bar-row">
<div class="bar-label">${label}</div>
<div class="bar-track"><div class="bar-fill" style="width:${pct}%;background:#6366f1"></div></div>
<div class="bar-value">${count}</div>
</div>`;
})
.join("\n");
}
function generateTimeOfDayChart(messageHours: number[]): string {
if (messageHours.length === 0) return '<p class="empty">No time data</p>';
// Group into time periods
const periods = [
{ label: "Morning (6-12)", range: [6, 7, 8, 9, 10, 11] },
{ label: "Afternoon (12-18)", range: [12, 13, 14, 15, 16, 17] },
{ label: "Evening (18-24)", range: [18, 19, 20, 21, 22, 23] },
{ label: "Night (0-6)", range: [0, 1, 2, 3, 4, 5] },
];
const hourCounts: Record<number, number> = {};
for (const h of messageHours) {
hourCounts[h] = (hourCounts[h] || 0) + 1;
}
const periodCounts = periods.map((p) => ({
label: p.label,
count: p.range.reduce((sum, h) => sum + (hourCounts[h] || 0), 0),
}));
const maxVal = Math.max(...periodCounts.map((p) => p.count)) || 1;
const barsHtml = periodCounts
.map(
(p) => `
<div class="bar-row">
<div class="bar-label">${p.label}</div>
<div class="bar-track"><div class="bar-fill" style="width:${(p.count / maxVal) * 100}%;background:#8b5cf6"></div></div>
<div class="bar-value">${p.count}</div>
</div>`,
)
.join("\n");
return `<div id="hour-histogram">${barsHtml}</div>`;
}
function getHourCountsJson(messageHours: number[]): string {
const hourCounts: Record<number, number> = {};
for (const h of messageHours) {
hourCounts[h] = (hourCounts[h] || 0) + 1;
}
return jsonStringify(hourCounts);
}
function generateHtmlReport(
data: AggregatedData,
insights: InsightResults,
): string {
const markdownToHtml = (md: string): string => {
if (!md) return "";
return md
.split("\n\n")
.map((p) => {
let html = escapeHtml(p);
html = html.replace(/\*\*(.+?)\*\*/g, "<strong>$1</strong>");
html = html.replace(/^- /gm, "• ");
html = html.replace(/\n/g, "<br>");
return `<p>${html}</p>`;
})
.join("\n");
};
// Build At a Glance section (new 4-part format with links to sections)
const atAGlance = insights.at_a_glance;
const atAGlanceHtml = atAGlance
? `
<div class="at-a-glance">
<div class="glance-title">At a Glance</div>
<div class="glance-sections">
${atAGlance.whats_working ? `<div class="glance-section"><strong>What's working:</strong> ${escapeHtmlWithBold(atAGlance.whats_working)} <a href="#section-wins" class="see-more">Impressive Things You Did →</a></div>` : ""}
${atAGlance.whats_hindering ? `<div class="glance-section"><strong>What's hindering you:</strong> ${escapeHtmlWithBold(atAGlance.whats_hindering)} <a href="#section-friction" class="see-more">Where Things Go Wrong →</a></div>` : ""}
${atAGlance.quick_wins ? `<div class="glance-section"><strong>Quick wins to try:</strong> ${escapeHtmlWithBold(atAGlance.quick_wins)} <a href="#section-features" class="see-more">Features to Try →</a></div>` : ""}
${atAGlance.ambitious_workflows ? `<div class="glance-section"><strong>Ambitious workflows:</strong> ${escapeHtmlWithBold(atAGlance.ambitious_workflows)} <a href="#section-horizon" class="see-more">On the Horizon →</a></div>` : ""}
</div>
</div>
`
: "";
// Build project areas section
const projectAreas = insights.project_areas?.areas || [];
const projectAreasHtml =
projectAreas.length > 0
? `
<h2 id="section-work">What You Work On</h2>
<div class="project-areas">
${projectAreas
.map(
(area) => `
<div class="project-area">
<div class="area-header">
<span class="area-name">${escapeHtml(area.name)}</span>
<span class="area-count">~${area.session_count} sessions</span>
</div>
<div class="area-desc">${escapeHtml(area.description)}</div>
</div>
`,
)
.join("")}
</div>
`
: "";
// Build interaction style section
const interactionStyle = insights.interaction_style;
const interactionHtml = interactionStyle?.narrative
? `
<h2 id="section-usage">How You Use Mervelas</h2>
<div class="narrative">
${markdownToHtml(interactionStyle.narrative)}
${interactionStyle.key_pattern ? `<div class="key-insight"><strong>Key pattern:</strong> ${escapeHtml(interactionStyle.key_pattern)}</div>` : ""}
</div>
`
: "";
// Build what works section
const whatWorks = insights.what_works;
const whatWorksHtml =
whatWorks?.impressive_workflows && whatWorks.impressive_workflows.length > 0
? `
<h2 id="section-wins">Impressive Things You Did</h2>
${whatWorks.intro ? `<p class="section-intro">${escapeHtml(whatWorks.intro)}</p>` : ""}
<div class="big-wins">
${whatWorks.impressive_workflows
.map(
(wf) => `
<div class="big-win">
<div class="big-win-title">${escapeHtml(wf.title || "")}</div>
<div class="big-win-desc">${escapeHtml(wf.description || "")}</div>
</div>
`,
)
.join("")}
</div>
`
: "";
// Build friction section
const frictionAnalysis = insights.friction_analysis;
const frictionHtml =
frictionAnalysis?.categories && frictionAnalysis.categories.length > 0
? `
<h2 id="section-friction">Where Things Go Wrong</h2>
${frictionAnalysis.intro ? `<p class="section-intro">${escapeHtml(frictionAnalysis.intro)}</p>` : ""}
<div class="friction-categories">
${frictionAnalysis.categories
.map(
(cat) => `
<div class="friction-category">
<div class="friction-title">${escapeHtml(cat.category || "")}</div>
<div class="friction-desc">${escapeHtml(cat.description || "")}</div>
${cat.examples ? `<ul class="friction-examples">${cat.examples.map((ex) => `<li>${escapeHtml(ex)}</li>`).join("")}</ul>` : ""}
</div>
`,
)
.join("")}
</div>
`
: "";
// Build suggestions section
const suggestions = insights.suggestions;
const suggestionsHtml = suggestions
? `
${
suggestions.claude_md_additions &&
suggestions.claude_md_additions.length > 0
? `
<h2 id="section-features">Existing CC Features to Try</h2>
<div class="mervelas-md-section">
<h3>Suggested MERVELAS.md Additions</h3>
<p style="font-size: 12px; color: #64748b; margin-bottom: 12px;">Just copy this into Mervelas to add it to your MERVELAS.md.</p>
<div class="mervelas-md-actions">
<button class="copy-all-btn" onclick="copyAllCheckedClaudeMd()">Copy All Checked</button>
</div>
${suggestions.claude_md_additions
.map(
(add, i) => `
<div class="mervelas-md-item">
<input type="checkbox" id="cmd-${i}" class="cmd-checkbox" checked data-text="${escapeHtml(add.prompt_scaffold || add.where || "Add to MERVELAS.md")}\\n\\n${escapeHtml(add.addition)}">
<label for="cmd-${i}">
<code class="cmd-code">${escapeHtml(add.addition)}</code>
<button class="copy-btn" onclick="copyCmdItem(${i})">Copy</button>
</label>
<div class="cmd-why">${escapeHtml(add.why)}</div>
</div>
`,
)
.join("")}
</div>
`
: ""
}
${
suggestions.features_to_try && suggestions.features_to_try.length > 0
? `
<p style="font-size: 13px; color: #64748b; margin-bottom: 12px;">Just copy this into Mervelas and it'll set it up for you.</p>
<div class="features-section">
${suggestions.features_to_try
.map(
(feat) => `
<div class="feature-card">
<div class="feature-title">${escapeHtml(feat.feature || "")}</div>
<div class="feature-oneliner">${escapeHtml(feat.one_liner || "")}</div>
<div class="feature-why"><strong>Why for you:</strong> ${escapeHtml(feat.why_for_you || "")}</div>
${
feat.example_code
? `
<div class="feature-examples">
<div class="feature-example">
<div class="example-code-row">
<code class="example-code">${escapeHtml(feat.example_code)}</code>
<button class="copy-btn" onclick="copyText(this)">Copy</button>
</div>
</div>
</div>
`
: ""
}
</div>
`,
)
.join("")}
</div>
`
: ""
}
${
suggestions.usage_patterns && suggestions.usage_patterns.length > 0
? `
<h2 id="section-patterns">New Ways to Use Mervelas</h2>
<p style="font-size: 13px; color: #64748b; margin-bottom: 12px;">Just copy this into Mervelas and it'll walk you through it.</p>
<div class="patterns-section">
${suggestions.usage_patterns
.map(
(pat) => `
<div class="pattern-card">
<div class="pattern-title">${escapeHtml(pat.title || "")}</div>
<div class="pattern-summary">${escapeHtml(pat.suggestion || "")}</div>
${pat.detail ? `<div class="pattern-detail">${escapeHtml(pat.detail)}</div>` : ""}
${
pat.copyable_prompt
? `
<div class="copyable-prompt-section">
<div class="prompt-label">Paste into Mervelas:</div>
<div class="copyable-prompt-row">
<code class="copyable-prompt">${escapeHtml(pat.copyable_prompt)}</code>
<button class="copy-btn" onclick="copyText(this)">Copy</button>
</div>
</div>
`
: ""
}
</div>
`,
)
.join("")}
</div>
`
: ""
}
`
: "";
// Build On the Horizon section
const horizonData = insights.on_the_horizon;
const horizonHtml =
horizonData?.opportunities && horizonData.opportunities.length > 0
? `
<h2 id="section-horizon">On the Horizon</h2>
${horizonData.intro ? `<p class="section-intro">${escapeHtml(horizonData.intro)}</p>` : ""}
<div class="horizon-section">
${horizonData.opportunities
.map(
(opp) => `
<div class="horizon-card">
<div class="horizon-title">${escapeHtml(opp.title || "")}</div>
<div class="horizon-possible">${escapeHtml(opp.whats_possible || "")}</div>
${opp.how_to_try ? `<div class="horizon-tip"><strong>Getting started:</strong> ${escapeHtml(opp.how_to_try)}</div>` : ""}
${opp.copyable_prompt ? `<div class="pattern-prompt"><div class="prompt-label">Paste into Mervelas:</div><code>${escapeHtml(opp.copyable_prompt)}</code><button class="copy-btn" onclick="copyText(this)">Copy</button></div>` : ""}
</div>
`,
)
.join("")}
</div>
`
: "";
// Build Team Feedback section (collapsible, ant-only)
const ccImprovements =
process.env.USER_TYPE === "ant"
? insights.cc_team_improvements?.improvements || []
: [];
const modelImprovements =
process.env.USER_TYPE === "ant"
? insights.model_behavior_improvements?.improvements || []
: [];
const teamFeedbackHtml =
ccImprovements.length > 0 || modelImprovements.length > 0
? `
<h2 id="section-feedback" class="feedback-header">Closing the Loop: Feedback for Other Teams</h2>
<p class="feedback-intro">Suggestions for the CC product and model teams based on your usage patterns. Click to expand.</p>
${
ccImprovements.length > 0
? `
<div class="collapsible-section">
<div class="collapsible-header" onclick="toggleCollapsible(this)">
<span class="collapsible-arrow">▶</span>
<h3>Product Improvements for CC Team</h3>
</div>
<div class="collapsible-content">
<div class="suggestions-section">
${ccImprovements
.map(
(imp) => `
<div class="feedback-card team-card">
<div class="feedback-title">${escapeHtml(imp.title || "")}</div>
<div class="feedback-detail">${escapeHtml(imp.detail || "")}</div>
${imp.evidence ? `<div class="feedback-evidence"><em>Evidence:</em> ${escapeHtml(imp.evidence)}</div>` : ""}
</div>
`,
)
.join("")}
</div>
</div>
</div>
`
: ""
}
${
modelImprovements.length > 0
? `
<div class="collapsible-section">
<div class="collapsible-header" onclick="toggleCollapsible(this)">
<span class="collapsible-arrow">▶</span>
<h3>Model Behavior Improvements</h3>
</div>
<div class="collapsible-content">
<div class="suggestions-section">
${modelImprovements
.map(
(imp) => `
<div class="feedback-card model-card">
<div class="feedback-title">${escapeHtml(imp.title || "")}</div>
<div class="feedback-detail">${escapeHtml(imp.detail || "")}</div>
${imp.evidence ? `<div class="feedback-evidence"><em>Evidence:</em> ${escapeHtml(imp.evidence)}</div>` : ""}
</div>
`,
)
.join("")}
</div>
</div>
</div>
`
: ""
}
`
: "";
// Build Fun Ending section
const funEnding = insights.fun_ending;
const funEndingHtml = funEnding?.headline
? `
<div class="fun-ending">
<div class="fun-headline">"${escapeHtml(funEnding.headline)}"</div>
${funEnding.detail ? `<div class="fun-detail">${escapeHtml(funEnding.detail)}</div>` : ""}
</div>
`
: "";
const css = `
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif; background: #f8fafc; color: #334155; line-height: 1.65; padding: 48px 24px; }
.container { max-width: 800px; margin: 0 auto; }
h1 { font-size: 32px; font-weight: 700; color: #0f172a; margin-bottom: 8px; }
h2 { font-size: 20px; font-weight: 600; color: #0f172a; margin-top: 48px; margin-bottom: 16px; }
.subtitle { color: #64748b; font-size: 15px; margin-bottom: 32px; }
.nav-toc { display: flex; flex-wrap: wrap; gap: 8px; margin: 24px 0 32px 0; padding: 16px; background: white; border-radius: 8px; border: 1px solid #e2e8f0; }
.nav-toc a { font-size: 12px; color: #64748b; text-decoration: none; padding: 6px 12px; border-radius: 6px; background: #f1f5f9; transition: all 0.15s; }
.nav-toc a:hover { background: #e2e8f0; color: #334155; }
.stats-row { display: flex; gap: 24px; margin-bottom: 40px; padding: 20px 0; border-top: 1px solid #e2e8f0; border-bottom: 1px solid #e2e8f0; flex-wrap: wrap; }
.stat { text-align: center; }
.stat-value { font-size: 24px; font-weight: 700; color: #0f172a; }
.stat-label { font-size: 11px; color: #64748b; text-transform: uppercase; }
.at-a-glance { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #f59e0b; border-radius: 12px; padding: 20px 24px; margin-bottom: 32px; }
.glance-title { font-size: 16px; font-weight: 700; color: #92400e; margin-bottom: 16px; }
.glance-sections { display: flex; flex-direction: column; gap: 12px; }
.glance-section { font-size: 14px; color: #78350f; line-height: 1.6; }
.glance-section strong { color: #92400e; }
.see-more { color: #b45309; text-decoration: none; font-size: 13px; white-space: nowrap; }
.see-more:hover { text-decoration: underline; }
.project-areas { display: flex; flex-direction: column; gap: 12px; margin-bottom: 32px; }
.project-area { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; }
.area-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }
.area-name { font-weight: 600; font-size: 15px; color: #0f172a; }
.area-count { font-size: 12px; color: #64748b; background: #f1f5f9; padding: 2px 8px; border-radius: 4px; }
.area-desc { font-size: 14px; color: #475569; line-height: 1.5; }
.narrative { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 20px; margin-bottom: 24px; }
.narrative p { margin-bottom: 12px; font-size: 14px; color: #475569; line-height: 1.7; }
.key-insight { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 12px 16px; margin-top: 12px; font-size: 14px; color: #166534; }
.section-intro { font-size: 14px; color: #64748b; margin-bottom: 16px; }
.big-wins { display: flex; flex-direction: column; gap: 12px; margin-bottom: 24px; }
.big-win { background: #f0fdf4; border: 1px solid #bbf7d0; border-radius: 8px; padding: 16px; }
.big-win-title { font-weight: 600; font-size: 15px; color: #166534; margin-bottom: 8px; }
.big-win-desc { font-size: 14px; color: #15803d; line-height: 1.5; }
.friction-categories { display: flex; flex-direction: column; gap: 16px; margin-bottom: 24px; }
.friction-category { background: #fef2f2; border: 1px solid #fca5a5; border-radius: 8px; padding: 16px; }
.friction-title { font-weight: 600; font-size: 15px; color: #991b1b; margin-bottom: 6px; }
.friction-desc { font-size: 13px; color: #7f1d1d; margin-bottom: 10px; }
.friction-examples { margin: 0 0 0 20px; font-size: 13px; color: #334155; }
.friction-examples li { margin-bottom: 4px; }
.mervelas-md-section { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px; padding: 16px; margin-bottom: 20px; }
.mervelas-md-section h3 { font-size: 14px; font-weight: 600; color: #1e40af; margin: 0 0 12px 0; }
.mervelas-md-actions { margin-bottom: 12px; padding-bottom: 12px; border-bottom: 1px solid #dbeafe; }
.copy-all-btn { background: #2563eb; color: white; border: none; border-radius: 4px; padding: 6px 12px; font-size: 12px; cursor: pointer; font-weight: 500; transition: all 0.2s; }
.copy-all-btn:hover { background: #1d4ed8; }
.copy-all-btn.copied { background: #16a34a; }
.mervelas-md-item { display: flex; flex-wrap: wrap; align-items: flex-start; gap: 8px; padding: 10px 0; border-bottom: 1px solid #dbeafe; }
.mervelas-md-item:last-child { border-bottom: none; }
.cmd-checkbox { margin-top: 2px; }
.cmd-code { background: white; padding: 8px 12px; border-radius: 4px; font-size: 12px; color: #1e40af; border: 1px solid #bfdbfe; font-family: monospace; display: block; white-space: pre-wrap; word-break: break-word; flex: 1; }
.cmd-why { font-size: 12px; color: #64748b; width: 100%; padding-left: 24px; margin-top: 4px; }
.features-section, .patterns-section { display: flex; flex-direction: column; gap: 12px; margin: 16px 0; }
.feature-card { background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; padding: 16px; }
.pattern-card { background: #f0f9ff; border: 1px solid #7dd3fc; border-radius: 8px; padding: 16px; }
.feature-title, .pattern-title { font-weight: 600; font-size: 15px; color: #0f172a; margin-bottom: 6px; }
.feature-oneliner { font-size: 14px; color: #475569; margin-bottom: 8px; }
.pattern-summary { font-size: 14px; color: #475569; margin-bottom: 8px; }
.feature-why, .pattern-detail { font-size: 13px; color: #334155; line-height: 1.5; }
.feature-examples { margin-top: 12px; }
.feature-example { padding: 8px 0; border-top: 1px solid #d1fae5; }
.feature-example:first-child { border-top: none; }
.example-desc { font-size: 13px; color: #334155; margin-bottom: 6px; }
.example-code-row { display: flex; align-items: flex-start; gap: 8px; }
.example-code { flex: 1; background: #f1f5f9; padding: 8px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; overflow-x: auto; white-space: pre-wrap; }
.copyable-prompt-section { margin-top: 12px; padding-top: 12px; border-top: 1px solid #e2e8f0; }
.copyable-prompt-row { display: flex; align-items: flex-start; gap: 8px; }
.copyable-prompt { flex: 1; background: #f8fafc; padding: 10px 12px; border-radius: 4px; font-family: monospace; font-size: 12px; color: #334155; border: 1px solid #e2e8f0; white-space: pre-wrap; line-height: 1.5; }
.feature-code { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; display: flex; align-items: flex-start; gap: 8px; }
.feature-code code { flex: 1; font-family: monospace; font-size: 12px; color: #334155; white-space: pre-wrap; }
.pattern-prompt { background: #f8fafc; padding: 12px; border-radius: 6px; margin-top: 12px; border: 1px solid #e2e8f0; }
.pattern-prompt code { font-family: monospace; font-size: 12px; color: #334155; display: block; white-space: pre-wrap; margin-bottom: 8px; }
.prompt-label { font-size: 11px; font-weight: 600; text-transform: uppercase; color: #64748b; margin-bottom: 6px; }
.copy-btn { background: #e2e8f0; border: none; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; color: #475569; flex-shrink: 0; }
.copy-btn:hover { background: #cbd5e1; }
.charts-row { display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin: 24px 0; }
.chart-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; }
.chart-title { font-size: 12px; font-weight: 600; color: #64748b; text-transform: uppercase; margin-bottom: 12px; }
.bar-row { display: flex; align-items: center; margin-bottom: 6px; }
.bar-label { width: 100px; font-size: 11px; color: #475569; flex-shrink: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.bar-track { flex: 1; height: 6px; background: #f1f5f9; border-radius: 3px; margin: 0 8px; }
.bar-fill { height: 100%; border-radius: 3px; }
.bar-value { width: 28px; font-size: 11px; font-weight: 500; color: #64748b; text-align: right; }
.empty { color: #94a3b8; font-size: 13px; }
.horizon-section { display: flex; flex-direction: column; gap: 16px; }
.horizon-card { background: linear-gradient(135deg, #faf5ff 0%, #f5f3ff 100%); border: 1px solid #c4b5fd; border-radius: 8px; padding: 16px; }
.horizon-title { font-weight: 600; font-size: 15px; color: #5b21b6; margin-bottom: 8px; }
.horizon-possible { font-size: 14px; color: #334155; margin-bottom: 10px; line-height: 1.5; }
.horizon-tip { font-size: 13px; color: #6b21a8; background: rgba(255,255,255,0.6); padding: 8px 12px; border-radius: 4px; }
.feedback-header { margin-top: 48px; color: #64748b; font-size: 16px; }
.feedback-intro { font-size: 13px; color: #94a3b8; margin-bottom: 16px; }
.feedback-section { margin-top: 16px; }
.feedback-section h3 { font-size: 14px; font-weight: 600; color: #475569; margin-bottom: 12px; }
.feedback-card { background: white; border: 1px solid #e2e8f0; border-radius: 8px; padding: 16px; margin-bottom: 12px; }
.feedback-card.team-card { background: #eff6ff; border-color: #bfdbfe; }
.feedback-card.model-card { background: #faf5ff; border-color: #e9d5ff; }
.feedback-title { font-weight: 600; font-size: 14px; color: #0f172a; margin-bottom: 6px; }
.feedback-detail { font-size: 13px; color: #475569; line-height: 1.5; }
.feedback-evidence { font-size: 12px; color: #64748b; margin-top: 8px; }
.fun-ending { background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border: 1px solid #fbbf24; border-radius: 12px; padding: 24px; margin-top: 40px; text-align: center; }
.fun-headline { font-size: 18px; font-weight: 600; color: #78350f; margin-bottom: 8px; }
.fun-detail { font-size: 14px; color: #92400e; }
.collapsible-section { margin-top: 16px; }
.collapsible-header { display: flex; align-items: center; gap: 8px; cursor: pointer; padding: 12px 0; border-bottom: 1px solid #e2e8f0; }
.collapsible-header h3 { margin: 0; font-size: 14px; font-weight: 600; color: #475569; }
.collapsible-arrow { font-size: 12px; color: #94a3b8; transition: transform 0.2s; }
.collapsible-content { display: none; padding-top: 16px; }
.collapsible-content.open { display: block; }
.collapsible-header.open .collapsible-arrow { transform: rotate(90deg); }
@media (max-width: 640px) { .charts-row { grid-template-columns: 1fr; } .stats-row { justify-content: center; } }
`;
const hourCountsJson = getHourCountsJson(data.message_hours);
const js = `
function toggleCollapsible(header) {
header.classList.toggle('open');
const content = header.nextElementSibling;
content.classList.toggle('open');
}
function copyText(btn) {
const code = btn.previousElementSibling;
navigator.clipboard.writeText(code.textContent).then(() => {
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy'; }, 2000);
});
}
function copyCmdItem(idx) {
const checkbox = document.getElementById('cmd-' + idx);
if (checkbox) {
const text = checkbox.dataset.text;
navigator.clipboard.writeText(text).then(() => {
const btn = checkbox.nextElementSibling.querySelector('.copy-btn');
if (btn) { btn.textContent = 'Copied!'; setTimeout(() => { btn.textContent = 'Copy'; }, 2000); }
});
}
}
function copyAllCheckedClaudeMd() {
const checkboxes = document.querySelectorAll('.cmd-checkbox:checked');
const texts = [];
checkboxes.forEach(cb => {
if (cb.dataset.text) { texts.push(cb.dataset.text); }
});
const combined = texts.join('\\n');
const btn = document.querySelector('.copy-all-btn');
if (btn) {
navigator.clipboard.writeText(combined).then(() => {
btn.textContent = 'Copied ' + texts.length + ' items!';
btn.classList.add('copied');
setTimeout(() => { btn.textContent = 'Copy All Checked'; btn.classList.remove('copied'); }, 2000);
});
}
}
// Timezone selector for time of day chart (data is from our own analytics, not user input)
const rawHourCounts = ${hourCountsJson};
function updateHourHistogram(offsetFromPT) {
const periods = [
{ label: "Morning (6-12)", range: [6,7,8,9,10,11] },
{ label: "Afternoon (12-18)", range: [12,13,14,15,16,17] },
{ label: "Evening (18-24)", range: [18,19,20,21,22,23] },
{ label: "Night (0-6)", range: [0,1,2,3,4,5] }
];
const adjustedCounts = {};
for (const [hour, count] of Object.entries(rawHourCounts)) {
const newHour = (parseInt(hour) + offsetFromPT + 24) % 24;
adjustedCounts[newHour] = (adjustedCounts[newHour] || 0) + count;
}
const periodCounts = periods.map(p => ({
label: p.label,
count: p.range.reduce((sum, h) => sum + (adjustedCounts[h] || 0), 0)
}));
const maxCount = Math.max(...periodCounts.map(p => p.count)) || 1;
const container = document.getElementById('hour-histogram');
container.textContent = '';
periodCounts.forEach(p => {
const row = document.createElement('div');
row.className = 'bar-row';
const label = document.createElement('div');
label.className = 'bar-label';
label.textContent = p.label;
const track = document.createElement('div');
track.className = 'bar-track';
const fill = document.createElement('div');
fill.className = 'bar-fill';
fill.style.width = (p.count / maxCount) * 100 + '%';
fill.style.background = '#8b5cf6';
track.appendChild(fill);
const value = document.createElement('div');
value.className = 'bar-value';
value.textContent = p.count;
row.appendChild(label);
row.appendChild(track);
row.appendChild(value);
container.appendChild(row);
});
}
document.getElementById('timezone-select').addEventListener('change', function() {
const customInput = document.getElementById('custom-offset');
if (this.value === 'custom') {
customInput.style.display = 'inline-block';
customInput.focus();
} else {
customInput.style.display = 'none';
updateHourHistogram(parseInt(this.value));
}
});
document.getElementById('custom-offset').addEventListener('change', function() {
const offset = parseInt(this.value) + 8;
updateHourHistogram(offset);
});
`;
return `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mervelas Insights</title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>${css}</style>
</head>
<body>
<div class="container">
<h1>Mervelas Insights</h1>
<p class="subtitle">${data.total_messages.toLocaleString()} messages across ${data.total_sessions} sessions${data.total_sessions_scanned && data.total_sessions_scanned > data.total_sessions ? ` (${data.total_sessions_scanned.toLocaleString()} total)` : ""} | ${data.date_range.start} to ${data.date_range.end}</p>
${atAGlanceHtml}
<nav class="nav-toc">
<a href="#section-work">What You Work On</a>
<a href="#section-usage">How You Use CC</a>
<a href="#section-wins">Impressive Things</a>
<a href="#section-friction">Where Things Go Wrong</a>
<a href="#section-features">Features to Try</a>
<a href="#section-patterns">New Usage Patterns</a>
<a href="#section-horizon">On the Horizon</a>
<a href="#section-feedback">Team Feedback</a>
</nav>
<div class="stats-row">
<div class="stat"><div class="stat-value">${data.total_messages.toLocaleString()}</div><div class="stat-label">Messages</div></div>
<div class="stat"><div class="stat-value">+${data.total_lines_added.toLocaleString()}/-${data.total_lines_removed.toLocaleString()}</div><div class="stat-label">Lines</div></div>
<div class="stat"><div class="stat-value">${data.total_files_modified}</div><div class="stat-label">Files</div></div>
<div class="stat"><div class="stat-value">${data.days_active}</div><div class="stat-label">Days</div></div>
<div class="stat"><div class="stat-value">${data.messages_per_day}</div><div class="stat-label">Msgs/Day</div></div>
</div>
${projectAreasHtml}
<div class="charts-row">
<div class="chart-card">
<div class="chart-title">What You Wanted</div>
${generateBarChart(data.goal_categories, "#2563eb")}
</div>
<div class="chart-card">
<div class="chart-title">Top Tools Used</div>
${generateBarChart(data.tool_counts, "#0891b2")}
</div>
</div>
<div class="charts-row">
<div class="chart-card">
<div class="chart-title">Languages</div>
${generateBarChart(data.languages, "#10b981")}
</div>
<div class="chart-card">
<div class="chart-title">Session Types</div>
${generateBarChart(data.session_types || {}, "#8b5cf6")}
</div>
</div>
${interactionHtml}
<!-- Response Time Distribution -->
<div class="chart-card" style="margin: 24px 0;">
<div class="chart-title">User Response Time Distribution</div>
${generateResponseTimeHistogram(data.user_response_times)}
<div style="font-size: 12px; color: #64748b; margin-top: 8px;">
Median: ${data.median_response_time.toFixed(1)}s • Average: ${data.avg_response_time.toFixed(1)}s
</div>
</div>
<!-- Multi-clauding Section (matching Python reference) -->
<div class="chart-card" style="margin: 24px 0;">
<div class="chart-title">Multi-Clauding (Parallel Sessions)</div>
${
data.multi_clauding.overlap_events === 0
? `
<p style="font-size: 14px; color: #64748b; padding: 8px 0;">
No parallel session usage detected. You typically work with one Mervelas session at a time.
</p>
`
: `
<div style="display: flex; gap: 24px; margin: 12px 0;">
<div style="text-align: center;">
<div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.multi_clauding.overlap_events}</div>
<div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Overlap Events</div>
</div>
<div style="text-align: center;">
<div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.multi_clauding.sessions_involved}</div>
<div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Sessions Involved</div>
</div>
<div style="text-align: center;">
<div style="font-size: 24px; font-weight: 700; color: #7c3aed;">${data.total_messages > 0 ? Math.round((100 * data.multi_clauding.user_messages_during) / data.total_messages) : 0}%</div>
<div style="font-size: 11px; color: #64748b; text-transform: uppercase;">Of Messages</div>
</div>
</div>
<p style="font-size: 13px; color: #475569; margin-top: 12px;">
You run multiple Mervelas sessions simultaneously. Multi-clauding is detected when sessions
overlap in time, suggesting parallel workflows.
</p>
`
}
</div>
<!-- Time of Day & Tool Errors -->
<div class="charts-row">
<div class="chart-card">
<div class="chart-title" style="display: flex; align-items: center; gap: 12px;">
User Messages by Time of Day
<select id="timezone-select" style="font-size: 12px; padding: 4px 8px; border-radius: 4px; border: 1px solid #e2e8f0;">
<option value="0">PT (UTC-8)</option>
<option value="3">ET (UTC-5)</option>
<option value="8">London (UTC)</option>
<option value="9">CET (UTC+1)</option>
<option value="17">Tokyo (UTC+9)</option>
<option value="custom">Custom offset...</option>
</select>
<input type="number" id="custom-offset" placeholder="UTC offset" style="display: none; width: 80px; font-size: 12px; padding: 4px; border-radius: 4px; border: 1px solid #e2e8f0;">
</div>
${generateTimeOfDayChart(data.message_hours)}
</div>
<div class="chart-card">
<div class="chart-title">Tool Errors Encountered</div>
${Object.keys(data.tool_error_categories).length > 0 ? generateBarChart(data.tool_error_categories, "#dc2626") : '<p class="empty">No tool errors</p>'}
</div>
</div>
${whatWorksHtml}
<div class="charts-row">
<div class="chart-card">
<div class="chart-title">What Helped Most (Mervelas's Capabilities)</div>
${generateBarChart(data.success, "#16a34a")}
</div>
<div class="chart-card">
<div class="chart-title">Outcomes</div>
${generateBarChart(data.outcomes, "#8b5cf6", 6, OUTCOME_ORDER)}
</div>
</div>
${frictionHtml}
<div class="charts-row">
<div class="chart-card">
<div class="chart-title">Primary Friction Types</div>
${generateBarChart(data.friction, "#dc2626")}
</div>
<div class="chart-card">
<div class="chart-title">Inferred Satisfaction (model-estimated)</div>
${generateBarChart(data.satisfaction, "#eab308", 6, SATISFACTION_ORDER)}
</div>
</div>
${suggestionsHtml}
${horizonHtml}
${funEndingHtml}
${teamFeedbackHtml}
</div>
<script>${js}</script>
</body>
</html>`;
}
// ============================================================================
// Export Types & Functions
// ============================================================================
/**
* Structured export format for claudescope consumption
*/
export type InsightsExport = {
metadata: {
username: string;
generated_at: string;
claude_code_version: string;
date_range: { start: string; end: string };
session_count: number;
remote_hosts_collected?: string[];
};
aggregated_data: AggregatedData;
insights: InsightResults;
facets_summary?: {
total: number;
goal_categories: Record<string, number>;
outcomes: Record<string, number>;
satisfaction: Record<string, number>;
friction: Record<string, number>;
};
};
/**
* Build export data from already-computed values.
* Used by background upload to S3.
*/
export function buildExportData(
data: AggregatedData,
insights: InsightResults,
facets: Map<string, SessionFacets>,
remoteStats?: { hosts: RemoteHostInfo[]; totalCopied: number },
): InsightsExport {
const version = typeof MACRO !== "undefined" ? MACRO.VERSION : "unknown";
const remote_hosts_collected = remoteStats?.hosts
.filter((h) => h.sessionCount > 0)
.map((h) => h.name);
const facets_summary = {
total: facets.size,
goal_categories: {} as Record<string, number>,
outcomes: {} as Record<string, number>,
satisfaction: {} as Record<string, number>,
friction: {} as Record<string, number>,
};
for (const f of facets.values()) {
for (const [cat, count] of safeEntries(f.goal_categories)) {
if (count > 0) {
facets_summary.goal_categories[cat] =
(facets_summary.goal_categories[cat] || 0) + count;
}
}
facets_summary.outcomes[f.outcome] =
(facets_summary.outcomes[f.outcome] || 0) + 1;
for (const [level, count] of safeEntries(f.user_satisfaction_counts)) {
if (count > 0) {
facets_summary.satisfaction[level] =
(facets_summary.satisfaction[level] || 0) + count;
}
}
for (const [type, count] of safeEntries(f.friction_counts)) {
if (count > 0) {
facets_summary.friction[type] =
(facets_summary.friction[type] || 0) + count;
}
}
}
return {
metadata: {
username: process.env.SAFEUSER || process.env.USER || "unknown",
generated_at: new Date().toISOString(),
claude_code_version: version,
date_range: data.date_range,
session_count: data.total_sessions,
...(remote_hosts_collected &&
remote_hosts_collected.length > 0 && {
remote_hosts_collected,
}),
},
aggregated_data: data,
insights,
facets_summary,
};
}
// ============================================================================
// Lite Session Scanning
// ============================================================================
type LiteSessionInfo = {
sessionId: string;
path: string;
mtime: number;
size: number;
};
/**
* Scans all project directories using filesystem metadata only (no JSONL parsing).
* Returns a list of session file info sorted by mtime descending.
* Yields to the event loop between project directories to keep the UI responsive.
*/
async function scanAllSessions(): Promise<LiteSessionInfo[]> {
const projectsDir = getProjectsDir();
let dirents: Awaited<ReturnType<typeof readdir>>;
try {
dirents = await readdir(projectsDir, { withFileTypes: true });
} catch {
return [];
}
const projectDirs = dirents
.filter((dirent) => dirent.isDirectory())
.map((dirent) => join(projectsDir, dirent.name));
const allSessions: LiteSessionInfo[] = [];
for (let i = 0; i < projectDirs.length; i++) {
const sessionFiles = await getSessionFilesWithMtime(projectDirs[i]!);
for (const [sessionId, fileInfo] of sessionFiles) {
allSessions.push({
sessionId,
path: fileInfo.path,
mtime: fileInfo.mtime,
size: fileInfo.size,
});
}
// Yield to event loop every 10 project directories
if (i % 10 === 9) {
await new Promise<void>((resolve) => setImmediate(resolve));
}
}
// Sort by mtime descending (most recent first)
allSessions.sort((a, b) => b.mtime - a.mtime);
return allSessions;
}
// ============================================================================
// Main Function
// ============================================================================
export async function generateUsageReport(options?: {
collectRemote?: boolean;
}): Promise<{
insights: InsightResults;
htmlPath: string;
data: AggregatedData;
remoteStats?: { hosts: RemoteHostInfo[]; totalCopied: number };
facets: Map<string, SessionFacets>;
}> {
let remoteStats: { hosts: RemoteHostInfo[]; totalCopied: number } | undefined;
// Optionally collect data from remote hosts first (ant-only)
if (process.env.USER_TYPE === "ant" && options?.collectRemote) {
const destDir = join(getClaudeConfigHomeDir(), "projects");
const { hosts, totalCopied } = await collectAllRemoteHostData(destDir);
remoteStats = { hosts, totalCopied };
}
// Phase 1: Lite scan — filesystem metadata only (no JSONL parsing)
const allScannedSessions = await scanAllSessions();
const totalSessionsScanned = allScannedSessions.length;
// Phase 2: Load SessionMeta — use cache where available, parse only uncached
// Read cached metas in parallel batches to avoid blocking the event loop
const META_BATCH_SIZE = 50;
const MAX_SESSIONS_TO_LOAD = 200;
let allMetas: SessionMeta[] = [];
const uncachedSessions: LiteSessionInfo[] = [];
for (let i = 0; i < allScannedSessions.length; i += META_BATCH_SIZE) {
const batch = allScannedSessions.slice(i, i + META_BATCH_SIZE);
const results = await Promise.all(
batch.map(async (sessionInfo) => ({
sessionInfo,
cached: await loadCachedSessionMeta(sessionInfo.sessionId),
})),
);
for (const { sessionInfo, cached } of results) {
if (cached) {
allMetas.push(cached);
} else if (uncachedSessions.length < MAX_SESSIONS_TO_LOAD) {
uncachedSessions.push(sessionInfo);
}
}
}
// Load full message data only for uncached sessions and compute SessionMeta
const logsForFacets = new Map<string, LogOption>();
// Filter out /insights meta-sessions (facet extraction API calls get logged as sessions)
const isMetaSession = (log: LogOption): boolean => {
for (const msg of log.messages.slice(0, 5)) {
if (msg.type === "user" && msg.message) {
const content = msg.message.content;
if (typeof content === "string") {
if (
content.includes("RESPOND WITH ONLY A VALID JSON OBJECT") ||
content.includes("record_facets")
) {
return true;
}
}
}
}
return false;
};
// Load uncached sessions in batches to yield to event loop between batches
const LOAD_BATCH_SIZE = 10;
for (let i = 0; i < uncachedSessions.length; i += LOAD_BATCH_SIZE) {
const batch = uncachedSessions.slice(i, i + LOAD_BATCH_SIZE);
const batchResults = await Promise.all(
batch.map(async (sessionInfo) => {
try {
return await loadAllLogsFromSessionFile(sessionInfo.path);
} catch {
return [];
}
}),
);
// Collect metas synchronously, then save them in parallel (independent writes)
const metasToSave: SessionMeta[] = [];
for (const logs of batchResults) {
for (const log of logs) {
if (isMetaSession(log) || !hasValidDates(log)) continue;
const meta = logToSessionMeta(log);
allMetas.push(meta);
metasToSave.push(meta);
// Keep the log around for potential facet extraction
logsForFacets.set(meta.session_id, log);
}
}
await Promise.all(metasToSave.map((meta) => saveSessionMeta(meta)));
}
// Deduplicate session branches (keep the one with most user messages per session_id)
// This prevents inflated totals when a session has multiple conversation branches
const bestBySession = new Map<string, SessionMeta>();
for (const meta of allMetas) {
const existing = bestBySession.get(meta.session_id);
if (
!existing ||
meta.user_message_count > existing.user_message_count ||
(meta.user_message_count === existing.user_message_count &&
meta.duration_minutes > existing.duration_minutes)
) {
bestBySession.set(meta.session_id, meta);
}
}
// Replace allMetas with deduplicated list and remove unused logs from logsForFacets
const keptSessionIds = new Set(bestBySession.keys());
allMetas = [...bestBySession.values()];
for (const sessionId of logsForFacets.keys()) {
if (!keptSessionIds.has(sessionId)) {
logsForFacets.delete(sessionId);
}
}
// Sort all metas by start_time descending (most recent first)
allMetas.sort((a, b) => b.start_time.localeCompare(a.start_time));
// Pre-filter obviously minimal sessions to save API calls
// (matching Python's substantive filtering concept)
const isSubstantiveSession = (meta: SessionMeta): boolean => {
// Skip sessions with very few user messages
if (meta.user_message_count < 2) return false;
// Skip very short sessions (< 1 minute)
if (meta.duration_minutes < 1) return false;
return true;
};
const substantiveMetas = allMetas.filter(isSubstantiveSession);
// Phase 3: Facet extraction — only for sessions without cached facets
const facets = new Map<string, SessionFacets>();
const toExtract: Array<{ log: LogOption; sessionId: string }> = [];
const MAX_FACET_EXTRACTIONS = 50;
// Load cached facets for all substantive sessions in parallel
const cachedFacetResults = await Promise.all(
substantiveMetas.map(async (meta) => ({
sessionId: meta.session_id,
cached: await loadCachedFacets(meta.session_id),
})),
);
for (const { sessionId, cached } of cachedFacetResults) {
if (cached) {
facets.set(sessionId, cached);
} else {
const log = logsForFacets.get(sessionId);
if (log && toExtract.length < MAX_FACET_EXTRACTIONS) {
toExtract.push({ log, sessionId });
}
}
}
// Extract facets for sessions that need them (50 concurrent)
const CONCURRENCY = 50;
for (let i = 0; i < toExtract.length; i += CONCURRENCY) {
const batch = toExtract.slice(i, i + CONCURRENCY);
const results = await Promise.all(
batch.map(async ({ log, sessionId }) => {
const newFacets = await extractFacetsFromAPI(log, sessionId);
return { sessionId, newFacets };
}),
);
// Collect facets synchronously, save in parallel (independent writes)
const facetsToSave: SessionFacets[] = [];
for (const { sessionId, newFacets } of results) {
if (newFacets) {
facets.set(sessionId, newFacets);
facetsToSave.push(newFacets);
}
}
await Promise.all(facetsToSave.map((f) => saveFacets(f)));
}
// Filter out warmup/minimal sessions (matching Python's is_minimal)
// A session is minimal if warmup_minimal is the ONLY goal category
const isMinimalSession = (sessionId: string): boolean => {
const sessionFacets = facets.get(sessionId);
if (!sessionFacets) return false;
const cats = sessionFacets.goal_categories;
const catKeys = safeKeys(cats).filter((k) => (cats[k] ?? 0) > 0);
return catKeys.length === 1 && catKeys[0] === "warmup_minimal";
};
const substantiveSessions = substantiveMetas.filter(
(s) => !isMinimalSession(s.session_id),
);
const substantiveFacets = new Map<string, SessionFacets>();
for (const [sessionId, f] of facets) {
if (!isMinimalSession(sessionId)) {
substantiveFacets.set(sessionId, f);
}
}
const aggregated = aggregateData(substantiveSessions, substantiveFacets);
aggregated.total_sessions_scanned = totalSessionsScanned;
// Generate parallel insights from Mervelas (6 sections)
const insights = await generateParallelInsights(aggregated, facets);
// Generate HTML report
const htmlReport = generateHtmlReport(aggregated, insights);
// Save reports
try {
await mkdir(getDataDir(), { recursive: true });
} catch {
// Directory may already exist
}
const htmlPath = join(getDataDir(), "report.html");
await writeFile(htmlPath, htmlReport, {
encoding: "utf-8",
mode: 0o600,
});
return {
insights,
htmlPath,
data: aggregated,
remoteStats,
facets: substantiveFacets,
};
}
function safeEntries<V>(
obj: Record<string, V> | undefined | null,
): [string, V][] {
return obj ? Object.entries(obj) : [];
}
function safeKeys(obj: Record<string, unknown> | undefined | null): string[] {
return obj ? Object.keys(obj) : [];
}
// ============================================================================
// Command Definition
// ============================================================================
const usageReport: Command = {
type: "prompt",
name: "insights",
description: "Generate a report analyzing your Mervelas sessions",
contentLength: 0, // Dynamic content
progressMessage: "analyzing your sessions",
source: "builtin",
async getPromptForCommand(args) {
let collectRemote = false;
let remoteHosts: string[] = [];
let hasRemoteHosts = false;
if (process.env.USER_TYPE === "ant") {
// Parse --homespaces flag
collectRemote = args?.includes("--homespaces") ?? false;
// Check for available remote hosts
remoteHosts = await getRunningRemoteHosts();
hasRemoteHosts = remoteHosts.length > 0;
// Show collection message if collecting
if (collectRemote && hasRemoteHosts) {
// biome-ignore lint/suspicious/noConsole: intentional
console.error(
`Collecting sessions from ${remoteHosts.length} homespace(s): ${remoteHosts.join(", ")}...`,
);
}
}
const { insights, htmlPath, data, remoteStats } = await generateUsageReport(
{ collectRemote },
);
let reportUrl = `file://${htmlPath}`;
let uploadHint = "";
if (process.env.USER_TYPE === "ant") {
// Try to upload to S3
const timestamp = new Date()
.toISOString()
.replace(/[-:]/g, "")
.replace("T", "_")
.slice(0, 15);
const username = process.env.SAFEUSER || process.env.USER || "unknown";
const filename = `${username}_insights_${timestamp}.html`;
const s3Path = `s3://anthropic-serve/atamkin/cc-user-reports/${filename}`;
const s3Url = `https://s3-frontend.infra.ant.dev/anthropic-serve/atamkin/cc-user-reports/${filename}`;
reportUrl = s3Url;
try {
execFileSync("ff", ["cp", htmlPath, s3Path], {
timeout: 60000,
stdio: "pipe", // Suppress output
});
} catch {
// Upload failed - fall back to local file and show upload command
reportUrl = `file://${htmlPath}`;
uploadHint = `\nAutomatic upload failed. Are you on the boron namespace? Try \`use-bo\` and ensure you've run \`sso\`.
To share, run: ff cp ${htmlPath} ${s3Path}
Then access at: ${s3Url}`;
}
}
// Build header with stats
const sessionLabel =
data.total_sessions_scanned &&
data.total_sessions_scanned > data.total_sessions
? `${data.total_sessions_scanned.toLocaleString()} sessions total · ${data.total_sessions} analyzed`
: `${data.total_sessions} sessions`;
const stats = [
sessionLabel,
`${data.total_messages.toLocaleString()} messages`,
`${Math.round(data.total_duration_hours)}h`,
`${data.git_commits} commits`,
].join(" · ");
// Build remote host info (ant-only)
let remoteInfo = "";
if (process.env.USER_TYPE === "ant") {
if (remoteStats && remoteStats.totalCopied > 0) {
const hsNames = remoteStats.hosts
.filter((h) => h.sessionCount > 0)
.map((h) => h.name)
.join(", ");
remoteInfo = `\n_Collected ${remoteStats.totalCopied} new sessions from: ${hsNames}_\n`;
} else if (!collectRemote && hasRemoteHosts) {
// Suggest using --homespaces if they have remote hosts but didn't use the flag
remoteInfo = `\n_Tip: Run \`/insights --homespaces\` to include sessions from your ${remoteHosts.length} running homespace(s)_\n`;
}
}
// Build markdown summary from insights
const atAGlance = insights.at_a_glance;
const summaryText = atAGlance
? `## At a Glance
${atAGlance.whats_working ? `**What's working:** ${atAGlance.whats_working} See _Impressive Things You Did_.` : ""}
${atAGlance.whats_hindering ? `**What's hindering you:** ${atAGlance.whats_hindering} See _Where Things Go Wrong_.` : ""}
${atAGlance.quick_wins ? `**Quick wins to try:** ${atAGlance.quick_wins} See _Features to Try_.` : ""}
${atAGlance.ambitious_workflows ? `**Ambitious workflows:** ${atAGlance.ambitious_workflows} See _On the Horizon_.` : ""}`
: "_No insights generated_";
const header = `# Mervelas Insights
${stats}
${data.date_range.start} to ${data.date_range.end}
${remoteInfo}
`;
const userSummary = `${header}${summaryText}
Your full shareable insights report is ready: ${reportUrl}${uploadHint}`;
// Return prompt for Mervelas to respond to
return [
{
type: "text",
text: `The user just ran /insights to generate a usage report analyzing their Mervelas sessions.
Here is the full insights data:
${jsonStringify(insights, null, 2)}
Report URL: ${reportUrl}
HTML file: ${htmlPath}
Facets directory: ${getFacetsDir()}
Here is what the user sees:
${userSummary}
Now output the following message exactly:
<message>
Your shareable insights report is ready:
${reportUrl}${uploadHint}
Want to dig into any section or try one of the suggestions?
</message>`,
},
];
},
};
function isValidSessionFacets(obj: unknown): obj is SessionFacets {
if (!obj || typeof obj !== "object") return false;
const o = obj as Record<string, unknown>;
return (
typeof o.underlying_goal === "string" &&
typeof o.outcome === "string" &&
typeof o.brief_summary === "string" &&
o.goal_categories !== null &&
typeof o.goal_categories === "object" &&
o.user_satisfaction_counts !== null &&
typeof o.user_satisfaction_counts === "object" &&
o.friction_counts !== null &&
typeof o.friction_counts === "object"
);
}
export default usageReport;