ai-session-search 1.0.0-rc.4

Local-first search, inspection, export, recovery, and MCP recall across supported AI coding-agent sessions.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
// SPDX-FileCopyrightText: 2026 Andrew Hundt
// SPDX-License-Identifier: Apache-2.0

use std::borrow::Cow;
use std::collections::BTreeMap;
use std::num::{NonZeroU32, NonZeroUsize};
use std::sync::atomic::{AtomicBool, Ordering as AtomicOrdering};

use chrono::{DateTime, Utc};
use nucleo_matcher::pattern::{AtomKind, CaseMatching, Normalization, Pattern};
use nucleo_matcher::{Config as NucleoConfig, Matcher as NucleoMatcher, Utf32Str};
use serde::ser::{SerializeMap, SerializeSeq};
use serde::{Deserialize, Serialize, Serializer};
use thiserror::Error;
use unicode_segmentation::UnicodeSegmentation;

use crate::hashing::FramedSha256;
use crate::models::{MessageKind, MessageSearchMode, Provider, Role, SearchField, SessionMeta};
use crate::refs::MessageRef;

pub const DEFAULT_MATCH_EVIDENCE_MAX_CHARS: usize = 220;
/// Version of the cross-surface structured message-search response contract.
///
/// This is intentionally independent of the SQLite schema version.
pub const MESSAGE_SEARCH_RESPONSE_SCHEMA_VERSION: u32 = 1;

#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum MessageSearchError {
    #[error("{kind} query must not be empty")]
    EmptyQuery { kind: &'static str },
    #[error("fuzzy query must contain at least 3 Unicode scalar values")]
    ShortFuzzyQuery,
    #[error("fuzzy query must contain a non-whitespace character")]
    BlankFuzzyQuery,
    #[error("invalid regex: {0}")]
    InvalidRegex(String),
    #[error("invalid RFC 6901 JSON pointer: {0}")]
    InvalidJsonPointer(String),
    #[error("{parameter}: {reason}")]
    InvalidParameter {
        parameter: &'static str,
        reason: String,
    },
    #[error("conflicting message-search parameters: {0}")]
    Conflict(String),
}

impl MessageSearchError {
    pub const fn code(&self) -> &'static str {
        match self {
            Self::EmptyQuery { .. }
            | Self::ShortFuzzyQuery
            | Self::BlankFuzzyQuery
            | Self::InvalidRegex(_) => "invalid-query",
            Self::InvalidJsonPointer(_) => "invalid-json-pointer",
            Self::InvalidParameter { .. } => "invalid-parameter",
            Self::Conflict(_) => "parameter-conflict",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct LiteralQuery(String);

impl LiteralQuery {
    pub fn new(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        nonempty_query(value, "literal").map(Self)
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct FuzzyQuery(String);

impl FuzzyQuery {
    pub fn new(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        let value = nonempty_query(value, "fuzzy")?;
        if value.trim().is_empty() {
            return Err(MessageSearchError::BlankFuzzyQuery);
        }
        if value.chars().take(3).count() < 3 {
            return Err(MessageSearchError::ShortFuzzyQuery);
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct ValidatedRegex(String);

impl ValidatedRegex {
    pub fn new(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        let value = nonempty_query(value, "regex")?;
        regex::Regex::new(&value)
            .map_err(|error| MessageSearchError::InvalidRegex(error.to_string()))?;
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

fn nonempty_query(
    value: impl Into<String>,
    kind: &'static str,
) -> Result<String, MessageSearchError> {
    let value = value.into();
    if value.is_empty() {
        return Err(MessageSearchError::EmptyQuery { kind });
    }
    Ok(value)
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(tag = "mode", content = "query", rename_all = "kebab-case")]
pub enum MessageQuery {
    All,
    Literal(LiteralQuery),
    Regex(ValidatedRegex),
    Fuzzy(FuzzyQuery),
}

impl MessageQuery {
    pub fn literal(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        LiteralQuery::new(value).map(Self::Literal)
    }

    pub fn regex(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        ValidatedRegex::new(value).map(Self::Regex)
    }

    pub fn fuzzy(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        FuzzyQuery::new(value).map(Self::Fuzzy)
    }

    pub fn text(&self) -> Option<&str> {
        match self {
            Self::All => None,
            Self::Literal(value) => Some(value.as_str()),
            Self::Regex(value) => Some(value.as_str()),
            Self::Fuzzy(value) => Some(value.as_str()),
        }
    }

    pub const fn mode(&self) -> Option<MessageSearchMode> {
        match self {
            Self::All => None,
            Self::Literal(_) => Some(MessageSearchMode::Literal),
            Self::Regex(_) => Some(MessageSearchMode::Regex),
            Self::Fuzzy(_) => Some(MessageSearchMode::Fuzzy),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
pub struct JsonPointer(String);

impl JsonPointer {
    pub fn new(value: impl Into<String>) -> Result<Self, MessageSearchError> {
        let value = value.into();
        if !value.is_empty() && !value.starts_with('/') {
            return Err(MessageSearchError::InvalidJsonPointer(
                "a nonempty pointer must start with '/'".into(),
            ));
        }
        let bytes = value.as_bytes();
        let mut index = 0;
        while index < bytes.len() {
            if bytes[index] == b'~' {
                if !matches!(bytes.get(index + 1), Some(b'0' | b'1')) {
                    return Err(MessageSearchError::InvalidJsonPointer(
                        "'~' must be followed by '0' or '1'".into(),
                    ));
                }
                index += 1;
            }
            index += 1;
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct MessageTarget {
    field: SearchField,
    argument_path: Option<JsonPointer>,
}

impl MessageTarget {
    pub const fn content() -> Self {
        Self {
            field: SearchField::Content,
            argument_path: None,
        }
    }

    pub const fn tool_name() -> Self {
        Self {
            field: SearchField::ToolName,
            argument_path: None,
        }
    }

    pub fn tool_argument(path: impl Into<String>) -> Result<Self, MessageSearchError> {
        Ok(Self {
            field: SearchField::ToolArgument,
            argument_path: Some(JsonPointer::new(path)?),
        })
    }

    pub const fn field(&self) -> SearchField {
        self.field
    }

    pub fn argument_path(&self) -> Option<&JsonPointer> {
        self.argument_path.as_ref()
    }
}

#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum,
)]
#[serde(rename_all = "kebab-case")]
pub enum MatchWindow {
    #[default]
    Earliest,
    Latest,
}

#[derive(
    Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum,
)]
#[serde(rename_all = "kebab-case")]
pub enum ReceiptLevel {
    #[default]
    None,
    Summary,
    Full,
}

/// Preset for the amount of one selected message value returned to a caller.
///
/// This changes presentation only. Result membership, ordering, context, includes, and receipts
/// are controlled independently.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum DetailLevel {
    Compact,
    Full,
}

/// Character budget for the boundary/full-value view of one selected message field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum FieldViewBudget {
    NoCharLimit,
    MaxChars { max_chars: NonZeroUsize },
}

impl FieldViewBudget {
    pub fn max_chars(max_chars: usize) -> Result<Self, MessageSearchError> {
        NonZeroUsize::new(max_chars)
            .map(|max_chars| Self::MaxChars { max_chars })
            .ok_or_else(|| MessageSearchError::InvalidParameter {
                parameter: "field_view",
                reason: "max_chars must be a positive character count; use kind=no_char_limit to apply no additional character limit after line selection".into(),
            })
    }
}

/// Character budget for the independently match-centered view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum MatchViewBudget {
    MinimalSpan,
    MaxChars { max_chars: NonZeroUsize },
}

/// Optional payload groups added to the stable message-search semantic core.
///
/// Context and receipt metadata intentionally are not include groups: their dedicated parameters
/// remain the single owners of those payloads.
#[derive(
    Debug,
    Clone,
    Copy,
    PartialEq,
    Eq,
    PartialOrd,
    Ord,
    Hash,
    Serialize,
    Deserialize,
    clap::ValueEnum,
)]
#[serde(rename_all = "snake_case")]
#[clap(rename_all = "snake_case")]
pub enum MessageSearchInclude {
    NormalizedSessionMetadata,
    ParsedReferences,
    RawProviderMetadata,
    RuntimeDiagnostics,
}

impl MatchViewBudget {
    pub fn max_chars(max_chars: usize) -> Result<Self, MessageSearchError> {
        NonZeroUsize::new(max_chars)
            .map(|max_chars| Self::MaxChars { max_chars })
            .ok_or_else(|| MessageSearchError::InvalidParameter {
                parameter: "match_view",
                reason: "max_chars must be a positive character count; use kind=minimal_span for only the match span".into(),
            })
    }
}

fn decode_view_max_chars(
    object: &serde_json::Map<String, serde_json::Value>,
    parameter: &str,
    maximum: usize,
) -> Result<usize, MessageSearchError> {
    let raw = object
        .get("max_chars")
        .ok_or_else(|| MessageSearchError::InvalidParameter {
            parameter: "view_budget",
            reason: format!("{parameter}.max_chars is required when kind=max_chars"),
        })?;
    let raw = raw
        .as_u64()
        .ok_or_else(|| MessageSearchError::InvalidParameter {
            parameter: "view_budget",
            reason: format!("{parameter}.max_chars must be a positive integer"),
        })?;
    let value = usize::try_from(raw).map_err(|_| MessageSearchError::InvalidParameter {
        parameter: "view_budget",
        reason: format!("{parameter}.max_chars exceeds this platform's supported integer range"),
    })?;
    if value == 0 || value > maximum {
        return Err(MessageSearchError::InvalidParameter {
            parameter: "view_budget",
            reason: format!(
                "{parameter}.max_chars must be an integer from 1 through {maximum}; got {value}"
            ),
        });
    }
    Ok(value)
}

fn reject_view_unknown_fields(
    object: &serde_json::Map<String, serde_json::Value>,
    parameter: &str,
    accepts_max_chars: bool,
) -> Result<(), MessageSearchError> {
    if let Some(key) = object
        .keys()
        .find(|key| *key != "kind" && !(accepts_max_chars && *key == "max_chars"))
    {
        return Err(MessageSearchError::InvalidParameter {
            parameter: "view_budget",
            reason: format!(
                "{parameter} contains unknown field {key:?}; accepted fields are {}",
                if accepts_max_chars {
                    "kind and max_chars"
                } else {
                    "kind"
                }
            ),
        });
    }
    Ok(())
}

/// Decode the object-shaped field-view contract shared by MCP and Python adapters.
pub fn decode_field_view_budget(
    value: &serde_json::Value,
    maximum: usize,
) -> Result<FieldViewBudget, MessageSearchError> {
    let object = value
        .as_object()
        .ok_or_else(|| MessageSearchError::InvalidParameter {
            parameter: "field_view",
            reason: "must be an object with a kind field".into(),
        })?;
    match object.get("kind").and_then(serde_json::Value::as_str) {
        Some("no_char_limit") => {
            reject_view_unknown_fields(object, "field_view", false)?;
            Ok(FieldViewBudget::NoCharLimit)
        }
        Some("max_chars") => {
            reject_view_unknown_fields(object, "field_view", true)?;
            FieldViewBudget::max_chars(decode_view_max_chars(object, "field_view", maximum)?)
        }
        Some(other) => Err(MessageSearchError::InvalidParameter {
            parameter: "field_view",
            reason: format!("kind must be no_char_limit or max_chars; got {other:?}"),
        }),
        None => Err(MessageSearchError::InvalidParameter {
            parameter: "field_view",
            reason: "kind is required".into(),
        }),
    }
}

/// Decode the object-shaped match-view contract shared by MCP and Python adapters.
pub fn decode_match_view_budget(
    value: &serde_json::Value,
    maximum: usize,
) -> Result<MatchViewBudget, MessageSearchError> {
    let object = value
        .as_object()
        .ok_or_else(|| MessageSearchError::InvalidParameter {
            parameter: "match_view",
            reason: "must be an object with a kind field".into(),
        })?;
    match object.get("kind").and_then(serde_json::Value::as_str) {
        Some("minimal_span") => {
            reject_view_unknown_fields(object, "match_view", false)?;
            Ok(MatchViewBudget::MinimalSpan)
        }
        Some("max_chars") => {
            reject_view_unknown_fields(object, "match_view", true)?;
            MatchViewBudget::max_chars(decode_view_max_chars(object, "match_view", maximum)?)
        }
        Some(other) => Err(MessageSearchError::InvalidParameter {
            parameter: "match_view",
            reason: format!("kind must be minimal_span or max_chars; got {other:?}"),
        }),
        None => Err(MessageSearchError::InvalidParameter {
            parameter: "match_view",
            reason: "kind is required".into(),
        }),
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ContextWindow {
    messages_before: usize,
    messages_after: usize,
}

impl ContextWindow {
    pub const fn new(messages_before: usize, messages_after: usize) -> Self {
        Self {
            messages_before,
            messages_after,
        }
    }

    pub const fn symmetric(count: usize) -> Self {
        Self::new(count, count)
    }

    pub const fn messages_before(self) -> usize {
        self.messages_before
    }

    pub const fn messages_after(self) -> usize {
        self.messages_after
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LineWindow {
    #[default]
    Full,
    Head(NonZeroUsize),
    Tail(NonZeroUsize),
}

impl LineWindow {
    pub fn from_signed(value: i64) -> Result<Self, MessageSearchError> {
        match value.cmp(&0) {
            std::cmp::Ordering::Equal => Ok(Self::Full),
            std::cmp::Ordering::Greater => usize::try_from(value)
                .ok()
                .and_then(NonZeroUsize::new)
                .map(Self::Head)
                .ok_or_else(|| MessageSearchError::InvalidParameter {
                    parameter: "lines_per_message",
                    reason: "positive value exceeds usize".into(),
                }),
            std::cmp::Ordering::Less => value
                .checked_abs()
                .and_then(|absolute| usize::try_from(absolute).ok())
                .and_then(NonZeroUsize::new)
                .map(Self::Tail)
                .ok_or_else(|| MessageSearchError::InvalidParameter {
                    parameter: "lines_per_message",
                    reason: "negative magnitude exceeds usize".into(),
                }),
        }
    }

    pub fn to_signed(self) -> Result<i64, MessageSearchError> {
        match self {
            Self::Full => Ok(0),
            Self::Head(lines) => {
                i64::try_from(lines.get()).map_err(|_| MessageSearchError::InvalidParameter {
                    parameter: "lines_per_message",
                    reason: "head line count exceeds i64".into(),
                })
            }
            Self::Tail(lines) => i64::try_from(lines.get()).map(|value| -value).map_err(|_| {
                MessageSearchError::InvalidParameter {
                    parameter: "lines_per_message",
                    reason: "tail line count exceeds i64".into(),
                }
            }),
        }
    }
}

/// Requested message-hit extent before surface defaults are resolved.
///
/// `Page { limit: None, .. }` deliberately has surface-specific meaning: Rust, CLI, and Python
/// resolve it to all literal, regex, or no-text matches, while MCP resolves it to its configured
/// finite page. Fuzzy search always requires a finite resolved page. `AllResults` is the explicit
/// cross-surface override and is never silently converted into a page.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
pub enum RequestedExtent {
    Page {
        limit: Option<NonZeroUsize>,
        offset: usize,
    },
    AllResults {
        offset: usize,
    },
}

impl Default for RequestedExtent {
    fn default() -> Self {
        Self::Page {
            limit: None,
            offset: 0,
        }
    }
}

impl RequestedExtent {
    pub fn page(limit: Option<usize>, offset: usize) -> Result<Self, MessageSearchError> {
        let limit = match limit {
            Some(0) => {
                return Err(MessageSearchError::InvalidParameter {
                    parameter: "limit",
                    reason: "use all_results instead of zero".into(),
                })
            }
            Some(value) => NonZeroUsize::new(value),
            None => None,
        };
        Ok(Self::Page { limit, offset })
    }

    pub const fn all_results() -> Self {
        Self::AllResults { offset: 0 }
    }

    pub const fn all_results_from(offset: usize) -> Self {
        Self::AllResults { offset }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
#[serde(transparent)]
struct NonEmptyValue(String);

impl NonEmptyValue {
    pub fn new(
        parameter: &'static str,
        value: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        let value = value.into();
        if value.is_empty() {
            return Err(MessageSearchError::InvalidParameter {
                parameter,
                reason: "must not be empty".into(),
            });
        }
        Ok(Self(value))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
pub struct SequenceRange {
    from: Option<i64>,
    to: Option<i64>,
}

impl SequenceRange {
    pub fn new(from: Option<i64>, to: Option<i64>) -> Result<Self, MessageSearchError> {
        if from.is_some_and(|value| value < 0) || to.is_some_and(|value| value < 0) {
            return Err(MessageSearchError::InvalidParameter {
                parameter: "sequence",
                reason: "bounds must be nonnegative".into(),
            });
        }
        if let (Some(from), Some(to)) = (from, to) {
            if from > to {
                return Err(MessageSearchError::InvalidParameter {
                    parameter: "sequence",
                    reason: format!("seq_from {from} exceeds seq_to {to}"),
                });
            }
        }
        Ok(Self { from, to })
    }

    pub const fn from(&self) -> Option<i64> {
        self.from
    }

    pub const fn to(&self) -> Option<i64> {
        self.to
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize)]
pub struct RequestedTimeRange {
    since: Option<DateTime<Utc>>,
    until: Option<DateTime<Utc>>,
}

impl RequestedTimeRange {
    pub fn new(
        since: Option<DateTime<Utc>>,
        until: Option<DateTime<Utc>>,
    ) -> Result<Self, MessageSearchError> {
        if let (Some(since), Some(until)) = (since, until) {
            if since > until {
                return Err(MessageSearchError::InvalidParameter {
                    parameter: "time",
                    reason: "since must not be later than until".into(),
                });
            }
        }
        Ok(Self { since, until })
    }

    pub const fn since(&self) -> Option<DateTime<Utc>> {
        self.since
    }

    pub const fn until(&self) -> Option<DateTime<Utc>> {
        self.until
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct MessagePredicates {
    role: Option<Role>,
    kinds: Option<Vec<MessageKind>>,
    providers: Option<Vec<Provider>>,
    session: Option<NonEmptyValue>,
    workspace_path_prefix: Option<NonEmptyValue>,
    transcript_path_prefix: Option<NonEmptyValue>,
    exclude_workspace_path_prefixes: Vec<NonEmptyValue>,
    exclude_transcript_path_prefixes: Vec<NonEmptyValue>,
    exclude_session_ids: Vec<NonEmptyValue>,
    time: RequestedTimeRange,
    sequence: Option<SequenceRange>,
    tool_name_contains: Option<NonEmptyValue>,
    include_compaction: bool,
}

impl Default for MessagePredicates {
    fn default() -> Self {
        Self {
            role: None,
            kinds: None,
            providers: None,
            session: None,
            workspace_path_prefix: None,
            transcript_path_prefix: None,
            exclude_workspace_path_prefixes: Vec::new(),
            exclude_transcript_path_prefixes: Vec::new(),
            exclude_session_ids: Vec::new(),
            time: RequestedTimeRange::default(),
            sequence: None,
            tool_name_contains: None,
            include_compaction: true,
        }
    }
}

impl MessagePredicates {
    pub const fn role(&self) -> Option<Role> {
        self.role
    }

    pub fn kinds(&self) -> Option<&[MessageKind]> {
        self.kinds.as_deref()
    }

    /// Selected session sources in canonical identifier order, or `None` for every source.
    pub fn providers(&self) -> Option<&[Provider]> {
        self.providers.as_deref()
    }

    pub fn session(&self) -> Option<&str> {
        self.session.as_ref().map(NonEmptyValue::as_str)
    }

    pub fn workspace_path_prefix(&self) -> Option<&str> {
        self.workspace_path_prefix
            .as_ref()
            .map(NonEmptyValue::as_str)
    }

    pub fn transcript_path_prefix(&self) -> Option<&str> {
        self.transcript_path_prefix
            .as_ref()
            .map(NonEmptyValue::as_str)
    }

    pub fn exclude_workspace_path_prefixes(&self) -> impl Iterator<Item = &str> {
        self.exclude_workspace_path_prefixes
            .iter()
            .map(NonEmptyValue::as_str)
    }

    pub fn exclude_transcript_path_prefixes(&self) -> impl Iterator<Item = &str> {
        self.exclude_transcript_path_prefixes
            .iter()
            .map(NonEmptyValue::as_str)
    }

    pub fn exclude_session_ids(&self) -> impl Iterator<Item = &str> {
        self.exclude_session_ids.iter().map(NonEmptyValue::as_str)
    }

    pub const fn time(&self) -> RequestedTimeRange {
        self.time
    }

    pub const fn sequence(&self) -> Option<SequenceRange> {
        self.sequence
    }

    pub fn tool_name_contains(&self) -> Option<&str> {
        self.tool_name_contains.as_ref().map(NonEmptyValue::as_str)
    }

    pub const fn include_compaction(&self) -> bool {
        self.include_compaction
    }
}

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct MessagePresentation {
    message_lines: Option<LineWindow>,
    detail: Option<DetailLevel>,
    field_view: Option<FieldViewBudget>,
    match_view: Option<MatchViewBudget>,
}

impl MessagePresentation {
    pub const fn message_lines(&self) -> Option<LineWindow> {
        self.message_lines
    }

    pub const fn detail(&self) -> Option<DetailLevel> {
        self.detail
    }

    pub const fn field_view(&self) -> Option<FieldViewBudget> {
        self.field_view
    }

    pub const fn match_view(&self) -> Option<MatchViewBudget> {
        self.match_view
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct PurposeSelection {
    name: NonEmptyValue,
    version: Option<NonZeroU32>,
}

impl PurposeSelection {
    pub fn new(
        name: impl Into<String>,
        version: Option<NonZeroU32>,
    ) -> Result<Self, MessageSearchError> {
        let name = NonEmptyValue::new("purpose", name)?;
        if !is_dash_separated_phrase(name.as_str()) {
            return Err(MessageSearchError::InvalidParameter {
                parameter: "purpose",
                reason: "must be a lowercase dash-separated phrase".into(),
            });
        }
        Ok(Self { name, version })
    }

    pub fn name(&self) -> &str {
        self.name.as_str()
    }

    pub const fn version(&self) -> Option<NonZeroU32> {
        self.version
    }
}

pub(crate) fn is_dash_separated_phrase(value: &str) -> bool {
    !value.is_empty()
        && value
            .split('-')
            .all(|part| !part.is_empty() && part.chars().all(|ch| ch.is_ascii_lowercase()))
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum SearchSurface {
    Rust,
    Cli,
    Mcp,
    Python,
}

impl SearchSurface {
    pub const ALL: &'static [Self] = &[Self::Rust, Self::Cli, Self::Mcp, Self::Python];
}

/// Stable conceptual identity for one message-search input.
///
/// Adapters may project a concept into idiomatic syntax, but they must not create a second
/// semantic owner.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageSearchParameter {
    Query,
    QueryMode,
    Field,
    ArgumentPath,
    Role,
    Kinds,
    Providers,
    SessionId,
    WorkspacePathPrefix,
    TranscriptPathPrefix,
    ExcludeWorkspacePathPrefixes,
    ExcludeTranscriptPathPrefixes,
    ExcludeSessionIds,
    Since,
    Until,
    Sequence,
    ToolNameContains,
    IncludeCompaction,
    MatchWindow,
    Context,
    ResultExtent,
    Detail,
    LinesPerMessage,
    FieldView,
    MatchView,
    Purpose,
    ReceiptLevel,
    Include,
}

impl MessageSearchParameter {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Query => "query",
            Self::QueryMode => "query_mode",
            Self::Field => "field",
            Self::ArgumentPath => "argument_path",
            Self::Role => "role",
            Self::Kinds => "kinds",
            Self::Providers => "providers",
            Self::SessionId => "session_id",
            Self::WorkspacePathPrefix => "workspace_path_prefix",
            Self::TranscriptPathPrefix => "transcript_path_prefix",
            Self::ExcludeWorkspacePathPrefixes => "exclude_workspace_path_prefixes",
            Self::ExcludeTranscriptPathPrefixes => "exclude_transcript_path_prefixes",
            Self::ExcludeSessionIds => "exclude_session_ids",
            Self::Since => "since",
            Self::Until => "until",
            Self::Sequence => "sequence",
            Self::ToolNameContains => "tool_name_contains",
            Self::IncludeCompaction => "include_compaction",
            Self::MatchWindow => "match_window",
            Self::Context => "context",
            Self::ResultExtent => "result_extent",
            Self::Detail => "detail",
            Self::LinesPerMessage => "lines_per_message",
            Self::FieldView => "field_view",
            Self::MatchView => "match_view",
            Self::Purpose => "purpose",
            Self::ReceiptLevel => "receipt_level",
            Self::Include => "include",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum MessageSearchObjectFieldDomain {
    PositiveCharacterCount,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchObjectFieldSpec {
    name: &'static str,
    required: bool,
    domain: MessageSearchObjectFieldDomain,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchObjectVariantSpec {
    value: &'static str,
    selects: &'static str,
    fields: Vec<MessageSearchObjectFieldSpec>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum MessageSearchParameterDomain {
    Text {
        non_empty: bool,
    },
    Boolean,
    Enum {
        accepted_values: Vec<String>,
    },
    NonEmptySet {
        accepted_values: Vec<String>,
    },
    NonNegativeCount,
    SignedEdgeCount,
    TimeBound,
    SequenceRange,
    ContextWindow,
    ResultExtent,
    FieldView {
        discriminator: &'static str,
        accepted_variants: Vec<MessageSearchObjectVariantSpec>,
    },
    MatchView {
        discriminator: &'static str,
        accepted_variants: Vec<MessageSearchObjectVariantSpec>,
    },
    PurposeSelection,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageSearchOmission {
    AllEligible,
    TypedDefault,
    SurfacePolicy,
    NoAdditionalFilter,
    QuerylessSearch,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchParameterSpec {
    parameter: MessageSearchParameter,
    selects: &'static str,
    domain: MessageSearchParameterDomain,
    omission: MessageSearchOmission,
    surfaces: &'static [SearchSurface],
}

impl MessageSearchParameterSpec {
    pub const fn parameter(&self) -> MessageSearchParameter {
        self.parameter
    }

    pub const fn selects(&self) -> &'static str {
        self.selects
    }

    pub const fn domain(&self) -> &MessageSearchParameterDomain {
        &self.domain
    }

    pub const fn omission(&self) -> MessageSearchOmission {
        self.omission
    }

    pub const fn surfaces(&self) -> &'static [SearchSurface] {
        self.surfaces
    }

    pub fn accepted_values(&self) -> &[String] {
        match &self.domain {
            MessageSearchParameterDomain::Enum { accepted_values }
            | MessageSearchParameterDomain::NonEmptySet { accepted_values } => accepted_values,
            _ => &[],
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ValueOriginKind {
    Explicit,
    DetailPreset,
    Purpose,
    OperationConfig,
    SurfaceConfig,
    TypedDefault,
    Derived,
}

/// Executable cross-parameter rule identity shared by request validation and caller specifications.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MessageSearchRule {
    DetailOwnsPresentationBudgets,
    SequenceRequiresSession,
    KindsMustRemainSatisfiable,
    CompactionRoleRequiresCompactionKind,
    ToolArgumentRequiresToolCallKind,
    MatchViewRequiresQuery,
    FuzzyRejectsMatchWindow,
    LatestWindowRequiresSession,
    FuzzyRejectsAllResults,
}

impl MessageSearchRule {
    pub const ALL: &'static [Self] = &[
        Self::DetailOwnsPresentationBudgets,
        Self::SequenceRequiresSession,
        Self::KindsMustRemainSatisfiable,
        Self::CompactionRoleRequiresCompactionKind,
        Self::ToolArgumentRequiresToolCallKind,
        Self::MatchViewRequiresQuery,
        Self::FuzzyRejectsMatchWindow,
        Self::LatestWindowRequiresSession,
        Self::FuzzyRejectsAllResults,
    ];

    pub const fn as_str(self) -> &'static str {
        match self {
            Self::DetailOwnsPresentationBudgets => "detail_owns_presentation_budgets",
            Self::SequenceRequiresSession => "sequence_requires_session",
            Self::KindsMustRemainSatisfiable => "kinds_must_remain_satisfiable",
            Self::CompactionRoleRequiresCompactionKind => {
                "compaction_role_requires_compaction_kind"
            }
            Self::ToolArgumentRequiresToolCallKind => "tool_argument_requires_tool_call_kind",
            Self::MatchViewRequiresQuery => "match_view_requires_query",
            Self::FuzzyRejectsMatchWindow => "fuzzy_rejects_match_window",
            Self::LatestWindowRequiresSession => "latest_window_requires_session",
            Self::FuzzyRejectsAllResults => "fuzzy_rejects_all_results",
        }
    }

    pub const fn message(self) -> &'static str {
        match self {
            Self::DetailOwnsPresentationBudgets => {
                "detail conflicts with lines_per_message, field_view, and match_view; omit detail to compose custom presentation budgets"
            }
            Self::SequenceRequiresSession => "sequence bounds require one session",
            Self::KindsMustRemainSatisfiable => {
                "the selected kinds exclude every message class, so nothing can match"
            }
            Self::CompactionRoleRequiresCompactionKind => {
                "role=compaction requires compaction among the selected kinds; include_compaction=false or a kinds set without it removes every match"
            }
            Self::ToolArgumentRequiresToolCallKind => {
                "tool-argument target requires tool_call among the selected kinds"
            }
            Self::MatchViewRequiresQuery => {
                "match_view requires a literal, regex, or fuzzy query"
            }
            Self::FuzzyRejectsMatchWindow => "match_window does not apply to fuzzy queries",
            Self::LatestWindowRequiresSession => "match_window=latest requires one session",
            Self::FuzzyRejectsAllResults => "fuzzy search does not support all_results",
        }
    }

    fn error(self) -> MessageSearchError {
        MessageSearchError::Conflict(format!("{}: {}", self.as_str(), self.message()))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct MessageSearchRuleDescriptor {
    rule: MessageSearchRule,
    message: &'static str,
}

impl MessageSearchRuleDescriptor {
    const fn new(rule: MessageSearchRule) -> Self {
        Self {
            rule,
            message: rule.message(),
        }
    }

    pub const fn rule(self) -> MessageSearchRule {
        self.rule
    }

    pub const fn message(self) -> &'static str {
        self.message
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchParameterRegistry {
    purpose: &'static str,
    parameters: Vec<MessageSearchParameterSpec>,
    precedence: &'static [ValueOriginKind],
    #[serde(skip)]
    rules: &'static [MessageSearchRule],
    #[serde(rename = "rules")]
    rule_descriptors: Vec<MessageSearchRuleDescriptor>,
}

impl MessageSearchParameterRegistry {
    /// Return the process-wide immutable input catalogue.
    ///
    /// Construction is `O(P + V)` time and memory for bounded parameter and vocabulary counts and
    /// occurs once per process. Search calls never clone or attach this catalogue to responses.
    pub fn current() -> &'static Self {
        static REGISTRY: std::sync::OnceLock<MessageSearchParameterRegistry> =
            std::sync::OnceLock::new();
        REGISTRY.get_or_init(Self::build)
    }

    pub const fn purpose(&self) -> &'static str {
        self.purpose
    }

    pub fn parameters(&self) -> &[MessageSearchParameterSpec] {
        &self.parameters
    }

    pub fn parameter(
        &self,
        parameter: MessageSearchParameter,
    ) -> Option<&MessageSearchParameterSpec> {
        self.parameters
            .iter()
            .find(|candidate| candidate.parameter == parameter)
    }

    pub const fn precedence(&self) -> &'static [ValueOriginKind] {
        self.precedence
    }

    pub const fn rules(&self) -> &'static [MessageSearchRule] {
        self.rules
    }

    pub fn rule_descriptors(&self) -> &[MessageSearchRuleDescriptor] {
        &self.rule_descriptors
    }

    fn build() -> Self {
        fn serialized_variants<T>() -> Vec<String>
        where
            T: clap::ValueEnum + Copy + Serialize + 'static,
        {
            T::value_variants()
                .iter()
                .map(|value| {
                    serde_json::to_value(*value)
                        .expect("message-search enum serializes")
                        .as_str()
                        .expect("message-search enum serializes as a string")
                        .to_owned()
                })
                .collect()
        }

        let enum_domain = |accepted_values| MessageSearchParameterDomain::Enum { accepted_values };
        let set_domain =
            |accepted_values| MessageSearchParameterDomain::NonEmptySet { accepted_values };
        let max_chars_field = || MessageSearchObjectFieldSpec {
            name: "max_chars",
            required: true,
            domain: MessageSearchObjectFieldDomain::PositiveCharacterCount,
        };
        let parameter = |parameter, selects, domain, omission| MessageSearchParameterSpec {
            parameter,
            selects,
            domain,
            omission,
            surfaces: SearchSurface::ALL,
        };
        let parameters = vec![
            parameter(
                MessageSearchParameter::Query,
                "Text to match.",
                MessageSearchParameterDomain::Text { non_empty: false },
                MessageSearchOmission::QuerylessSearch,
            ),
            parameter(
                MessageSearchParameter::QueryMode,
                "How query is matched.",
                enum_domain(serialized_variants::<MessageSearchMode>()),
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::Field,
                "Which field to match.",
                enum_domain(serialized_variants::<SearchField>()),
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::ArgumentPath,
                "RFC 6901 pointer into tool arguments; needs field=tool_argument",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::Role,
                "Author role.",
                enum_domain(serialized_variants::<Role>()),
                MessageSearchOmission::AllEligible,
            ),
            parameter(
                MessageSearchParameter::Kinds,
                "Message classes to return.",
                set_domain(serialized_variants::<MessageKind>()),
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::Providers,
                "Session sources.",
                set_domain(
                    crate::source::PROVIDERS
                        .iter()
                        .map(|provider| provider.as_str().to_owned())
                        .collect(),
                ),
                MessageSearchOmission::AllEligible,
            ),
            parameter(
                MessageSearchParameter::SessionId,
                "One session by ID or prefix.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::AllEligible,
            ),
            parameter(
                MessageSearchParameter::WorkspacePathPrefix,
                "Match cwd or repo-root prefix.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::AllEligible,
            ),
            parameter(
                MessageSearchParameter::TranscriptPathPrefix,
                "Match transcript-path prefix.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::AllEligible,
            ),
            parameter(
                MessageSearchParameter::ExcludeWorkspacePathPrefixes,
                "Excluded cwd/repo-root prefixes.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::ExcludeTranscriptPathPrefixes,
                "Excluded transcript prefixes.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::ExcludeSessionIds,
                "Excluded session IDs.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::Since,
                "Lower time bound.",
                MessageSearchParameterDomain::TimeBound,
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::Until,
                "Upper time bound.",
                MessageSearchParameterDomain::TimeBound,
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::Sequence,
                "Sequence bound.",
                MessageSearchParameterDomain::SequenceRange,
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::ToolNameContains,
                "Substring in the tool name.",
                MessageSearchParameterDomain::Text { non_empty: true },
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::IncludeCompaction,
                "Keep compaction summaries.",
                MessageSearchParameterDomain::Boolean,
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::MatchWindow,
                "First N matches in session order, or last N of one session.",
                enum_domain(serialized_variants::<MatchWindow>()),
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::Context,
                "Neighbours each side per hit.",
                MessageSearchParameterDomain::ContextWindow,
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::ResultExtent,
                "Page size.",
                MessageSearchParameterDomain::ResultExtent,
                MessageSearchOmission::SurfacePolicy,
            ),
            parameter(
                MessageSearchParameter::Detail,
                "Presentation preset.",
                enum_domain(serialized_variants::<DetailLevel>()),
                MessageSearchOmission::SurfacePolicy,
            ),
            parameter(
                MessageSearchParameter::LinesPerMessage,
                "Line window.",
                MessageSearchParameterDomain::SignedEdgeCount,
                MessageSearchOmission::SurfacePolicy,
            ),
            parameter(
                MessageSearchParameter::FieldView,
                "Character budget for the field.",
                MessageSearchParameterDomain::FieldView {
                    discriminator: "kind",
                    accepted_variants: vec![
                        MessageSearchObjectVariantSpec {
                            value: "no_char_limit",
                            selects: "No additional character limit after line selection.",
                            fields: vec![],
                        },
                        MessageSearchObjectVariantSpec {
                            value: "max_chars",
                            selects: "At most max_chars Unicode-scalar characters from the field boundary.",
                            fields: vec![max_chars_field()],
                        },
                    ],
                },
                MessageSearchOmission::SurfacePolicy,
            ),
            parameter(
                MessageSearchParameter::MatchView,
                "Character budget around the match.",
                MessageSearchParameterDomain::MatchView {
                    discriminator: "kind",
                    accepted_variants: vec![
                        MessageSearchObjectVariantSpec {
                            value: "minimal_span",
                            selects: "Only the complete selected match span.",
                            fields: vec![],
                        },
                        MessageSearchObjectVariantSpec {
                            value: "max_chars",
                            selects: "Up to max_chars Unicode-scalar characters centered on the complete match.",
                            fields: vec![max_chars_field()],
                        },
                    ],
                },
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::Purpose,
                "Configured preference bundle.",
                MessageSearchParameterDomain::PurposeSelection,
                MessageSearchOmission::NoAdditionalFilter,
            ),
            parameter(
                MessageSearchParameter::ReceiptLevel,
                "Diagnostics.",
                enum_domain(serialized_variants::<ReceiptLevel>()),
                MessageSearchOmission::TypedDefault,
            ),
            parameter(
                MessageSearchParameter::Include,
                "Payload groups; a supplied set replaces the default",
                set_domain(serialized_variants::<MessageSearchInclude>()),
                MessageSearchOmission::TypedDefault,
            ),
        ];
        Self {
            purpose: "Search indexed AI-session messages while separating result selection, context, presentation, optional payloads, and receipts.",
            parameters,
            precedence: &[
                ValueOriginKind::Explicit,
                ValueOriginKind::DetailPreset,
                ValueOriginKind::Purpose,
                ValueOriginKind::OperationConfig,
                ValueOriginKind::SurfaceConfig,
                ValueOriginKind::TypedDefault,
                ValueOriginKind::Derived,
            ],
            rules: MessageSearchRule::ALL,
            rule_descriptors: MessageSearchRule::ALL
                .iter()
                .copied()
                .map(MessageSearchRuleDescriptor::new)
                .collect(),
        }
    }
}

/// Static caller catalogue plus the real planner's configured default semantic request.
///
/// The registry is borrowed from the process-wide cache. The configured request is produced by
/// [`crate::service::MessageService::plan`], so this DTO cannot drift into a second precedence
/// resolver. Construction is independent of indexed result count and message bytes.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchSpecification {
    registry: &'static MessageSearchParameterRegistry,
    configured_default: ResolvedMessageSearchRequest,
}

impl MessageSearchSpecification {
    pub(crate) fn new(configured_default: ResolvedMessageSearchRequest) -> Self {
        Self {
            registry: MessageSearchParameterRegistry::current(),
            configured_default,
        }
    }

    pub const fn registry(&self) -> &'static MessageSearchParameterRegistry {
        self.registry
    }

    pub const fn configured_default(&self) -> &ResolvedMessageSearchRequest {
        &self.configured_default
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "source", rename_all = "kebab-case")]
pub enum ValueOrigin {
    Explicit,
    DetailPreset { detail: DetailLevel },
    Purpose { name: String, version: NonZeroU32 },
    SurfaceConfig { surface: SearchSurface },
    OperationConfig,
    TypedDefault,
    Derived,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageSearchOrigins {
    pub(crate) result_extent: ValueOrigin,
    pub(crate) context_messages_before: ValueOrigin,
    pub(crate) context_messages_after: ValueOrigin,
    pub(crate) includes: ValueOrigin,
    pub(crate) detail: ValueOrigin,
    pub(crate) lines_per_message: ValueOrigin,
    pub(crate) field_view: ValueOrigin,
    pub(crate) match_view: ValueOrigin,
    pub(crate) receipt_level: ValueOrigin,
    pub(crate) result_order: ValueOrigin,
}

impl MessageSearchOrigins {
    pub fn result_extent(&self) -> &ValueOrigin {
        &self.result_extent
    }

    pub fn context_messages_before(&self) -> &ValueOrigin {
        &self.context_messages_before
    }

    pub fn context_messages_after(&self) -> &ValueOrigin {
        &self.context_messages_after
    }

    pub fn includes(&self) -> &ValueOrigin {
        &self.includes
    }

    pub fn detail(&self) -> &ValueOrigin {
        &self.detail
    }

    pub fn lines_per_message(&self) -> &ValueOrigin {
        &self.lines_per_message
    }

    pub fn field_view(&self) -> &ValueOrigin {
        &self.field_view
    }

    pub fn match_view(&self) -> &ValueOrigin {
        &self.match_view
    }

    pub fn receipt_level(&self) -> &ValueOrigin {
        &self.receipt_level
    }

    pub fn result_order(&self) -> &ValueOrigin {
        &self.result_order
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum ExecutionOrder {
    SessionSequence,
    FuzzyRelevance,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize)]
pub enum ResolvedExtent {
    Page { limit: NonZeroUsize, offset: usize },
    AllResults { offset: usize },
}

#[derive(Debug, Clone)]
pub(crate) struct ResolvedMessagePredicates {
    pub(crate) role: Option<Role>,
    pub(crate) kinds: Option<Vec<MessageKind>>,
    pub(crate) providers: Option<Vec<Provider>>,
    pub(crate) session_id: Option<String>,
    pub(crate) workspace_path_prefix: Option<String>,
    pub(crate) transcript_path_prefix: Option<String>,
    pub(crate) exclude_workspace_path_prefixes: Vec<String>,
    pub(crate) exclude_transcript_path_prefixes: Vec<String>,
    pub(crate) exclude_session_ids: Vec<String>,
    pub(crate) time: RequestedTimeRange,
    pub(crate) sequence: Option<SequenceRange>,
    pub(crate) tool_name_contains: Option<String>,
    pub(crate) include_compaction: bool,
}

#[derive(Debug, Clone)]
pub(crate) struct MessageRetrievalPlan {
    pub(crate) query: MessageQuery,
    pub(crate) target: MessageTarget,
    pub(crate) predicates: ResolvedMessagePredicates,
    pub(crate) match_window: Option<MatchWindow>,
    pub(crate) ordering: ExecutionOrder,
    pub(crate) extent: ResolvedExtent,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ResolvedMessagePresentation {
    pub(crate) include_refs: bool,
    pub(crate) message_lines: LineWindow,
    pub(crate) match_evidence_max_chars: NonZeroUsize,
    pub(crate) detail: Option<DetailLevel>,
    pub(crate) field_view: FieldViewBudget,
    pub(crate) match_view: MatchViewBudget,
}

impl ResolvedMessagePresentation {
    pub const fn include_refs(&self) -> bool {
        self.include_refs
    }

    pub const fn message_lines(&self) -> LineWindow {
        self.message_lines
    }

    pub const fn match_evidence_max_chars(&self) -> NonZeroUsize {
        self.match_evidence_max_chars
    }

    pub const fn detail(&self) -> Option<DetailLevel> {
        self.detail
    }

    pub const fn field_view(&self) -> FieldViewBudget {
        self.field_view
    }

    pub const fn match_view(&self) -> MatchViewBudget {
        self.match_view
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub(crate) struct MessageResponsePlan {
    pub(crate) context: ContextWindow,
    pub(crate) presentation: ResolvedMessagePresentation,
    pub(crate) includes: Vec<MessageSearchInclude>,
}

#[derive(Debug, Clone)]
pub struct MessageSearchPlan {
    pub(crate) retrieval: MessageRetrievalPlan,
    pub(crate) response: MessageResponsePlan,
    pub(crate) receipt: ReceiptLevel,
    pub(crate) origins: MessageSearchOrigins,
}

impl MessageSearchPlan {
    pub const fn ordering(&self) -> ExecutionOrder {
        self.retrieval.ordering
    }

    pub const fn extent(&self) -> ResolvedExtent {
        self.retrieval.extent
    }

    pub const fn context(&self) -> ContextWindow {
        self.response.context
    }

    pub const fn presentation(&self) -> ResolvedMessagePresentation {
        self.response.presentation
    }

    pub fn includes(&self) -> &[MessageSearchInclude] {
        &self.response.includes
    }

    pub const fn receipt_level(&self) -> ReceiptLevel {
        self.receipt
    }

    pub fn origins(&self) -> &MessageSearchOrigins {
        &self.origins
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ProviderScope {
    All,
    Selected { providers: Vec<Provider> },
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ResolvedRequestExtent {
    Page { limit: NonZeroUsize, offset: usize },
    AllResults { offset: usize },
}

impl From<ResolvedExtent> for ResolvedRequestExtent {
    fn from(value: ResolvedExtent) -> Self {
        match value {
            ResolvedExtent::Page { limit, offset } => Self::Page { limit, offset },
            ResolvedExtent::AllResults { offset } => Self::AllResults { offset },
        }
    }
}

/// Public query-mode vocabulary shared by CLI, Python, MCP, and response documents.
///
/// Public query-mode vocabulary shared by all search surfaces.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResolvedQueryMode {
    Literal,
    Regex,
    Fuzzy,
}

impl From<MessageSearchMode> for ResolvedQueryMode {
    fn from(value: MessageSearchMode) -> Self {
        match value {
            MessageSearchMode::Literal => Self::Literal,
            MessageSearchMode::Regex => Self::Regex,
            MessageSearchMode::Fuzzy => Self::Fuzzy,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolvedRequestPresentation {
    lines_per_message: i64,
    field_view: FieldViewBudget,
    match_view: MatchViewBudget,
}

impl ResolvedRequestPresentation {
    pub const fn lines_per_message(&self) -> i64 {
        self.lines_per_message
    }

    pub const fn field_view(&self) -> FieldViewBudget {
        self.field_view
    }

    pub const fn match_view(&self) -> MatchViewBudget {
        self.match_view
    }
}

/// Effective semantic choices returned with every response.
///
/// Parameter origins and planner evidence are optional receipt data; this compact record is always
/// present so a caller can interpret result and presentation extent without conversational state.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ResolvedMessageSearchRequest {
    #[serde(skip_serializing_if = "Option::is_none")]
    query: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    query_mode: Option<ResolvedQueryMode>,
    target: MessageTarget,
    provider_scope: ProviderScope,
    extent: ResolvedRequestExtent,
    #[serde(skip_serializing_if = "Option::is_none")]
    match_window: Option<MatchWindow>,
    context: ContextWindow,
    presentation: ResolvedRequestPresentation,
    include: Vec<MessageSearchInclude>,
    receipt_level: ReceiptLevel,
}

impl ResolvedMessageSearchRequest {
    pub(crate) fn from_plan(plan: &MessageSearchPlan) -> Result<Self, MessageSearchError> {
        Ok(Self {
            query: plan.retrieval.query.text().map(str::to_owned),
            query_mode: plan.retrieval.query.mode().map(ResolvedQueryMode::from),
            target: plan.retrieval.target.clone(),
            provider_scope: plan
                .retrieval
                .predicates
                .providers
                .clone()
                .map_or(ProviderScope::All, |providers| ProviderScope::Selected {
                    providers,
                }),
            extent: plan.retrieval.extent.into(),
            match_window: (!matches!(plan.retrieval.query, MessageQuery::Fuzzy(_)))
                .then_some(plan.retrieval.match_window.unwrap_or_default()),
            context: plan.response.context,
            presentation: ResolvedRequestPresentation {
                lines_per_message: plan.response.presentation.message_lines.to_signed()?,
                field_view: plan.response.presentation.field_view,
                match_view: plan.response.presentation.match_view,
            },
            include: plan.response.includes.clone(),
            receipt_level: plan.receipt,
        })
    }

    pub fn query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    pub const fn query_mode(&self) -> Option<ResolvedQueryMode> {
        self.query_mode
    }

    pub const fn target(&self) -> &MessageTarget {
        &self.target
    }

    pub const fn provider_scope(&self) -> &ProviderScope {
        &self.provider_scope
    }

    pub const fn extent(&self) -> ResolvedRequestExtent {
        self.extent
    }

    pub const fn match_window(&self) -> Option<MatchWindow> {
        self.match_window
    }

    pub const fn context(&self) -> ContextWindow {
        self.context
    }

    pub const fn presentation(&self) -> &ResolvedRequestPresentation {
        &self.presentation
    }

    pub fn include(&self) -> &[MessageSearchInclude] {
        &self.include
    }

    pub const fn receipt_level(&self) -> ReceiptLevel {
        self.receipt_level
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct PageInfo {
    extent: ResolvedExtent,
    returned: usize,
    next_offset: Option<usize>,
    ordering: ExecutionOrder,
    earlier_results: PageSide,
    result_set_extent: ResultSetExtent,
}

impl PageInfo {
    pub(crate) const fn new(
        extent: ResolvedExtent,
        returned: usize,
        next_offset: Option<usize>,
        ordering: ExecutionOrder,
    ) -> Self {
        let offset = match extent {
            ResolvedExtent::Page { offset, .. } | ResolvedExtent::AllResults { offset } => offset,
        };
        let earlier_results = if offset == 0 {
            PageSide::None
        } else if returned > 0 {
            // A nonempty page after an offset proves that matching rows were skipped.
            PageSide::Present
        } else {
            // A positive offset alone does not distinguish no matches from a beyond-end page.
            PageSide::Unknown
        };
        let result_set_extent = match (earlier_results, next_offset.is_some()) {
            (PageSide::Present, _) | (_, true) => ResultSetExtent::Partial,
            (PageSide::None, false) => ResultSetExtent::All,
            _ => ResultSetExtent::Unknown,
        };
        Self {
            extent,
            returned,
            next_offset,
            ordering,
            earlier_results,
            result_set_extent,
        }
    }

    pub const fn extent(&self) -> ResolvedExtent {
        self.extent
    }

    pub const fn next_offset(&self) -> Option<usize> {
        self.next_offset
    }

    pub const fn ordering(&self) -> ExecutionOrder {
        self.ordering
    }

    pub const fn returned(&self) -> usize {
        self.returned
    }

    pub const fn earlier_results(&self) -> PageSide {
        self.earlier_results
    }

    pub const fn result_set_extent(&self) -> ResultSetExtent {
        self.result_set_extent
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PageSide {
    None,
    Present,
    Unknown,
}

impl PageSide {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Present => "present",
            Self::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ResultSetExtent {
    All,
    Partial,
    Unknown,
}

impl ResultSetExtent {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::All => "all",
            Self::Partial => "partial",
            Self::Unknown => "unknown",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct ViewCharRange {
    pub view_start_char: usize,
    pub view_end_char_exclusive: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "kebab-case")]
pub enum MessageMatchViewMarkers {
    Characters {
        ranges: Vec<ViewCharRange>,
        matched_chars_total: usize,
        matched_chars_shown: usize,
    },
    Boundary {
        view_at_char: usize,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageMatchEvidence {
    pub view_text: String,
    pub field_start_char: usize,
    pub field_total_chars: usize,
    pub markers: MessageMatchViewMarkers,
}

/// Complete selected-field occurrence for literal mode.
///
/// The independently bounded evidence excerpt can omit part of a long literal. This record keeps
/// the exact matched field text and absolute character coordinates without expanding regex or
/// fuzzy evidence.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageLiteralMatch {
    pub text: String,
    pub field_start_char: usize,
    pub field_end_char_exclusive: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct FieldCharRange {
    field_start_char: usize,
    field_end_char_exclusive: usize,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum CoordinateUnit {
    UnicodeScalar,
}

/// Which portion of the selected field is present in one returned view.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum AdditionalFieldText {
    None,
    Before,
    After,
    BeforeAndAfter,
}

impl AdditionalFieldText {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Before => "before",
            Self::After => "after",
            Self::BeforeAndAfter => "before_and_after",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct FieldViewExtent {
    additional_field_text: AdditionalFieldText,
    /// Full selected-field Unicode scalar count, or `None` when computing it would require an
    /// additional full-field scan solely for metadata.
    ///
    /// Deliberately per view rather than hoisted with the unit beside it. The two views are
    /// filled by different code paths -- `evidence_field_view` always knows the count while
    /// `selected_field_view` computes an `Option` -- so one can be `null` while the other is
    /// populated for the same result. Collapsing them would either invent a value or drop one,
    /// which `REQ046-preserve-boundary-results` names as silently dropping optional data.
    field_total_chars: Option<usize>,
    /// Not serialized: `CoordinateUnit` has a single variant, so this was the same constant
    /// written three times per result. It is stated once at the response root instead.
    #[serde(skip)]
    coordinate_unit: CoordinateUnit,
}

impl FieldViewExtent {
    pub const fn additional_field_text(&self) -> AdditionalFieldText {
        self.additional_field_text
    }

    pub const fn field_total_chars(&self) -> Option<usize> {
        self.field_total_chars
    }
}

/// Absolute Unicode-scalar range and remaining-text direction for returned message content.
///
/// The range length equals the returned `content` character count. `field_total_chars` stays
/// optional when obtaining it would require another full-field scan solely for metadata.
/// Completeness and both boundary conditions are derivable without parallel booleans:
/// `additional_field_text == none` means the range contains the complete field.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct MessageContentExtent {
    field_start_char: usize,
    field_end_char_exclusive: usize,
    #[serde(flatten)]
    extent: FieldViewExtent,
    /// Kept here, unlike the search response's views, because this shape is serialized into
    /// `get_session`, a different document with no shared root to hoist to. It also appears once
    /// per returned message rather than three times per result, so the repetition the search
    /// response had is not there to remove.
    coordinate_unit: CoordinateUnit,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct MessageFieldView {
    text: String,
    field_start_char: usize,
    field_end_char_exclusive: usize,
    #[serde(skip_serializing_if = "Vec::is_empty")]
    markers: Vec<ViewCharRange>,
    #[serde(flatten)]
    extent: FieldViewExtent,
}

impl MessageFieldView {
    pub fn text(&self) -> &str {
        &self.text
    }

    pub const fn field_start_char(&self) -> usize {
        self.field_start_char
    }

    pub const fn field_end_char_exclusive(&self) -> usize {
        self.field_end_char_exclusive
    }

    pub fn markers(&self) -> &[ViewCharRange] {
        &self.markers
    }

    pub const fn extent(&self) -> FieldViewExtent {
        self.extent
    }

    pub(crate) fn into_content_and_extent(self) -> (String, MessageContentExtent) {
        (
            self.text,
            MessageContentExtent {
                field_start_char: self.field_start_char,
                field_end_char_exclusive: self.field_end_char_exclusive,
                extent: self.extent,
                coordinate_unit: CoordinateUnit::UnicodeScalar,
            },
        )
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct MessageResultRef<'a> {
    session_id: &'a str,
    message_seq: i64,
}

impl<'a> MessageResultRef<'a> {
    pub const fn session_id(self) -> &'a str {
        self.session_id
    }

    pub const fn message_seq(self) -> i64 {
        self.message_seq
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct MessageSearchHit {
    #[serde(flatten)]
    pub message: crate::models::MessageHit,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub match_evidence: Option<MessageMatchEvidence>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub literal_match: Option<MessageLiteralMatch>,
    #[serde(skip_serializing)]
    field_view: Option<MessageFieldView>,
    #[serde(skip_serializing)]
    match_view: Option<MessageFieldView>,
    #[serde(skip_serializing)]
    parsed_references: Option<Vec<MessageRef>>,
}

impl MessageSearchHit {
    #[cfg(test)]
    pub(crate) fn from_parts(
        message: crate::models::MessageHit,
        match_evidence: Option<MessageMatchEvidence>,
        literal_match: Option<MessageLiteralMatch>,
    ) -> Self {
        let field_view = complete_field_view(&message.content);
        let match_view = match_evidence.as_ref().map(evidence_field_view);
        Self {
            message,
            match_evidence,
            literal_match,
            field_view: Some(field_view),
            match_view,
            parsed_references: None,
        }
    }

    pub fn message(&self) -> &crate::models::MessageHit {
        &self.message
    }

    pub fn match_evidence(&self) -> Option<&MessageMatchEvidence> {
        self.match_evidence.as_ref()
    }

    pub fn literal_match(&self) -> Option<&MessageLiteralMatch> {
        self.literal_match.as_ref()
    }

    pub fn message_ref(&self) -> MessageResultRef<'_> {
        MessageResultRef {
            session_id: &self.message.session_id,
            message_seq: self.message.seq,
        }
    }

    pub const fn field_view(&self) -> &MessageFieldView {
        self.field_view
            .as_ref()
            .expect("message presentation must be applied before returning search results")
    }

    pub fn match_view(&self) -> Option<&MessageFieldView> {
        self.match_view.as_ref()
    }

    pub fn parsed_references(&self) -> Option<&[MessageRef]> {
        self.parsed_references.as_deref()
    }

    pub(crate) fn set_parsed_references(&mut self, references: Vec<MessageRef>) {
        self.parsed_references = Some(references);
    }
}

impl std::ops::Deref for MessageSearchHit {
    type Target = crate::models::MessageHit;

    fn deref(&self) -> &Self::Target {
        &self.message
    }
}

#[derive(Debug, Clone)]
pub struct MessageSearchResponse {
    request: ResolvedMessageSearchRequest,
    query: Option<String>,
    match_target: Option<MessageTarget>,
    match_mode: Option<MessageSearchMode>,
    hits: Vec<MessageSearchHit>,
    context_windows: Vec<Vec<crate::models::MessageHit>>,
    page: PageInfo,
    context: ContextWindow,
    presentation: ResolvedMessagePresentation,
    includes: Vec<MessageSearchInclude>,
    planner: Option<crate::models::SearchExplain>,
    origins: Option<MessageSearchOrigins>,
    included: MessageSearchIncludedData,
}

#[derive(Debug, Clone, Serialize)]
pub struct MessageSearchRuntimeDiagnostics {
    package_version: &'static str,
    database_schema_version: i64,
    response_schema_version: u32,
    surface: SearchSurface,
    config_digest: String,
}

impl MessageSearchRuntimeDiagnostics {
    pub(crate) fn new(surface: SearchSurface, config_digest: String) -> Self {
        Self {
            package_version: env!("CARGO_PKG_VERSION"),
            database_schema_version: crate::db::SCHEMA_VERSION,
            response_schema_version: MESSAGE_SEARCH_RESPONSE_SCHEMA_VERSION,
            surface,
            config_digest,
        }
    }

    pub const fn package_version(&self) -> &'static str {
        self.package_version
    }

    pub const fn database_schema_version(&self) -> i64 {
        self.database_schema_version
    }

    pub const fn response_schema_version(&self) -> u32 {
        self.response_schema_version
    }

    pub const fn surface(&self) -> SearchSurface {
        self.surface
    }

    pub fn config_digest(&self) -> &str {
        &self.config_digest
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct MessageSearchIncludedData {
    #[serde(skip_serializing_if = "Option::is_none")]
    normalized_session_metadata: Option<BTreeMap<String, SessionMeta>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    raw_provider_metadata: Option<BTreeMap<String, Box<serde_json::value::RawValue>>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    runtime_diagnostics: Option<MessageSearchRuntimeDiagnostics>,
}

impl MessageSearchIncludedData {
    pub(crate) fn new(
        normalized_session_metadata: Option<BTreeMap<String, SessionMeta>>,
        raw_provider_metadata: Option<BTreeMap<String, Box<serde_json::value::RawValue>>>,
        runtime_diagnostics: Option<MessageSearchRuntimeDiagnostics>,
    ) -> Self {
        Self {
            normalized_session_metadata,
            raw_provider_metadata,
            runtime_diagnostics,
        }
    }

    pub(crate) fn is_empty(&self) -> bool {
        self.normalized_session_metadata.is_none()
            && self.raw_provider_metadata.is_none()
            && self.runtime_diagnostics.is_none()
    }

    pub fn normalized_session_metadata(&self) -> Option<&BTreeMap<String, SessionMeta>> {
        self.normalized_session_metadata.as_ref()
    }

    pub fn raw_provider_metadata(
        &self,
    ) -> Option<&BTreeMap<String, Box<serde_json::value::RawValue>>> {
        self.raw_provider_metadata.as_ref()
    }

    pub const fn runtime_diagnostics(&self) -> Option<&MessageSearchRuntimeDiagnostics> {
        self.runtime_diagnostics.as_ref()
    }
}

pub(crate) struct MessageSearchResponseParts {
    pub request: ResolvedMessageSearchRequest,
    pub match_details: Option<(MessageTarget, MessageSearchMode)>,
    pub hits: Vec<MessageSearchHit>,
    pub context_windows: Vec<Vec<crate::models::MessageHit>>,
    pub page: PageInfo,
    pub response: MessageResponsePlan,
    pub planner: Option<crate::models::SearchExplain>,
    pub origins: Option<MessageSearchOrigins>,
    pub included: MessageSearchIncludedData,
}

impl MessageSearchResponse {
    pub(crate) fn new(parts: MessageSearchResponseParts) -> Self {
        let MessageSearchResponseParts {
            request,
            match_details,
            hits,
            context_windows,
            page,
            response,
            planner,
            origins,
            included,
        } = parts;
        let (match_target, match_mode) = match match_details {
            Some((target, mode)) => (Some(target), Some(mode)),
            None => (None, None),
        };
        Self {
            request,
            query: None,
            match_target,
            match_mode,
            hits,
            context_windows,
            page,
            context: response.context,
            presentation: response.presentation,
            includes: response.includes,
            planner,
            origins,
            included,
        }
    }

    pub(crate) fn with_query(mut self, query: Option<String>) -> Self {
        self.query = query;
        self
    }

    pub fn query(&self) -> Option<&str> {
        self.query.as_deref()
    }

    pub const fn request(&self) -> &ResolvedMessageSearchRequest {
        &self.request
    }

    pub fn hits(&self) -> &[MessageSearchHit] {
        &self.hits
    }

    /// Finalized semantic result records. `hits()` remains as the Rust compatibility spelling
    /// while adapters migrate; both access the same allocation and ordered identities.
    pub fn results(&self) -> &[MessageSearchHit] {
        &self.hits
    }

    pub fn into_hits(self) -> Vec<MessageSearchHit> {
        self.hits
    }

    /// Consume returned rows without cloning their potentially large content strings.
    pub fn into_rows(self) -> (Vec<MessageSearchHit>, Vec<Vec<crate::models::MessageHit>>) {
        (self.hits, self.context_windows)
    }

    pub fn match_target(&self) -> Option<&MessageTarget> {
        self.match_target.as_ref()
    }

    pub const fn match_mode(&self) -> Option<MessageSearchMode> {
        self.match_mode
    }

    /// Context windows aligned by index with [`MessageSearchResponse::hits`]. Empty when the
    /// resolved context is zero on both sides.
    pub fn context_windows(&self) -> &[Vec<crate::models::MessageHit>] {
        &self.context_windows
    }

    pub const fn page(&self) -> PageInfo {
        self.page
    }

    pub const fn context(&self) -> ContextWindow {
        self.context
    }

    pub const fn presentation(&self) -> ResolvedMessagePresentation {
        self.presentation
    }

    pub fn includes(&self) -> &[MessageSearchInclude] {
        &self.includes
    }

    pub fn search_explanation(&self) -> Option<&crate::models::SearchExplain> {
        self.planner.as_ref()
    }

    pub fn parameter_origins(&self) -> Option<&MessageSearchOrigins> {
        self.origins.as_ref()
    }

    pub const fn included(&self) -> &MessageSearchIncludedData {
        &self.included
    }

    pub fn has_included_data(&self) -> bool {
        !self.included.is_empty()
    }

    /// Borrow the finalized cross-surface version-1 semantic document without cloning hit text.
    pub const fn document(&self) -> MessageSearchDocument<'_> {
        MessageSearchDocument {
            response: self,
            cancellation: None,
        }
    }

    /// Borrow the canonical document with cooperative cancellation between encoded results.
    ///
    /// Let `H` be returned results and `P` their encoded bytes. Successful serialization remains
    /// `O(H + P)` time with `O(P)` destination memory. Cancellation is observed in `O(1)` at every
    /// result boundary and during an optional ordered-digest pass; one result is the maximum
    /// non-interruptible unit because serializers receive each string value atomically.
    pub const fn document_cancellable<'a>(
        &'a self,
        cancellation: &'a AtomicBool,
    ) -> MessageSearchDocument<'a> {
        MessageSearchDocument {
            response: self,
            cancellation: Some(cancellation),
        }
    }

    /// Borrow one canonical result for incremental encoders such as CLI JSON Lines.
    ///
    /// Serialization is `O(result bytes)` time and retains no second result tree.
    pub fn result_document(&self, index: usize) -> Option<MessageSearchResultDocument<'_>> {
        self.hits.get(index).map(|hit| MessageSearchResultDocument {
            hit,
            target: Some(self.request.target()),
            context: self.context_windows.get(index).map(Vec::as_slice),
            presentation: self.presentation,
        })
    }

    /// Borrow canonical page metadata for incremental encoders.
    pub const fn page_document(&self) -> MessageSearchPageDocument {
        MessageSearchPageDocument(self.page)
    }

    /// Borrow the requested receipt without cloning response data.
    ///
    /// The ordered digest is computed only for a full receipt, matching [`MessageSearchDocument`].
    pub fn receipt_document(&self) -> Option<MessageSearchReceiptDocument<'_>> {
        (self.request.receipt_level != ReceiptLevel::None).then(|| MessageSearchReceiptDocument {
            search_explanation: self.planner.as_ref(),
            parameter_origins: self.origins.as_ref(),
            ordered_digest: (self.request.receipt_level == ReceiptLevel::Full)
                .then(|| self.ordered_digest()),
        })
    }

    /// Digest ordered semantic result identities, excluding presentation and output encoding.
    ///
    /// Let `H` be returned hits and `I` their identity/target bytes. Time is `O(H + I)` and
    /// retained memory is `O(1)` beyond the SHA-256 state and final string.
    pub fn ordered_digest(&self) -> String {
        self.ordered_digest_cancellable(None)
            .expect("uncancelled digest construction cannot fail")
    }

    fn ordered_digest_cancellable(
        &self,
        cancellation: Option<&AtomicBool>,
    ) -> Result<String, &'static str> {
        let mut digest =
            MessageSearchOrderedDigest::new(self.request.target().clone(), self.match_mode);
        for hit in &self.hits {
            ensure_message_search_serialization_active(cancellation)?;
            digest.update(hit);
        }
        ensure_message_search_serialization_active(cancellation)?;
        Ok(digest.finish())
    }
}

/// Incremental owner of the canonical ordered-result digest used by materialized and streamed
/// responses. Presentation, batch size, context, includes, and encoding never enter this digest.
pub(crate) struct MessageSearchOrderedDigest {
    digest: FramedSha256,
    target: MessageTarget,
    match_mode: Option<MessageSearchMode>,
}

impl MessageSearchOrderedDigest {
    pub(crate) fn new(target: MessageTarget, match_mode: Option<MessageSearchMode>) -> Self {
        let digest = FramedSha256::new(b"aise-message-search-ordered-digest-v1");
        Self {
            digest,
            target,
            match_mode,
        }
    }

    /// Add one already-enriched semantic result in `O(identity + target-path bytes)` time and
    /// `O(1)` retained state.
    pub(crate) fn update(&mut self, hit: &MessageSearchHit) {
        self.digest.update_bytes(hit.message.session_id.as_bytes());
        self.digest.update_i64(hit.message.seq);
        self.digest.update_u8(match self.target.field() {
            SearchField::Content => 0,
            SearchField::ToolName => 1,
            SearchField::ToolArgument => 2,
        });
        if let Some(path) = self.target.argument_path() {
            self.digest.update_u8(1);
            self.digest.update_bytes(path.as_str().as_bytes());
        } else {
            self.digest.update_u8(0);
        }
        self.digest.update_u8(match self.match_mode {
            Some(MessageSearchMode::Literal) => 0,
            Some(MessageSearchMode::Regex) => 1,
            Some(MessageSearchMode::Fuzzy) => 2,
            None => 255,
        });
        if let Some(score) = hit.message.fuzzy_score {
            self.digest.update_u8(1);
            self.digest.update_u32(score);
        } else {
            self.digest.update_u8(0);
        }
        if let Some(literal) = hit.literal_match.as_ref() {
            self.digest.update_u8(1);
            self.digest.update_u64(literal.field_start_char as u64);
            self.digest
                .update_u64(literal.field_end_char_exclusive as u64);
        } else {
            self.digest.update_u8(0);
        }
    }

    pub(crate) fn finish(self) -> String {
        self.digest.finish()
    }
}

impl Serialize for MessageSearchResponse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.document().serialize(serializer)
    }
}

/// Canonical structured response projection. CLI JSON, JSONL framing, MCP structured content, and
/// schema fixtures must derive from this owner rather than rebuilding response facts.
#[derive(Debug, Clone, Copy)]
pub struct MessageSearchDocument<'a> {
    response: &'a MessageSearchResponse,
    cancellation: Option<&'a AtomicBool>,
}

impl Serialize for MessageSearchDocument<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::Error as _;

        ensure_message_search_serialization_active(self.cancellation).map_err(S::Error::custom)?;
        let receipt_level = self.response.request.receipt_level;
        let mut entry_count = 5;
        if receipt_level != ReceiptLevel::None {
            entry_count += 1;
        }
        if !self.response.included.is_empty() {
            entry_count += 1;
        }
        let mut map = serializer.serialize_map(Some(entry_count))?;
        map.serialize_entry(
            "response_schema_version",
            &MESSAGE_SEARCH_RESPONSE_SCHEMA_VERSION,
        )?;
        // Every character offset in this document is in this unit. It used to be repeated at
        // three sites per result, always the same constant, because `CoordinateUnit` has one
        // variant. `REQ006-report-extent-honestly` requires the response to state it; stating it
        // once satisfies that and costs 34 characters instead of 34 times three times the page.
        map.serialize_entry("coordinate_unit", &CoordinateUnit::UnicodeScalar)?;
        map.serialize_entry("effective_request", &self.response.request)?;
        map.serialize_entry(
            "results",
            &SemanticResults {
                hits: &self.response.hits,
                target: Some(self.response.request.target()),
                context_windows: &self.response.context_windows,
                presentation: self.response.presentation,
                cancellation: self.cancellation,
            },
        )?;
        ensure_message_search_serialization_active(self.cancellation).map_err(S::Error::custom)?;
        map.serialize_entry("page", &self.response.page_document())?;
        if !self.response.included.is_empty() {
            ensure_message_search_serialization_active(self.cancellation)
                .map_err(S::Error::custom)?;
            map.serialize_entry("included", &self.response.included)?;
        }
        if receipt_level != ReceiptLevel::None {
            ensure_message_search_serialization_active(self.cancellation)
                .map_err(S::Error::custom)?;
            let ordered_digest = if receipt_level == ReceiptLevel::Full {
                Some(
                    self.response
                        .ordered_digest_cancellable(self.cancellation)
                        .map_err(S::Error::custom)?,
                )
            } else {
                None
            };
            map.serialize_entry(
                "receipt",
                &MessageSearchReceiptDocument {
                    search_explanation: self.response.planner.as_ref(),
                    parameter_origins: self.response.origins.as_ref(),
                    ordered_digest,
                },
            )?;
        }
        ensure_message_search_serialization_active(self.cancellation).map_err(S::Error::custom)?;
        map.end()
    }
}

/// Borrowed canonical result projection for incremental output encoders.
#[derive(Debug, Clone, Copy)]
pub struct MessageSearchResultDocument<'a> {
    hit: &'a MessageSearchHit,
    target: Option<&'a MessageTarget>,
    context: Option<&'a [crate::models::MessageHit]>,
    presentation: ResolvedMessagePresentation,
}

impl<'a> MessageSearchResultDocument<'a> {
    pub(crate) fn from_batch_parts(
        hit: &'a MessageSearchHit,
        request: &'a ResolvedMessageSearchRequest,
        context: Option<&'a [crate::models::MessageHit]>,
    ) -> Self {
        let resolved = request.presentation();
        Self {
            hit,
            target: Some(request.target()),
            context,
            presentation: ResolvedMessagePresentation {
                include_refs: request
                    .include()
                    .contains(&MessageSearchInclude::ParsedReferences),
                message_lines: LineWindow::from_signed(resolved.lines_per_message())
                    .expect("resolved request contains a validated line window"),
                match_evidence_max_chars: NonZeroUsize::new(DEFAULT_MATCH_EVIDENCE_MAX_CHARS)
                    .expect("typed default is positive"),
                detail: None,
                field_view: resolved.field_view(),
                match_view: resolved.match_view(),
            },
        }
    }
}

impl Serialize for MessageSearchResultDocument<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        SemanticResult {
            hit: self.hit,
            target: self.target,
            context: self.context,
            presentation: self.presentation,
        }
        .serialize(serializer)
    }
}

/// Borrowed canonical result-page projection for incremental output encoders.
#[derive(Debug, Clone, Copy)]
pub struct MessageSearchPageDocument(PageInfo);

impl MessageSearchPageDocument {
    pub(crate) const fn from_page(page: PageInfo) -> Self {
        Self(page)
    }
}

impl Serialize for MessageSearchPageDocument {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        SemanticPageFields::from(self.0).serialize(serializer)
    }
}

/// Borrowed canonical optional receipt for incremental output encoders.
#[derive(Debug)]
pub struct MessageSearchReceiptDocument<'a> {
    search_explanation: Option<&'a crate::models::SearchExplain>,
    parameter_origins: Option<&'a MessageSearchOrigins>,
    ordered_digest: Option<String>,
}

impl<'a> MessageSearchReceiptDocument<'a> {
    pub(crate) fn from_parts(
        receipt_level: ReceiptLevel,
        search_explanation: Option<&'a crate::models::SearchExplain>,
        parameter_origins: Option<&'a MessageSearchOrigins>,
        ordered_digest: Option<&'a str>,
    ) -> Option<Self> {
        (receipt_level != ReceiptLevel::None).then_some(Self {
            search_explanation,
            parameter_origins,
            ordered_digest: (receipt_level == ReceiptLevel::Full)
                .then_some(ordered_digest)
                .flatten()
                .map(str::to_owned),
        })
    }
}

impl Serialize for MessageSearchReceiptDocument<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        SemanticReceipt {
            search_explanation: self.search_explanation,
            parameter_origins: self.parameter_origins,
            ordered_digest: self.ordered_digest.clone(),
        }
        .serialize(serializer)
    }
}

struct SemanticResults<'a> {
    hits: &'a [MessageSearchHit],
    target: Option<&'a MessageTarget>,
    context_windows: &'a [Vec<crate::models::MessageHit>],
    presentation: ResolvedMessagePresentation,
    cancellation: Option<&'a AtomicBool>,
}

impl Serialize for SemanticResults<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::Error as _;

        let mut sequence = serializer.serialize_seq(Some(self.hits.len()))?;
        for (index, hit) in self.hits.iter().enumerate() {
            ensure_message_search_serialization_active(self.cancellation)
                .map_err(S::Error::custom)?;
            sequence.serialize_element(&SemanticResult {
                hit,
                target: self.target,
                context: self.context_windows.get(index).map(Vec::as_slice),
                presentation: self.presentation,
            })?;
        }
        sequence.end()
    }
}

fn ensure_message_search_serialization_active(
    cancellation: Option<&AtomicBool>,
) -> Result<(), &'static str> {
    if cancellation.is_some_and(|flag| flag.load(AtomicOrdering::Acquire)) {
        Err("message-search response serialization was cancelled")
    } else {
        Ok(())
    }
}

#[derive(Serialize)]
struct SemanticMessageRef<'a> {
    session_id: &'a str,
    message_seq: i64,
}

#[derive(Serialize)]
struct SemanticMessageMetadata {
    provider: Provider,
    role: Role,
    kind: MessageKind,
}

#[derive(Serialize)]
struct SemanticLiteralOccurrence<'a> {
    text: &'a str,
    field_start_char: usize,
    field_end_char_exclusive: usize,
}

#[derive(Serialize)]
struct SemanticMatch<'a> {
    field: SearchField,
    #[serde(skip_serializing_if = "Option::is_none")]
    argument_path: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    fuzzy_score: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    literal_occurrence: Option<SemanticLiteralOccurrence<'a>>,
}

#[derive(Serialize)]
struct SemanticPresentation<'a> {
    field_view: SemanticFieldView<'a>,
    #[serde(skip_serializing_if = "Option::is_none")]
    match_view: Option<SemanticFieldView<'a>>,
}

#[derive(Serialize)]
struct SemanticFieldView<'a> {
    text: &'a str,
    field_start_char: usize,
    field_end_char_exclusive: usize,
    #[serde(skip_serializing_if = "SemanticMarkers::is_empty")]
    markers: SemanticMarkers<'a>,
    #[serde(flatten)]
    extent: FieldViewExtent,
}

impl<'a> From<&'a MessageFieldView> for SemanticFieldView<'a> {
    fn from(view: &'a MessageFieldView) -> Self {
        Self {
            text: &view.text,
            field_start_char: view.field_start_char,
            field_end_char_exclusive: view.field_end_char_exclusive,
            markers: SemanticMarkers(&view.markers),
            extent: view.extent,
        }
    }
}

struct SemanticMarkers<'a>(&'a [ViewCharRange]);

impl SemanticMarkers<'_> {
    fn is_empty(&self) -> bool {
        self.0.is_empty()
    }
}

impl Serialize for SemanticMarkers<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut sequence = serializer.serialize_seq(Some(self.0.len()))?;
        for marker in self.0 {
            sequence.serialize_element(&SemanticMarker {
                view_start_char: marker.view_start_char,
                view_end_char_exclusive: marker.view_end_char_exclusive,
            })?;
        }
        sequence.end()
    }
}

#[derive(Serialize)]
struct SemanticMarker {
    view_start_char: usize,
    view_end_char_exclusive: usize,
}

struct SemanticResult<'a> {
    hit: &'a MessageSearchHit,
    target: Option<&'a MessageTarget>,
    context: Option<&'a [crate::models::MessageHit]>,
    presentation: ResolvedMessagePresentation,
}

impl Serialize for SemanticResult<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let hit = self.hit;
        let message_ref = SemanticMessageRef {
            session_id: &hit.message.session_id,
            message_seq: hit.message.seq,
        };
        let literal_occurrence =
            hit.literal_match
                .as_ref()
                .map(|literal| SemanticLiteralOccurrence {
                    text: &literal.text,
                    field_start_char: literal.field_start_char,
                    field_end_char_exclusive: literal.field_end_char_exclusive,
                });
        let field = self
            .target
            .map_or(SearchField::Content, MessageTarget::field);
        let has_match = hit.match_evidence.is_some() || hit.literal_match.is_some();
        let mut entry_count = if has_match { 4 } else { 3 };
        if hit.parsed_references.is_some() {
            entry_count += 1;
        }
        if self.context.is_some() {
            entry_count += 1;
        }
        let mut map = serializer.serialize_map(Some(entry_count))?;
        map.serialize_entry("message_ref", &message_ref)?;
        map.serialize_entry(
            "message_metadata",
            &SemanticMessageMetadata {
                provider: hit.message.provider,
                role: hit.message.role,
                kind: hit.message.kind,
            },
        )?;
        if has_match {
            map.serialize_entry(
                "match",
                &SemanticMatch {
                    field,
                    argument_path: self
                        .target
                        .and_then(MessageTarget::argument_path)
                        .map(JsonPointer::as_str),
                    fuzzy_score: hit.message.fuzzy_score,
                    literal_occurrence,
                },
            )?;
        }
        map.serialize_entry(
            "presentation",
            &SemanticPresentation {
                field_view: SemanticFieldView::from(hit.field_view()),
                match_view: hit.match_view.as_ref().map(SemanticFieldView::from),
            },
        )?;
        if let Some(parsed_references) = hit.parsed_references.as_ref() {
            map.serialize_entry("included", &SemanticResultIncluded { parsed_references })?;
        }
        if let Some(context) = self.context {
            map.serialize_entry(
                "context",
                &SemanticContext {
                    anchor_seq: hit.message.seq,
                    messages: context,
                    presentation: self.presentation,
                },
            )?;
        }
        map.end()
    }
}

#[derive(Serialize)]
struct SemanticResultIncluded<'a> {
    parsed_references: &'a [MessageRef],
}

struct SemanticContext<'a> {
    anchor_seq: i64,
    messages: &'a [crate::models::MessageHit],
    presentation: ResolvedMessagePresentation,
}

impl Serialize for SemanticContext<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let messages_before = self
            .messages
            .iter()
            .filter(|message| message.seq < self.anchor_seq)
            .map(|message| SemanticContextMessage {
                message,
                presentation: self.presentation,
            })
            .collect::<Vec<_>>();
        let messages_after = self
            .messages
            .iter()
            .filter(|message| message.seq > self.anchor_seq)
            .map(|message| SemanticContextMessage {
                message,
                presentation: self.presentation,
            })
            .collect::<Vec<_>>();
        let mut map = serializer.serialize_map(Some(2))?;
        map.serialize_entry("messages_before", &messages_before)?;
        map.serialize_entry("messages_after", &messages_after)?;
        map.end()
    }
}

struct SemanticContextMessage<'a> {
    message: &'a crate::models::MessageHit,
    presentation: ResolvedMessagePresentation,
}

impl Serialize for SemanticContextMessage<'_> {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        use serde::ser::Error as _;

        let message = self.message;
        let field_view = selected_field_view(
            &message.content,
            self.presentation.message_lines,
            self.presentation.field_view,
            None,
        )
        .map_err(S::Error::custom)?;
        let mut map = serializer.serialize_map(Some(6))?;
        map.serialize_entry(
            "message_ref",
            &SemanticMessageRef {
                session_id: &message.session_id,
                message_seq: message.seq,
            },
        )?;
        map.serialize_entry(
            "message_metadata",
            &SemanticMessageMetadata {
                provider: message.provider,
                role: message.role,
                kind: message.kind,
            },
        )?;
        map.serialize_entry("timestamp", &message.ts)?;
        map.serialize_entry("tool_name", &message.tool_name)?;
        map.serialize_entry("tool_call_id", &message.tool_call_id)?;
        map.serialize_entry(
            "presentation",
            &SemanticPresentation {
                field_view: SemanticFieldView::from(&field_view),
                match_view: None,
            },
        )?;
        map.end()
    }
}

#[derive(Serialize)]
struct SemanticPageFields {
    returned: usize,
    limit: Option<usize>,
    offset: usize,
    has_more: bool,
    next_offset: Option<usize>,
    earlier_results: PageSide,
    result_set_extent: ResultSetExtent,
    ordering: ExecutionOrder,
    consistency: PageConsistency,
}

#[derive(Serialize)]
#[serde(rename_all = "kebab-case")]
enum PageConsistency {
    PerCall,
}

impl From<PageInfo> for SemanticPageFields {
    fn from(page: PageInfo) -> Self {
        let (limit, offset) = match page.extent {
            ResolvedExtent::Page { limit, offset } => (Some(limit.get()), offset),
            ResolvedExtent::AllResults { offset } => (None, offset),
        };
        Self {
            returned: page.returned,
            limit,
            offset,
            has_more: page.next_offset.is_some(),
            next_offset: page.next_offset,
            earlier_results: page.earlier_results,
            result_set_extent: page.result_set_extent,
            ordering: page.ordering,
            consistency: PageConsistency::PerCall,
        }
    }
}

#[derive(Serialize)]
struct SemanticReceipt<'a> {
    #[serde(skip_serializing_if = "Option::is_none")]
    search_explanation: Option<&'a crate::models::SearchExplain>,
    #[serde(skip_serializing_if = "Option::is_none")]
    parameter_origins: Option<&'a MessageSearchOrigins>,
    #[serde(skip_serializing_if = "Option::is_none")]
    ordered_digest: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct MessageSearchRequest {
    query: MessageQuery,
    target: MessageTarget,
    predicates: MessagePredicates,
    match_window: Option<MatchWindow>,
    context: Option<ContextWindow>,
    presentation: MessagePresentation,
    extent: RequestedExtent,
    purpose: Option<PurposeSelection>,
    receipt: Option<ReceiptLevel>,
    includes: Option<Vec<MessageSearchInclude>>,
}

impl MessageSearchRequest {
    pub fn builder(query: MessageQuery, target: MessageTarget) -> MessageSearchRequestBuilder {
        MessageSearchRequestBuilder {
            request: Self {
                query,
                target,
                predicates: MessagePredicates::default(),
                match_window: None,
                context: None,
                presentation: MessagePresentation::default(),
                extent: RequestedExtent::default(),
                purpose: None,
                receipt: None,
                includes: None,
            },
        }
    }

    pub fn query(&self) -> &MessageQuery {
        &self.query
    }

    pub fn target(&self) -> &MessageTarget {
        &self.target
    }

    pub fn predicates(&self) -> &MessagePredicates {
        &self.predicates
    }

    pub const fn match_window(&self) -> Option<MatchWindow> {
        self.match_window
    }

    pub const fn context(&self) -> Option<ContextWindow> {
        self.context
    }

    pub const fn presentation(&self) -> MessagePresentation {
        self.presentation
    }

    pub const fn extent(&self) -> RequestedExtent {
        self.extent
    }

    pub fn purpose(&self) -> Option<&PurposeSelection> {
        self.purpose.as_ref()
    }

    pub const fn receipt_level(&self) -> Option<ReceiptLevel> {
        self.receipt
    }

    pub fn includes(&self) -> Option<&[MessageSearchInclude]> {
        self.includes.as_deref()
    }

    fn validate(&self) -> Result<(), MessageSearchError> {
        if self.presentation.detail.is_some()
            && (self.presentation.message_lines.is_some()
                || self.presentation.field_view.is_some()
                || self.presentation.match_view.is_some())
        {
            return Err(MessageSearchRule::DetailOwnsPresentationBudgets.error());
        }
        if self.predicates.sequence.is_some() && self.predicates.session.is_none() {
            return Err(MessageSearchRule::SequenceRequiresSession.error());
        }
        // Validate the RESOLVED set, not each parameter alone: `kinds` and include_compaction
        // both narrow the same set, and every conflict found in this area passed
        // per-parameter checks while producing a request that could not match anything.
        // An unsatisfiable request must error, never return silently empty.
        let mut effective = self
            .predicates
            .kinds
            .clone()
            .unwrap_or_else(MessageKind::default_search_set);
        if !self.predicates.include_compaction {
            effective.retain(|kind| *kind != MessageKind::Compaction);
        }
        if effective.is_empty() {
            return Err(MessageSearchRule::KindsMustRemainSatisfiable.error());
        }
        if self.predicates.role == Some(Role::Compaction)
            && !effective.contains(&MessageKind::Compaction)
        {
            return Err(MessageSearchRule::CompactionRoleRequiresCompactionKind.error());
        }
        if self.target.field == SearchField::ToolArgument
            && self
                .predicates
                .kinds
                .as_ref()
                .is_some_and(|kinds| !kinds.contains(&MessageKind::ToolCall))
        {
            return Err(MessageSearchRule::ToolArgumentRequiresToolCallKind.error());
        }
        if matches!(self.query, MessageQuery::All) && self.presentation.match_view.is_some() {
            return Err(MessageSearchRule::MatchViewRequiresQuery.error());
        }
        if self.match_window.is_some() && matches!(self.query, MessageQuery::Fuzzy(_)) {
            return Err(MessageSearchRule::FuzzyRejectsMatchWindow.error());
        }
        if self.match_window == Some(MatchWindow::Latest) && self.predicates.session.is_none() {
            return Err(MessageSearchRule::LatestWindowRequiresSession.error());
        }
        if let MessageQuery::Fuzzy(_) = self.query {
            match self.extent {
                RequestedExtent::Page { .. } => {}
                RequestedExtent::AllResults { .. } => {
                    return Err(MessageSearchRule::FuzzyRejectsAllResults.error())
                }
            }
        }
        Ok(())
    }
}

pub struct MessageSearchRequestBuilder {
    request: MessageSearchRequest,
}

impl MessageSearchRequestBuilder {
    pub fn role(mut self, role: Role) -> Self {
        self.request.predicates.role = Some(role);
        self
    }

    /// Select exactly one class. Convenience over [`Self::kinds`] for the common case.
    pub fn kind(mut self, kind: MessageKind) -> Self {
        self.request.predicates.kinds = Some(vec![kind]);
        self
    }

    /// Select the classes to return, replacing the default set (everything except
    /// `HarnessNotice`). This is the single mechanism for class selection.
    pub fn kinds(mut self, kinds: Vec<MessageKind>) -> Self {
        self.request.predicates.kinds = Some(kinds);
        self
    }

    pub fn provider(mut self, provider: Provider) -> Self {
        self.request.predicates.providers = Some(vec![provider]);
        self
    }

    /// Select one or more session sources.
    ///
    /// This is set semantics: duplicates are removed and the stored order is canonical, so
    /// equivalent requests produce byte-identical effective-request metadata. An empty set is an
    /// invalid scope rather than a successful search that misleadingly reports no matches.
    pub fn providers(mut self, mut providers: Vec<Provider>) -> Result<Self, MessageSearchError> {
        if providers.is_empty() {
            return Err(MessageSearchError::InvalidParameter {
                parameter: "providers",
                reason: "must contain at least one provider".into(),
            });
        }
        providers.sort_unstable_by_key(|provider| provider.as_str());
        providers.dedup();
        self.request.predicates.providers = Some(providers);
        Ok(self)
    }

    pub fn session_id(mut self, session: impl Into<String>) -> Result<Self, MessageSearchError> {
        self.request.predicates.session = Some(NonEmptyValue::new("session_id", session)?);
        Ok(self)
    }

    pub fn workspace_path_prefix(
        mut self,
        path: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request.predicates.workspace_path_prefix =
            Some(NonEmptyValue::new("workspace_path_prefix", path)?);
        Ok(self)
    }

    pub fn transcript_path_prefix(
        mut self,
        path: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request.predicates.transcript_path_prefix =
            Some(NonEmptyValue::new("transcript_path_prefix", path)?);
        Ok(self)
    }

    pub fn exclude_workspace_path_prefix(
        mut self,
        path: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request
            .predicates
            .exclude_workspace_path_prefixes
            .push(NonEmptyValue::new("exclude_workspace_path_prefix", path)?);
        Ok(self)
    }

    pub fn exclude_transcript_path_prefix(
        mut self,
        path: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request
            .predicates
            .exclude_transcript_path_prefixes
            .push(NonEmptyValue::new("exclude_transcript_path_prefix", path)?);
        Ok(self)
    }

    pub fn exclude_session_id(
        mut self,
        session: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request
            .predicates
            .exclude_session_ids
            .push(NonEmptyValue::new("exclude_session_id", session)?);
        Ok(self)
    }

    pub fn time(mut self, time: RequestedTimeRange) -> Self {
        self.request.predicates.time = time;
        self
    }

    pub fn sequence(mut self, sequence: SequenceRange) -> Self {
        self.request.predicates.sequence = Some(sequence);
        self
    }

    pub fn tool_name_contains(
        mut self,
        value: impl Into<String>,
    ) -> Result<Self, MessageSearchError> {
        self.request.predicates.tool_name_contains =
            Some(NonEmptyValue::new("tool_name_contains", value)?);
        Ok(self)
    }

    pub fn include_compaction(mut self, include: bool) -> Self {
        self.request.predicates.include_compaction = include;
        self
    }

    pub fn match_window(mut self, window: MatchWindow) -> Self {
        self.request.match_window = Some(window);
        self
    }

    pub fn context(mut self, context: ContextWindow) -> Self {
        self.request.context = Some(context);
        self
    }

    pub fn message_lines(mut self, window: LineWindow) -> Self {
        self.request.presentation.message_lines = Some(window);
        self
    }

    pub fn detail(mut self, detail: DetailLevel) -> Self {
        self.request.presentation.detail = Some(detail);
        self
    }

    pub fn field_view(mut self, budget: FieldViewBudget) -> Self {
        self.request.presentation.field_view = Some(budget);
        self
    }

    pub fn match_view(mut self, budget: MatchViewBudget) -> Self {
        self.request.presentation.match_view = Some(budget);
        self
    }

    pub fn extent(mut self, extent: RequestedExtent) -> Self {
        self.request.extent = extent;
        self
    }

    pub fn purpose(mut self, purpose: PurposeSelection) -> Self {
        self.request.purpose = Some(purpose);
        self
    }

    pub fn receipt_level(mut self, level: ReceiptLevel) -> Self {
        self.request.receipt = Some(level);
        self
    }

    /// Replace optional payload groups. An empty collection explicitly requests the semantic core.
    pub fn includes(mut self, includes: impl IntoIterator<Item = MessageSearchInclude>) -> Self {
        let mut includes = includes.into_iter().collect::<Vec<_>>();
        includes.sort_unstable();
        includes.dedup();
        self.request.includes = Some(includes);
        self
    }

    pub fn build(self) -> Result<MessageSearchRequest, MessageSearchError> {
        self.request.validate()?;
        Ok(self.request)
    }
}

pub(crate) fn selected_message_field<'a>(
    hit: &'a crate::models::MessageHit,
    target: &MessageTarget,
) -> Option<Cow<'a, str>> {
    selected_message_field_parts(
        hit,
        target.field(),
        target.argument_path().map(JsonPointer::as_str),
    )
}

pub(crate) fn selected_message_field_parts<'a>(
    hit: &'a crate::models::MessageHit,
    field: SearchField,
    argument_path: Option<&str>,
) -> Option<Cow<'a, str>> {
    match field {
        SearchField::Content => Some(Cow::Borrowed(&hit.content)),
        SearchField::ToolName => hit.tool_name.as_deref().map(Cow::Borrowed),
        SearchField::ToolArgument => {
            let envelope: serde_json::Value = serde_json::from_str(&hit.content).ok()?;
            let args = envelope.get("args")?;
            let value = match argument_path.unwrap_or("") {
                "" => args,
                pointer => args.pointer(pointer)?,
            };
            Some(Cow::Owned(match value {
                serde_json::Value::String(value) => value.clone(),
                other => serde_json::to_string(other).ok()?,
            }))
        }
    }
}

#[cfg(test)]
pub(crate) fn attach_match_evidence(
    query: &MessageQuery,
    target: &MessageTarget,
    match_view: MatchViewBudget,
    hits: Vec<crate::models::MessageHit>,
) -> anyhow::Result<Vec<MessageSearchHit>> {
    attach_match_evidence_cancellable(query, target, match_view, hits, || Ok(()))
}

pub(crate) fn attach_match_evidence_cancellable(
    query: &MessageQuery,
    target: &MessageTarget,
    match_view: MatchViewBudget,
    hits: Vec<crate::models::MessageHit>,
    mut check_active: impl FnMut() -> anyhow::Result<()>,
) -> anyhow::Result<Vec<MessageSearchHit>> {
    let mut prepared = PreparedMatchEvidence::new(query)?;
    let mut enriched = Vec::with_capacity(hits.len());
    for message in hits {
        check_active()?;
        let (match_evidence, literal_match) = match query {
            MessageQuery::All => {
                // Queryless search selects rows by field presence and deliberately does not
                // parse or reconstruct a selected value merely to prove match evidence.
                (None, None)
            }
            _ => {
                let selected = selected_message_field(&message, target).ok_or_else(|| {
                    anyhow::anyhow!(
                        "message-search match evidence cannot project {:?} for {} sequence {}",
                        target.field(),
                        message.session_id,
                        message.seq
                    )
                })?;
                let evidence = prepared.build(&selected, match_view).ok_or_else(|| {
                    anyhow::anyhow!(
                        "message-search match evidence disagrees with {:?} membership for {} sequence {}",
                        target.field(),
                        message.session_id,
                        message.seq
                    )
                })?;
                check_active()?;
                let literal_match = match query {
                    MessageQuery::Literal(_) => {
                        let range = match &evidence.markers {
                            MessageMatchViewMarkers::Characters {
                                ranges,
                                matched_chars_total,
                                ..
                            } => ranges.first().map(|range| {
                                let field_start_char =
                                    evidence.field_start_char + range.view_start_char;
                                FieldCharRange {
                                    field_start_char,
                                    field_end_char_exclusive: field_start_char
                                        + matched_chars_total,
                                }
                            }),
                            MessageMatchViewMarkers::Boundary { .. } => None,
                        }
                        .ok_or_else(|| {
                            anyhow::anyhow!(
                                "literal match evidence has no character range for {} sequence {}",
                                message.session_id,
                                message.seq
                            )
                        })?;
                        Some(MessageLiteralMatch {
                            text: selected
                                .chars()
                                .skip(range.field_start_char)
                                .take(range.field_end_char_exclusive - range.field_start_char)
                                .collect(),
                            field_start_char: range.field_start_char,
                            field_end_char_exclusive: range.field_end_char_exclusive,
                        })
                    }
                    _ => None,
                };
                (Some(evidence), literal_match)
            }
        };
        enriched.push(MessageSearchHit {
            message,
            match_evidence,
            literal_match,
            field_view: None,
            match_view: None,
            parsed_references: None,
        });
    }
    Ok(enriched)
}

#[cfg(test)]
fn complete_field_view(field_text: &str) -> MessageFieldView {
    let returned_chars = field_text.chars().count();
    MessageFieldView {
        text: field_text.to_owned(),
        field_start_char: 0,
        field_end_char_exclusive: returned_chars,
        markers: Vec::new(),
        extent: FieldViewExtent {
            additional_field_text: AdditionalFieldText::None,
            field_total_chars: Some(returned_chars),
            coordinate_unit: CoordinateUnit::UnicodeScalar,
        },
    }
}

fn evidence_field_view(evidence: &MessageMatchEvidence) -> MessageFieldView {
    let markers = match &evidence.markers {
        MessageMatchViewMarkers::Characters { ranges, .. } => ranges.clone(),
        MessageMatchViewMarkers::Boundary { view_at_char } => vec![ViewCharRange {
            view_start_char: *view_at_char,
            view_end_char_exclusive: *view_at_char,
        }],
    };
    let returned_chars = evidence.view_text.chars().count();
    let has_text_before = evidence.field_start_char > 0;
    let has_text_after =
        evidence.field_start_char.saturating_add(returned_chars) < evidence.field_total_chars;
    MessageFieldView {
        text: evidence.view_text.clone(),
        field_start_char: evidence.field_start_char,
        field_end_char_exclusive: evidence.field_start_char.saturating_add(returned_chars),
        markers,
        extent: FieldViewExtent {
            additional_field_text: additional_field_text(has_text_before, has_text_after),
            field_total_chars: Some(evidence.field_total_chars),
            coordinate_unit: CoordinateUnit::UnicodeScalar,
        },
    }
}

/// Project a fully classified message into bounded field and match views without changing the
/// text used for classification.
///
/// Time is `O(D + V)`, where `D` is authoritative message characters and `V` is returned view
/// characters. Retained memory is `O(V)`. Exact match coordinates come from the classifier, so a
/// repeated substring cannot move the presentation marker to a different occurrence.
pub(crate) fn classification_presentation(
    content: &str,
    match_start_char: usize,
    match_end_char_exclusive: usize,
    field_budget: FieldViewBudget,
    match_budget: MatchViewBudget,
) -> anyhow::Result<(MessageFieldView, MessageFieldView)> {
    let field_total_chars = content.chars().count();
    if match_start_char >= match_end_char_exclusive || match_end_char_exclusive > field_total_chars
    {
        anyhow::bail!(
            "classification match range {match_start_char}..{match_end_char_exclusive} is outside \
             a message containing {field_total_chars} Unicode scalar characters"
        );
    }
    let range = FieldCharRange {
        field_start_char: match_start_char,
        field_end_char_exclusive: match_end_char_exclusive,
    };
    let maximum = match_view_max_chars(
        match_budget,
        field_total_chars,
        std::slice::from_ref(&range),
    );
    let evidence = character_evidence(content, field_total_chars, maximum, vec![range], false);
    Ok((
        selected_field_view(
            content,
            LineWindow::Full,
            field_budget,
            Some(field_total_chars),
        )?,
        evidence_field_view(&evidence),
    ))
}

/// Serialize one bounded classification result using the same recovery-oriented shape for CLI
/// JSON and MCP. The full classified content remains in the typed core report; bounded adapters
/// return its stable message reference and extent instead of duplicating large text.
pub(crate) fn classification_presentation_document(
    matched: &crate::models::MessageClassificationMatch,
    field_budget: FieldViewBudget,
    match_budget: MatchViewBudget,
) -> anyhow::Result<serde_json::Value> {
    let (field_view, match_view) = classification_presentation(
        &matched.content,
        matched.match_start_char,
        matched.match_end_char_exclusive,
        field_budget,
        match_budget,
    )?;
    Ok(serde_json::json!({
        "message_ref": {
            "session_id": matched.session_id,
            "message_seq": matched.message_seq
        },
        "message_metadata": {
            "provider": matched.provider,
            "timestamp": matched.ts
        },
        "classification": {
            "policy_name": matched.policy_name,
            "category": matched.category,
            "matched_text": matched.matched_text,
            "field_start_char": matched.match_start_char,
            "field_end_char_exclusive": matched.match_end_char_exclusive,
            "coordinate_unit": "unicode_scalar"
        },
        "presentation": {
            "field_view": field_view,
            "match_view": match_view
        }
    }))
}

/// Apply presentation after retrieval and match proof have been finalized.
///
/// Let `V` be returned view characters and `D` the selected-field characters inspected to locate
/// a tail boundary. Head/full presentation is `O(V)` when the original size is not needed; tail
/// selection is `O(D)`. This function never changes hit membership, order, score, or page identity.
pub(crate) fn apply_message_presentation_cancellable(
    target: &MessageTarget,
    presentation: ResolvedMessagePresentation,
    hits: &mut [MessageSearchHit],
    mut check_active: impl FnMut() -> anyhow::Result<()>,
) -> anyhow::Result<()> {
    for hit in hits {
        check_active()?;
        let selected = match selected_message_field(&hit.message, target) {
            Some(selected) => selected,
            None if hit.match_evidence.is_none() => Cow::Borrowed(hit.message.content.as_str()),
            None => {
                return Err(anyhow::anyhow!(
                    "message-search presentation cannot project {:?} for {} sequence {}",
                    target.field(),
                    hit.message.session_id,
                    hit.message.seq
                ))
            }
        };
        hit.field_view = Some(selected_field_view(
            &selected,
            presentation.message_lines,
            presentation.field_view,
            hit.match_evidence
                .as_ref()
                .map(|evidence| evidence.field_total_chars),
        )?);
        hit.match_view = hit.match_evidence.as_ref().map(evidence_field_view);
        check_active()?;
    }
    Ok(())
}

pub(crate) fn selected_field_view(
    original: &str,
    lines: LineWindow,
    budget: FieldViewBudget,
    known_original_chars: Option<usize>,
) -> Result<MessageFieldView, MessageSearchError> {
    let signed_lines = lines.to_signed()?;
    let line_selected = if signed_lines == 0 {
        Cow::Borrowed(original)
    } else {
        Cow::Owned(crate::util::select_message_lines(original, signed_lines))
    };
    let line_start = if matches!(lines, LineWindow::Tail(_)) {
        let selected_chars = line_selected.chars().count();
        known_original_chars
            .map(|total| total.saturating_sub(selected_chars))
            .or_else(|| {
                original
                    .rfind(line_selected.as_ref())
                    .map(|byte| original[..byte].chars().count())
            })
            .unwrap_or_else(|| original.chars().count().saturating_sub(selected_chars))
    } else {
        0
    };
    let line_has_text_before = line_start > 0;
    let line_end = line_start.saturating_add(line_selected.chars().count());
    let tail_has_text_after =
        matches!(lines, LineWindow::Tail(_)) && !original.ends_with(line_selected.as_ref());
    let original_chars_if_counted = match (known_original_chars, lines, budget) {
        (Some(total), _, _) => Some(total),
        (None, LineWindow::Full, FieldViewBudget::NoCharLimit) => Some(original.chars().count()),
        (None, LineWindow::Tail(_), _) => None,
        (None, LineWindow::Head(_), _) if line_selected == original => Some(line_end),
        _ => None,
    };
    let line_has_text_after = original_chars_if_counted.is_some_and(|total| line_end < total)
        || (matches!(lines, LineWindow::Head(_)) && line_selected != original)
        || tail_has_text_after;

    let (text, field_start_char, budget_has_text_before, budget_has_text_after) = match budget {
        FieldViewBudget::NoCharLimit => (line_selected.into_owned(), line_start, false, false),
        FieldViewBudget::MaxChars { max_chars } => {
            let maximum = max_chars.get();
            match lines {
                LineWindow::Tail(_) => {
                    let selected_chars = line_selected.chars().count();
                    if selected_chars <= maximum {
                        (line_selected.into_owned(), line_start, false, false)
                    } else {
                        let skipped = selected_chars - maximum;
                        let start_byte = line_selected
                            .char_indices()
                            .nth(skipped)
                            .map_or(line_selected.len(), |(byte, _)| byte);
                        (
                            line_selected[start_byte..].to_owned(),
                            line_start + skipped,
                            true,
                            false,
                        )
                    }
                }
                LineWindow::Full | LineWindow::Head(_) => {
                    let mut characters = line_selected.chars();
                    let text = characters.by_ref().take(maximum).collect::<String>();
                    let truncated = characters.next().is_some();
                    (text, line_start, false, truncated)
                }
            }
        }
    };
    let returned_chars = text.chars().count();
    let has_text_before = line_has_text_before || budget_has_text_before;
    let has_text_after = line_has_text_after || budget_has_text_after;
    let field_total_chars = original_chars_if_counted;
    Ok(MessageFieldView {
        text,
        field_start_char,
        field_end_char_exclusive: field_start_char.saturating_add(returned_chars),
        markers: Vec::new(),
        extent: FieldViewExtent {
            additional_field_text: additional_field_text(has_text_before, has_text_after),
            field_total_chars,
            coordinate_unit: CoordinateUnit::UnicodeScalar,
        },
    })
}

const fn additional_field_text(has_text_before: bool, has_text_after: bool) -> AdditionalFieldText {
    match (has_text_before, has_text_after) {
        (false, false) => AdditionalFieldText::None,
        (false, true) => AdditionalFieldText::After,
        (true, false) => AdditionalFieldText::Before,
        (true, true) => AdditionalFieldText::BeforeAndAfter,
    }
}

enum PreparedMatchEvidence {
    All,
    Literal {
        lowered_query: String,
    },
    Regex(regex::Regex),
    Fuzzy {
        pattern: Pattern,
        matcher: NucleoMatcher,
        utf32_buf: Vec<char>,
        indices: Vec<u32>,
    },
}

impl PreparedMatchEvidence {
    fn new(query: &MessageQuery) -> anyhow::Result<Self> {
        Ok(match query {
            MessageQuery::All => Self::All,
            MessageQuery::Literal(query) => Self::Literal {
                lowered_query: crate::util::fold_caseless(query.as_str()),
            },
            MessageQuery::Regex(query) => Self::Regex(regex::Regex::new(query.as_str())?),
            MessageQuery::Fuzzy(query) => Self::Fuzzy {
                pattern: Pattern::new(
                    query.as_str(),
                    CaseMatching::Ignore,
                    Normalization::Smart,
                    AtomKind::Fuzzy,
                ),
                matcher: NucleoMatcher::new(NucleoConfig::DEFAULT),
                utf32_buf: Vec::new(),
                indices: Vec::new(),
            },
        })
    }

    fn build(
        &mut self,
        selected: &str,
        match_view: MatchViewBudget,
    ) -> Option<MessageMatchEvidence> {
        let field_total_chars = selected.chars().count();
        match self {
            Self::All => None,
            Self::Literal { lowered_query } => {
                let range = literal_char_range(selected, lowered_query)?;
                let maximum = match_view_max_chars(
                    match_view,
                    field_total_chars,
                    std::slice::from_ref(&range),
                );
                Some(character_evidence(
                    selected,
                    field_total_chars,
                    maximum,
                    vec![range],
                    false,
                ))
            }
            Self::Regex(regex) => {
                let matched = regex.find(selected)?;
                let start = selected[..matched.start()].chars().count();
                let end = start + matched.as_str().chars().count();
                if start == end {
                    let maximum = match match_view {
                        MatchViewBudget::MinimalSpan => 0,
                        MatchViewBudget::MaxChars { max_chars } => {
                            max_chars.get().min(field_total_chars.max(1))
                        }
                    };
                    Some(boundary_evidence(
                        selected,
                        field_total_chars,
                        maximum,
                        start,
                    ))
                } else {
                    let range = FieldCharRange {
                        field_start_char: start,
                        field_end_char_exclusive: end,
                    };
                    let maximum = match_view_max_chars(
                        match_view,
                        field_total_chars,
                        std::slice::from_ref(&range),
                    );
                    Some(character_evidence(
                        selected,
                        field_total_chars,
                        maximum,
                        vec![range],
                        false,
                    ))
                }
            }
            Self::Fuzzy {
                pattern,
                matcher,
                utf32_buf,
                indices,
            } => {
                utf32_buf.clear();
                indices.clear();
                let matcher_input = Utf32Str::new(selected, utf32_buf);
                pattern.indices(matcher_input, matcher, indices)?;
                let matcher_unit_ranges = scalar_ranges_by_matcher_unit(selected, matcher_input);
                let ranges = indices
                    .iter()
                    .map(|index| matcher_unit_ranges.get(*index as usize).copied())
                    .collect::<Option<Vec<_>>>()?;
                let ranges = coalesce_character_ranges(ranges);
                let maximum = match_view_max_chars(match_view, field_total_chars, &ranges);
                Some(character_evidence(
                    selected,
                    field_total_chars,
                    maximum,
                    ranges,
                    true,
                ))
            }
        }
    }
}

fn match_view_max_chars(
    budget: MatchViewBudget,
    field_total_chars: usize,
    ranges: &[FieldCharRange],
) -> usize {
    match budget {
        MatchViewBudget::MaxChars { max_chars } => max_chars.get().min(field_total_chars.max(1)),
        MatchViewBudget::MinimalSpan => ranges
            .first()
            .zip(ranges.last())
            .map(|(first, last)| {
                last.field_end_char_exclusive
                    .saturating_sub(first.field_start_char)
            })
            .unwrap_or(0),
    }
}

/// Where `lowered_query` sits in `selected`, in source characters.
///
/// `lowered_query` is folded by [`crate::util::fold_caseless`] and this folds the text the same
/// way, so the range it reports is the range the matcher that selected the row agreed on. Folding
/// the two sides by different rules located nothing for text they spelled differently, and the
/// caller then showed the head of the field as evidence for a match found elsewhere in it.
fn literal_char_range(selected: &str, lowered_query: &str) -> Option<FieldCharRange> {
    let mut lowered = String::new();
    let mut original_char_for_lowered = Vec::new();
    for (original_char, value) in selected.chars().enumerate() {
        for lowered_char in crate::util::fold_caseless_char(value) {
            lowered.push(lowered_char);
            original_char_for_lowered.push(original_char);
        }
    }
    let start_byte = lowered.find(lowered_query)?;
    let start_lowered = lowered[..start_byte].chars().count();
    let end_lowered = start_lowered + lowered_query.chars().count();
    Some(FieldCharRange {
        field_start_char: original_char_for_lowered[start_lowered],
        field_end_char_exclusive: original_char_for_lowered[end_lowered - 1] + 1,
    })
}

fn scalar_ranges_by_grapheme(selected: &str) -> Vec<FieldCharRange> {
    let mut scalar_start = 0;
    selected
        .graphemes(true)
        .map(|grapheme| {
            let scalar_end = scalar_start + grapheme.chars().count();
            let range = FieldCharRange {
                field_start_char: scalar_start,
                field_end_char_exclusive: scalar_end,
            };
            scalar_start = scalar_end;
            range
        })
        .collect()
}

fn scalar_ranges_by_matcher_unit(
    selected: &str,
    matcher_input: Utf32Str<'_>,
) -> Vec<FieldCharRange> {
    match matcher_input {
        Utf32Str::Unicode(_) => scalar_ranges_by_grapheme(selected),
        Utf32Str::Ascii(_) => {
            let mut scalar_start = 0;
            let mut ranges = Vec::with_capacity(selected.len());
            for grapheme in selected.graphemes(true) {
                let scalar_end = scalar_start + grapheme.chars().count();
                let range = FieldCharRange {
                    field_start_char: scalar_start,
                    field_end_char_exclusive: scalar_end,
                };
                ranges.extend(std::iter::repeat_n(range, grapheme.len()));
                scalar_start = scalar_end;
            }
            ranges
        }
    }
}

fn coalesce_character_ranges(mut ranges: Vec<FieldCharRange>) -> Vec<FieldCharRange> {
    ranges.sort_by_key(|range| (range.field_start_char, range.field_end_char_exclusive));
    let mut coalesced = Vec::new();
    for range in ranges {
        match coalesced.last_mut() {
            Some(FieldCharRange {
                field_end_char_exclusive,
                ..
            }) if range.field_start_char <= *field_end_char_exclusive => {
                *field_end_char_exclusive =
                    (*field_end_char_exclusive).max(range.field_end_char_exclusive);
            }
            _ => coalesced.push(range),
        }
    }
    coalesced
}

fn character_evidence(
    selected: &str,
    field_total_chars: usize,
    maximum: usize,
    ranges: Vec<FieldCharRange>,
    densest_window: bool,
) -> MessageMatchEvidence {
    let matched_chars_total = ranges
        .iter()
        .map(|range| range.field_end_char_exclusive - range.field_start_char)
        .sum();
    let field_start_char = if field_total_chars <= maximum {
        0
    } else if densest_window {
        densest_excerpt_start(&ranges, maximum, field_total_chars)
    } else {
        let first = ranges[0];
        let width = first.field_end_char_exclusive - first.field_start_char;
        first
            .field_start_char
            .saturating_sub(maximum.saturating_sub(width) / 2)
            .min(field_total_chars - maximum)
    };
    let field_end_char_exclusive = (field_start_char + maximum).min(field_total_chars);
    let shown = ranges
        .iter()
        .filter_map(|range| {
            let start = range.field_start_char.max(field_start_char);
            let end = range.field_end_char_exclusive.min(field_end_char_exclusive);
            (start < end).then_some(ViewCharRange {
                view_start_char: start - field_start_char,
                view_end_char_exclusive: end - field_start_char,
            })
        })
        .collect::<Vec<_>>();
    let matched_chars_shown = shown
        .iter()
        .map(|range| range.view_end_char_exclusive - range.view_start_char)
        .sum();
    MessageMatchEvidence {
        view_text: selected
            .chars()
            .skip(field_start_char)
            .take(field_end_char_exclusive - field_start_char)
            .collect(),
        field_start_char,
        field_total_chars,
        markers: MessageMatchViewMarkers::Characters {
            ranges: shown,
            matched_chars_total,
            matched_chars_shown,
        },
    }
}

fn densest_excerpt_start(
    ranges: &[FieldCharRange],
    maximum: usize,
    field_total_chars: usize,
) -> usize {
    let indices = ranges
        .iter()
        .flat_map(|range| range.field_start_char..range.field_end_char_exclusive)
        .collect::<Vec<_>>();
    let mut best = (0, 0);
    let mut right = 0;
    for left in 0..indices.len() {
        while right < indices.len() && indices[right] < indices[left] + maximum {
            right += 1;
        }
        let candidate = (right - left, indices[left].min(field_total_chars - maximum));
        if candidate.0 > best.0 || (candidate.0 == best.0 && candidate.1 < best.1) {
            best = candidate;
        }
    }
    best.1
}

fn boundary_evidence(
    selected: &str,
    field_total_chars: usize,
    maximum: usize,
    boundary: usize,
) -> MessageMatchEvidence {
    let field_start_char = boundary
        .saturating_sub(maximum / 2)
        .min(field_total_chars.saturating_sub(maximum));
    let field_end_char_exclusive = (field_start_char + maximum).min(field_total_chars);
    MessageMatchEvidence {
        view_text: selected
            .chars()
            .skip(field_start_char)
            .take(field_end_char_exclusive - field_start_char)
            .collect(),
        field_start_char,
        field_total_chars,
        markers: MessageMatchViewMarkers::Boundary {
            view_at_char: boundary - field_start_char,
        },
    }
}

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

    fn hit(content: impl Into<String>) -> crate::models::MessageHit {
        crate::models::MessageHit {
            session_id: "claude:evidence".into(),
            provider: Provider::Claude,
            seq: 7,
            role: Role::Tool,
            kind: MessageKind::ToolCall,
            ts: None,
            tool_name: Some("exec_command".into()),
            tool_call_id: Some("tool-7".into()),
            fuzzy_score: None,
            content: content.into(),
        }
    }

    #[test]
    fn query_and_target_constructors_validate_input() {
        assert_eq!(
            MessageQuery::literal("").unwrap_err().code(),
            "invalid-query"
        );
        assert_eq!(
            MessageQuery::regex("[").unwrap_err().code(),
            "invalid-query"
        );
        assert_eq!(
            MessageQuery::fuzzy("ab").unwrap_err().code(),
            "invalid-query"
        );
        assert!(MessageQuery::fuzzy("a🦀b").is_ok());
        assert!(MessageTarget::tool_argument("").is_ok());
        assert!(MessageTarget::tool_argument("/request/path").is_ok());
        assert_eq!(
            MessageTarget::tool_argument("request/path")
                .unwrap_err()
                .code(),
            "invalid-json-pointer"
        );
        assert!(MessageTarget::tool_argument("/~0key/~1path").is_ok());
        assert!(MessageTarget::tool_argument("/~bad").is_err());
        assert_eq!(
            MessageQuery::fuzzy(" \t\n").unwrap_err().code(),
            "invalid-query"
        );
    }

    #[test]
    fn builder_rejects_cross_field_conflicts() {
        let sequence = SequenceRange::new(Some(1), Some(2)).unwrap();
        let error = MessageSearchRequest::builder(
            MessageQuery::literal("needle").unwrap(),
            MessageTarget::content(),
        )
        .sequence(sequence)
        .build()
        .unwrap_err();
        assert_eq!(error.code(), "parameter-conflict");

        let error = MessageSearchRequest::builder(
            MessageQuery::All,
            MessageTarget::tool_argument("/cmd").unwrap(),
        )
        .kind(MessageKind::Conversation)
        .build()
        .unwrap_err();
        assert_eq!(error.code(), "parameter-conflict");

        let error = MessageSearchRequest::builder(
            MessageQuery::literal("needle").unwrap(),
            MessageTarget::content(),
        )
        .role(Role::Compaction)
        .include_compaction(false)
        .build()
        .unwrap_err();
        assert_eq!(error.code(), "parameter-conflict");

        let error = MessageSearchRequest::builder(MessageQuery::All, MessageTarget::content())
            .match_view(MatchViewBudget::max_chars(20).unwrap())
            .build()
            .unwrap_err();
        assert!(error.to_string().contains("requires a literal"));
    }

    #[test]
    fn selected_tool_argument_evidence_exposes_a_match_beyond_raw_boundaries() {
        let command = format!("{}Trash{}", "x".repeat(855), "y".repeat(400));
        let content = serde_json::json!({"args": {"command": command}}).to_string();
        let evidence = attach_match_evidence(
            &MessageQuery::literal("trash").unwrap(),
            &MessageTarget::tool_argument("/command").unwrap(),
            MatchViewBudget::MaxChars {
                max_chars: NonZeroUsize::new(40).unwrap(),
            },
            vec![hit(content)],
        )
        .unwrap();

        let evidence = evidence[0].match_evidence().unwrap();
        assert!(evidence.view_text.to_lowercase().contains("trash"));
        assert!(evidence.field_start_char > 220);
        assert_eq!(evidence.view_text.chars().count(), 40);
        assert_eq!(evidence.field_total_chars, 1_260);
    }

    #[test]
    fn batch_enrichment_checks_cancellation_between_hits_and_phases() {
        let query = MessageQuery::literal("needle").unwrap();
        let target = MessageTarget::content();
        let source_hits = vec![hit("needle zero"), hit("needle one"), hit("needle two")];
        let mut evidence_checks = 0;
        let evidence_error = attach_match_evidence_cancellable(
            &query,
            &target,
            MatchViewBudget::MinimalSpan,
            source_hits.clone(),
            || {
                evidence_checks += 1;
                anyhow::ensure!(evidence_checks < 3, "injected evidence cancellation");
                Ok(())
            },
        )
        .unwrap_err();
        assert_eq!(evidence_checks, 3);
        assert!(evidence_error
            .to_string()
            .contains("injected evidence cancellation"));

        let mut hits =
            attach_match_evidence(&query, &target, MatchViewBudget::MinimalSpan, source_hits)
                .unwrap();
        let presentation = ResolvedMessagePresentation {
            include_refs: false,
            message_lines: LineWindow::Full,
            match_evidence_max_chars: NonZeroUsize::new(32).unwrap(),
            detail: None,
            field_view: FieldViewBudget::NoCharLimit,
            match_view: MatchViewBudget::MinimalSpan,
        };
        let mut presentation_checks = 0;
        let presentation_error =
            apply_message_presentation_cancellable(&target, presentation, &mut hits, || {
                presentation_checks += 1;
                anyhow::ensure!(
                    presentation_checks < 3,
                    "injected presentation cancellation"
                );
                Ok(())
            })
            .unwrap_err();
        assert_eq!(presentation_checks, 3);
        assert!(presentation_error
            .to_string()
            .contains("injected presentation cancellation"));
    }

    #[test]
    fn long_literal_keeps_complete_field_occurrence_beside_bounded_evidence() {
        let literal = "Needle".repeat(80);
        let content = format!("prefix {literal} suffix");
        let hits = attach_match_evidence(
            &MessageQuery::literal(literal.to_lowercase()).unwrap(),
            &MessageTarget::content(),
            MatchViewBudget::MaxChars {
                max_chars: NonZeroUsize::new(40).unwrap(),
            },
            vec![hit(content)],
        )
        .unwrap();

        let hit = &hits[0];
        assert_eq!(hit.match_evidence().unwrap().view_text.chars().count(), 40);
        let occurrence = hit.literal_match().expect("literal field occurrence");
        assert_eq!(occurrence.text, literal);
        assert_eq!(occurrence.field_start_char, 7);
        assert_eq!(
            occurrence.field_end_char_exclusive,
            7 + literal.chars().count()
        );
    }

    #[test]
    fn minimal_match_view_contains_the_entire_literal_regex_or_fuzzy_span() {
        let literal = "Needle".repeat(80);
        let content = format!("prefix {literal} suffix");
        for query in [
            MessageQuery::literal(literal.to_lowercase()).unwrap(),
            MessageQuery::regex(r"(?:Needle){80}").unwrap(),
        ] {
            let hits = attach_match_evidence(
                &query,
                &MessageTarget::content(),
                MatchViewBudget::MinimalSpan,
                vec![hit(content.clone())],
            )
            .unwrap();
            assert_eq!(hits[0].match_evidence().unwrap().view_text, literal);
        }

        let fuzzy = attach_match_evidence(
            &MessageQuery::fuzzy("tst").unwrap(),
            &MessageTarget::content(),
            MatchViewBudget::MinimalSpan,
            vec![hit("prefix test suffix")],
        )
        .unwrap();
        assert_eq!(fuzzy[0].match_evidence().unwrap().view_text, "test");

        let boundary = attach_match_evidence(
            &MessageQuery::regex(r"(?m)^").unwrap(),
            &MessageTarget::content(),
            MatchViewBudget::MinimalSpan,
            vec![hit("line")],
        )
        .unwrap();
        assert_eq!(boundary[0].match_evidence().unwrap().view_text, "");
    }

    #[test]
    fn field_view_range_extent_and_count_cover_full_start_end_middle_and_unicode() {
        let full =
            selected_field_view("aé🙂", LineWindow::Full, FieldViewBudget::NoCharLimit, None)
                .unwrap();
        assert_eq!(full.text(), "aé🙂");
        assert_eq!(
            (full.field_start_char(), full.field_end_char_exclusive()),
            (0, 3)
        );
        assert_eq!(
            full.extent().additional_field_text(),
            AdditionalFieldText::None
        );
        assert_eq!(full.extent().field_total_chars(), Some(3));

        let start = selected_field_view(
            "alpha\nbeta",
            LineWindow::Head(NonZeroUsize::new(1).unwrap()),
            FieldViewBudget::NoCharLimit,
            None,
        )
        .unwrap();
        assert_eq!(start.text(), "alpha");
        assert_eq!(
            (start.field_start_char(), start.field_end_char_exclusive()),
            (0, 5)
        );
        assert_eq!(
            start.extent().additional_field_text(),
            AdditionalFieldText::After
        );
        assert_eq!(start.extent().field_total_chars(), None);

        let end = selected_field_view(
            "alpha\nbeta",
            LineWindow::Tail(NonZeroUsize::new(1).unwrap()),
            FieldViewBudget::NoCharLimit,
            None,
        )
        .unwrap();
        assert_eq!(end.text(), "beta");
        assert_eq!(
            (end.field_start_char(), end.field_end_char_exclusive()),
            (6, 10)
        );
        assert_eq!(
            end.extent().additional_field_text(),
            AdditionalFieldText::Before
        );
        assert_eq!(end.extent().field_total_chars(), None);

        let middle = evidence_field_view(&MessageMatchEvidence {
            view_text: "cd".into(),
            field_start_char: 2,
            field_total_chars: 6,
            markers: MessageMatchViewMarkers::Characters {
                ranges: vec![ViewCharRange {
                    view_start_char: 0,
                    view_end_char_exclusive: 2,
                }],
                matched_chars_total: 2,
                matched_chars_shown: 2,
            },
        });
        assert_eq!(
            (middle.field_start_char(), middle.field_end_char_exclusive()),
            (2, 4)
        );
        assert_eq!(
            middle.extent().additional_field_text(),
            AdditionalFieldText::BeforeAndAfter
        );
        assert_eq!(middle.extent().field_total_chars(), Some(6));

        let empty =
            selected_field_view("", LineWindow::Full, FieldViewBudget::NoCharLimit, None).unwrap();
        assert_eq!(
            (empty.field_start_char(), empty.field_end_char_exclusive()),
            (0, 0)
        );
        assert_eq!(
            empty.extent().additional_field_text(),
            AdditionalFieldText::None
        );
        assert_eq!(empty.extent().field_total_chars(), Some(0));

        for view in [&full, &start, &end, &middle, &empty] {
            assert_eq!(
                view.field_end_char_exclusive() - view.field_start_char(),
                view.text().chars().count(),
                "absolute field range must equal returned Unicode scalar count"
            );
        }
    }

    #[test]
    fn content_extent_uses_absolute_ranges_and_one_additional_text_direction() {
        let original = "alpha\nbeta\ngamma";
        let cases = [
            (
                LineWindow::Full,
                FieldViewBudget::NoCharLimit,
                "alpha\nbeta\ngamma",
                0,
                16,
                "none",
                Some(16),
            ),
            (
                LineWindow::Head(NonZeroUsize::new(1).unwrap()),
                FieldViewBudget::NoCharLimit,
                "alpha",
                0,
                5,
                "after",
                None,
            ),
            (
                LineWindow::Tail(NonZeroUsize::new(1).unwrap()),
                FieldViewBudget::NoCharLimit,
                "gamma",
                11,
                16,
                "before",
                None,
            ),
            (
                LineWindow::Full,
                FieldViewBudget::max_chars(6).unwrap(),
                "alpha\n",
                0,
                6,
                "after",
                None,
            ),
        ];
        for (lines, budget, text, start, end, additional, total) in cases {
            let view = selected_field_view(original, lines, budget, None).unwrap();
            let (actual_text, extent) = view.into_content_and_extent();
            let extent = serde_json::to_value(extent).unwrap();
            assert_eq!(actual_text, text);
            assert_eq!(extent["field_start_char"], start);
            assert_eq!(extent["field_end_char_exclusive"], end);
            assert_eq!(extent["additional_field_text"], additional);
            assert_eq!(extent["field_total_chars"], serde_json::json!(total));
            // This shape is serialized into get_session, which has no shared root to hoist to,
            // so it keeps the unit. The search response's views do not.
            assert_eq!(extent["coordinate_unit"], "unicode_scalar");
            for rejected in [
                "complete",
                "omitted_start",
                "omitted_end",
                "returned_chars",
                "original_chars",
            ] {
                assert!(
                    extent.get(rejected).is_none(),
                    "{rejected} leaked: {extent}"
                );
            }
        }

        let trailing_newline = selected_field_view(
            "alpha\nbeta\n",
            LineWindow::Tail(NonZeroUsize::new(1).unwrap()),
            FieldViewBudget::NoCharLimit,
            None,
        )
        .unwrap();
        let (text, extent) = trailing_newline.into_content_and_extent();
        let extent = serde_json::to_value(extent).unwrap();
        assert_eq!(text, "beta");
        assert_eq!(extent["field_start_char"], 6);
        assert_eq!(extent["field_end_char_exclusive"], 10);
        assert_eq!(extent["additional_field_text"], "before_and_after");
    }

    #[test]
    fn regex_zero_width_and_fuzzy_matches_have_typed_markers() {
        let regex = attach_match_evidence(
            &MessageQuery::regex(r"(?m)^").unwrap(),
            &MessageTarget::content(),
            MatchViewBudget::MaxChars {
                max_chars: NonZeroUsize::new(8).unwrap(),
            },
            vec![hit("abcdefghijk")],
        )
        .unwrap();
        assert!(matches!(
            regex[0].match_evidence().unwrap().markers,
            MessageMatchViewMarkers::Boundary { view_at_char: 0 }
        ));

        let fuzzy = attach_match_evidence(
            &MessageQuery::fuzzy("tst").unwrap(),
            &MessageTarget::content(),
            MatchViewBudget::MaxChars {
                max_chars: NonZeroUsize::new(12).unwrap(),
            },
            vec![hit("prefix test suffix")],
        )
        .unwrap();
        let evidence = fuzzy[0].match_evidence().unwrap();
        assert!(matches!(
            evidence.markers,
            MessageMatchViewMarkers::Characters {
                matched_chars_total: 3,
                matched_chars_shown: 3,
                ..
            }
        ));
    }

    #[test]
    fn fuzzy_grapheme_indices_map_to_complete_scalar_ranges() {
        for (selected, expected) in [
            (
                "e\u{301} prefix test",
                vec![
                    ViewCharRange {
                        view_start_char: 10,
                        view_end_char_exclusive: 11,
                    },
                    ViewCharRange {
                        view_start_char: 12,
                        view_end_char_exclusive: 14,
                    },
                ],
            ),
            (
                "é e\u{301} prefix test",
                vec![
                    ViewCharRange {
                        view_start_char: 12,
                        view_end_char_exclusive: 13,
                    },
                    ViewCharRange {
                        view_start_char: 14,
                        view_end_char_exclusive: 16,
                    },
                ],
            ),
            (
                "👩‍💻 test",
                vec![
                    ViewCharRange {
                        view_start_char: 4,
                        view_end_char_exclusive: 5,
                    },
                    ViewCharRange {
                        view_start_char: 6,
                        view_end_char_exclusive: 8,
                    },
                ],
            ),
        ] {
            let fuzzy = attach_match_evidence(
                &MessageQuery::fuzzy("tst").unwrap(),
                &MessageTarget::content(),
                MatchViewBudget::MaxChars {
                    max_chars: NonZeroUsize::new(30).unwrap(),
                },
                vec![hit(selected)],
            )
            .unwrap();
            let MessageMatchViewMarkers::Characters { ranges, .. } =
                &fuzzy[0].match_evidence().unwrap().markers
            else {
                panic!("fuzzy evidence must use character ranges");
            };
            assert_eq!(ranges, &expected);
        }
    }

    #[test]
    fn queryless_hits_omit_evidence_without_projecting_selected_fields() {
        let hits = attach_match_evidence(
            &MessageQuery::All,
            &MessageTarget::tool_argument("/missing").unwrap(),
            MatchViewBudget::MaxChars {
                max_chars: NonZeroUsize::new(20).unwrap(),
            },
            vec![hit("not-json")],
        )
        .unwrap();
        assert!(hits[0].match_evidence().is_none());
    }

    #[test]
    fn fuzzy_extent_and_latest_window_rules_are_explicit() {
        let fuzzy = MessageQuery::fuzzy("needle").unwrap();
        assert!(
            MessageSearchRequest::builder(fuzzy.clone(), MessageTarget::content())
                .build()
                .is_ok()
        );
        assert!(
            MessageSearchRequest::builder(fuzzy.clone(), MessageTarget::content())
                .extent(RequestedExtent::page(Some(10), 1).unwrap())
                .build()
                .is_ok(),
            "deterministically ranked fuzzy results support numeric offset pages"
        );
        assert!(
            MessageSearchRequest::builder(fuzzy, MessageTarget::content())
                .extent(RequestedExtent::page(Some(10), 0).unwrap())
                .build()
                .is_ok()
        );

        let latest = MessageSearchRequest::builder(
            MessageQuery::regex("needle").unwrap(),
            MessageTarget::content(),
        )
        .match_window(MatchWindow::Latest)
        .build()
        .unwrap_err();
        assert!(latest.to_string().contains("requires one session"));

        assert!(
            MessageSearchRequest::builder(MessageQuery::All, MessageTarget::content())
                .session_id("claude:session")
                .unwrap()
                .match_window(MatchWindow::Latest)
                .build()
                .is_ok()
        );
    }

    #[test]
    fn provider_sets_are_non_empty_deduplicated_and_canonically_ordered() {
        let empty = MessageSearchRequest::builder(
            MessageQuery::literal("needle").unwrap(),
            MessageTarget::content(),
        )
        .providers(Vec::new())
        .err()
        .expect("an empty provider set must fail");
        assert!(empty.to_string().contains("providers"), "{empty}");
        assert!(empty.to_string().contains("at least one"), "{empty}");

        let request = MessageSearchRequest::builder(
            MessageQuery::literal("needle").unwrap(),
            MessageTarget::content(),
        )
        .providers(vec![
            Provider::Codex,
            Provider::Claude,
            Provider::Codex,
            Provider::GeminiCli,
        ])
        .unwrap()
        .build()
        .unwrap();
        assert_eq!(
            request.predicates().providers(),
            Some([Provider::Claude, Provider::Codex, Provider::GeminiCli].as_slice())
        );
    }

    #[test]
    fn signed_line_window_preserves_full_head_and_tail() {
        assert_eq!(LineWindow::from_signed(0).unwrap(), LineWindow::Full);
        assert_eq!(LineWindow::from_signed(3).unwrap().to_signed().unwrap(), 3);
        assert_eq!(
            LineWindow::from_signed(-3).unwrap().to_signed().unwrap(),
            -3
        );
        assert!(LineWindow::from_signed(i64::MIN).is_err());
    }

    #[test]
    fn complete_valid_request_preserves_every_orthogonal_concept() {
        let time = RequestedTimeRange::new(
            Some(Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()),
            Some(Utc.with_ymd_and_hms(2026, 7, 22, 0, 0, 0).unwrap()),
        )
        .unwrap();
        let request = MessageSearchRequest::builder(
            MessageQuery::literal("cargo test").unwrap(),
            MessageTarget::tool_argument("/cmd").unwrap(),
        )
        .role(Role::Tool)
        .kind(MessageKind::ToolCall)
        .provider(Provider::Claude)
        .session_id("claude:session")
        .unwrap()
        .workspace_path_prefix("/workspace")
        .unwrap()
        .transcript_path_prefix("/transcripts")
        .unwrap()
        .exclude_workspace_path_prefix("/workspace/vendor")
        .unwrap()
        .exclude_transcript_path_prefix("/transcripts/archive")
        .unwrap()
        .exclude_session_id("claude:excluded")
        .unwrap()
        .time(time)
        .sequence(SequenceRange::new(Some(2), Some(8)).unwrap())
        .tool_name_contains("exec")
        .unwrap()
        .include_compaction(true)
        .match_window(MatchWindow::Latest)
        .context(ContextWindow::new(1, 3))
        .includes([MessageSearchInclude::ParsedReferences])
        .message_lines(LineWindow::from_signed(-8).unwrap())
        .extent(RequestedExtent::page(Some(25), 5).unwrap())
        .purpose(PurposeSelection::new("historical-audit", NonZeroU32::new(2)).unwrap())
        .receipt_level(ReceiptLevel::Full)
        .build()
        .unwrap();

        assert_eq!(request.query().text(), Some("cargo test"));
        assert_eq!(request.target().field(), SearchField::ToolArgument);
        assert_eq!(
            request.target().argument_path().map(JsonPointer::as_str),
            Some("/cmd")
        );
        assert_eq!(request.predicates().session(), Some("claude:session"));
        assert_eq!(request.predicates().sequence().unwrap().from(), Some(2));
        assert_eq!(request.context(), Some(ContextWindow::new(1, 3)));
        assert_eq!(
            request.includes(),
            Some([MessageSearchInclude::ParsedReferences].as_slice())
        );
        assert_eq!(request.match_window(), Some(MatchWindow::Latest));
        assert_eq!(request.receipt_level(), Some(ReceiptLevel::Full));
        assert_eq!(request.purpose().unwrap().name(), "historical-audit");
    }

    #[test]
    fn range_extent_and_purpose_failures_have_stable_codes() {
        assert_eq!(
            RequestedExtent::page(Some(0), 0).unwrap_err().code(),
            "invalid-parameter"
        );
        assert_eq!(
            SequenceRange::new(Some(2), Some(1)).unwrap_err().code(),
            "invalid-parameter"
        );
        assert_eq!(
            RequestedTimeRange::new(
                Some(Utc.with_ymd_and_hms(2026, 7, 2, 0, 0, 0).unwrap()),
                Some(Utc.with_ymd_and_hms(2026, 7, 1, 0, 0, 0).unwrap()),
            )
            .unwrap_err()
            .code(),
            "invalid-parameter"
        );
        assert_eq!(
            PurposeSelection::new("hard2parse", None)
                .unwrap_err()
                .code(),
            "invalid-parameter"
        );
    }

    #[test]
    fn registered_rules_reject_the_named_parameter_combinations() {
        let literal = || {
            MessageSearchRequest::builder(
                MessageQuery::literal("needle").unwrap(),
                MessageTarget::content(),
            )
        };
        let cases = [
            (
                MessageSearchRule::DetailOwnsPresentationBudgets,
                literal()
                    .detail(DetailLevel::Full)
                    .message_lines(LineWindow::Full)
                    .build(),
            ),
            (
                MessageSearchRule::SequenceRequiresSession,
                literal()
                    .sequence(SequenceRange::new(Some(1), None).unwrap())
                    .build(),
            ),
            (
                MessageSearchRule::KindsMustRemainSatisfiable,
                literal().kinds(Vec::new()).build(),
            ),
            (
                MessageSearchRule::CompactionRoleRequiresCompactionKind,
                literal()
                    .role(Role::Compaction)
                    .kinds(vec![MessageKind::Conversation])
                    .build(),
            ),
            (
                MessageSearchRule::ToolArgumentRequiresToolCallKind,
                MessageSearchRequest::builder(
                    MessageQuery::literal("needle").unwrap(),
                    MessageTarget::tool_argument("/cmd").unwrap(),
                )
                .kinds(vec![MessageKind::Conversation])
                .build(),
            ),
            (
                MessageSearchRule::MatchViewRequiresQuery,
                MessageSearchRequest::builder(MessageQuery::All, MessageTarget::content())
                    .match_view(MatchViewBudget::MinimalSpan)
                    .build(),
            ),
            (
                MessageSearchRule::FuzzyRejectsMatchWindow,
                MessageSearchRequest::builder(
                    MessageQuery::fuzzy("needle").unwrap(),
                    MessageTarget::content(),
                )
                .match_window(MatchWindow::Earliest)
                .extent(RequestedExtent::page(Some(1), 0).unwrap())
                .build(),
            ),
            (
                MessageSearchRule::LatestWindowRequiresSession,
                literal().match_window(MatchWindow::Latest).build(),
            ),
            (
                MessageSearchRule::FuzzyRejectsAllResults,
                MessageSearchRequest::builder(
                    MessageQuery::fuzzy("needle").unwrap(),
                    MessageTarget::content(),
                )
                .extent(RequestedExtent::all_results())
                .build(),
            ),
        ];

        assert_eq!(
            MessageSearchParameterRegistry::current().rules(),
            MessageSearchRule::ALL
        );
        for (rule, result) in cases {
            let error = result.unwrap_err();
            assert_eq!(error.code(), "parameter-conflict");
            assert!(
                error.to_string().contains(rule.as_str()),
                "{} must identify executable rule {}",
                error,
                rule.as_str()
            );
            assert!(error.to_string().contains(rule.message()));
        }
    }

    #[test]
    fn parameter_registry_derives_closed_vocabularies_and_names_surface_availability() {
        fn serialized_variants<T>() -> Vec<String>
        where
            T: clap::ValueEnum + Copy + Serialize + 'static,
        {
            T::value_variants()
                .iter()
                .map(|value| {
                    serde_json::to_value(*value)
                        .unwrap()
                        .as_str()
                        .unwrap()
                        .to_owned()
                })
                .collect()
        }

        let registry = MessageSearchParameterRegistry::current();
        for (parameter, expected) in [
            (
                MessageSearchParameter::QueryMode,
                serialized_variants::<MessageSearchMode>(),
            ),
            (
                MessageSearchParameter::Field,
                serialized_variants::<SearchField>(),
            ),
            (MessageSearchParameter::Role, serialized_variants::<Role>()),
            (
                MessageSearchParameter::Kinds,
                serialized_variants::<MessageKind>(),
            ),
            (
                MessageSearchParameter::MatchWindow,
                serialized_variants::<MatchWindow>(),
            ),
            (
                MessageSearchParameter::Detail,
                serialized_variants::<DetailLevel>(),
            ),
            (
                MessageSearchParameter::Include,
                serialized_variants::<MessageSearchInclude>(),
            ),
            (
                MessageSearchParameter::ReceiptLevel,
                serialized_variants::<ReceiptLevel>(),
            ),
        ] {
            assert_eq!(
                registry
                    .parameter(parameter)
                    .unwrap_or_else(|| panic!("missing registry parameter {}", parameter.as_str()))
                    .accepted_values(),
                expected,
                "{} must derive its vocabulary from the executable enum",
                parameter.as_str()
            );
        }
        assert_eq!(
            registry
                .parameter(MessageSearchParameter::Providers)
                .unwrap()
                .accepted_values(),
            crate::source::PROVIDERS
                .iter()
                .map(|provider| provider.as_str().to_owned())
                .collect::<Vec<_>>(),
            "provider vocabulary and canonical order must come from source::PROVIDERS"
        );
        assert_eq!(
            registry
                .parameter(MessageSearchParameter::Query)
                .unwrap()
                .domain(),
            &MessageSearchParameterDomain::Text { non_empty: false },
            "empty is the cross-surface queryless-search spelling and must not be advertised as invalid"
        );
        assert_eq!(
            registry
                .parameter(MessageSearchParameter::Detail)
                .unwrap()
                .surfaces(),
            SearchSurface::ALL,
            "the finalized registry must not freeze provisional CLI/Python presentation gaps"
        );
        assert_eq!(registry.rule_descriptors().len(), registry.rules().len());
        for (descriptor, rule) in registry.rule_descriptors().iter().zip(registry.rules()) {
            assert_eq!(descriptor.rule(), *rule);
            assert_eq!(descriptor.message(), rule.message());
        }
    }
}