mx 0.1.232

A Swiss army knife for Claude Code and multi-agent toolkits
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
//! Trigger-based ambient memory: the pure logic behind `mx doors`.
//!
//! A *door* is any kv entry carrying a `triggers` list. When one of its trigger
//! phrases appears in a prompt, the door opens: a one-line fragment plus a
//! pointer to where the full fact lives. The fragment is the whole payload —
//! nothing is resolved, nothing is fetched, no graph is touched. Digging is a
//! separate, deliberate `mx kv get` the reader chooses to run.
//!
//! Everything here is IO-free so it can be tested exhaustively. The store reads,
//! the fire log and stdout live in `handlers::doors`.

mod classify;
mod route;
mod session;

use std::collections::{HashMap, HashSet};

use serde::{Deserialize, Serialize};

pub use classify::{Classified, NamesUs, Verdict, classify};
pub use route::{Mode, Places, Pool, ScopeValue};
pub use session::{
    Hint, SESSION_KEY, SessionRow, SessionState, foreign_paste, hints, session_state,
};

use crate::kv::TriggeredRef;
use crate::triggers;

/// Distinct entries allowed to fire on a single prompt. Overflow is not
/// recorded, so a deferred door stays eligible on the next prompt.
pub const DEFAULT_BUDGET: usize = 2;

/// Longest derived fragment, in Unicode scalar values, before it is cut. An
/// authored `fragment` is printed verbatim and is never subject to this.
const DERIVED_FRAGMENT_MAX: usize = 200;

/// The kv key holding the fire log. It is both the dedup table and the
/// telemetry source: one row per (session, key, entry) fire.
pub const FIRED_KEY: &str = "doors_fired";

/// The subset of the Claude Code UserPromptSubmit payload doors reads.
///
/// Every other field is ignored rather than rejected — the hook must survive a
/// payload that grows new keys.
#[derive(Debug, Deserialize)]
pub struct HookInput {
    #[serde(default, deserialize_with = "lenient_string")]
    pub session_id: String,
    #[serde(default, deserialize_with = "lenient_string")]
    pub prompt: String,
}

/// Accept a JSON string, number, or null where a string is expected.
///
/// Claude Code sends `session_id` as a string today. If that ever arrives as a
/// number, a strict `String` field would fail the WHOLE payload and the hook
/// would go silent for that prompt with no door and no clue why. Coercing is
/// strictly better than losing the turn: a numeric id still dedups correctly,
/// it just stringifies first.
fn lenient_string<'de, D>(d: D) -> Result<String, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(match serde_json::Value::deserialize(d)? {
        serde_json::Value::String(s) => s,
        serde_json::Value::Null => String::new(),
        other => other.to_string(),
    })
}

/// One door that opened.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FiredDoor {
    pub key: String,
    pub id: String,
    pub trigger: String,
    pub fragment: String,
    pub dig: String,
    /// Where the matching text came from: `typed`, `paste` or `channel`.
    pub origin: &'static str,
    /// The place it opened through: `house`, `book:<slug>`, or `pinned`.
    /// Empty for a held door, which opened through nothing.
    pub place: String,
}

impl FiredDoor {
    /// The stdout line Claude Code injects as context.
    pub fn render(&self) -> String {
        format!(
            "\u{1f6aa} {} \u{2192} {} (dig: {})",
            self.trigger, self.fragment, self.dig
        )
    }
}

/// What one prompt produced: the doors that fired and how many matched but lost
/// the budget.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Selection {
    pub fired: Vec<FiredDoor>,
    pub deferred: usize,
}

/// Remove `<channel ...>` opening tags and `</channel>` closing tags, keeping
/// the body text between them.
///
/// Matrix messages reach the hook wrapped in a channel block whose ATTRIBUTES
/// carry the sender's identity: `user="tester"`, `room_name="delta"`. Left in
/// place, a `tester` door would fire on every message in that room regardless of
/// what was said. The body is what a person actually wrote, so it is the only
/// part that may open a door.
///
/// The scan is quote-aware: an unbalanced `>` inside an attribute value does not
/// end the tag.
pub fn strip_channel_tags(prompt: &str) -> String {
    let mut out = String::with_capacity(prompt.len());
    let mut i = 0;
    while i < prompt.len() {
        let rest = &prompt[i..];
        if let Some(after) = rest.strip_prefix("</channel>") {
            out.push(' ');
            i += rest.len() - after.len();
            continue;
        }
        if is_channel_opener(rest) {
            if let Some(end) = channel_tag_end(prompt, i) {
                out.push(' ');
                i = end;
                continue;
            }
            // No closing bracket: this is not a real channel tag (a stray
            // "<channel" someone typed, or an unbalanced quote). Swallowing to
            // end-of-string would silently cost every door for the turn, so
            // treat the remainder as ordinary body text and stop stripping.
            out.push_str(rest);
            break;
        }
        let ch = rest.chars().next().unwrap();
        out.push(ch);
        i += ch.len_utf8();
    }
    out
}

const CHANNEL_OPEN: &str = "<channel";

fn is_channel_opener(s: &str) -> bool {
    s.strip_prefix(CHANNEL_OPEN)
        .and_then(|r| r.chars().next())
        .is_some_and(|c| c.is_whitespace() || c == '>')
}

/// End (one past `>`) of the channel opener starting at `at`, scanning
/// quote-aware so an unbalanced `>` inside an attribute value does not end the
/// tag. `None` when no unquoted `>` follows.
fn channel_tag_end(s: &str, at: usize) -> Option<usize> {
    let mut in_quote = false;
    for (j, b) in s.bytes().enumerate().skip(at + CHANNEL_OPEN.len()) {
        match b {
            b'"' => in_quote = !in_quote,
            b'>' if !in_quote => return Some(j + 1),
            _ => {}
        }
    }
    None
}

/// Harness block names matched exactly. `local-command-*` is handled apart
/// because its suffix varies.
const HARNESS_BLOCKS: [&str; 2] = ["task-notification", "system-reminder"];
const LOCAL_COMMAND_PREFIX: &str = "local-command-";

/// The harness tag name `s` begins with, if any. A `local-command-` name takes
/// the longest `[a-z0-9-]` suffix, so the caller's `>` check is what rejects
/// `local-command-stdoutX`.
fn harness_name(s: &str) -> Option<&str> {
    if let Some(name) = HARNESS_BLOCKS.into_iter().find(|n| s.starts_with(n)) {
        return Some(name);
    }
    let suffix = s.strip_prefix(LOCAL_COMMAND_PREFIX)?;
    let n = suffix
        .bytes()
        .take_while(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || *b == b'-')
        .count();
    (n > 0).then(|| &s[..LOCAL_COMMAND_PREFIX.len() + n])
}

enum TagKind {
    Open,
    SelfClosing,
    Close,
}

struct Tag<'a> {
    start: usize,
    end: usize,
    kind: TagKind,
    name: &'a str,
}

/// The bare harness tag at the start of `s`: exactly `<name>`, `<name/>` or
/// `</name>`. Attributes, whitespace and case variants are not harness tags.
fn bare_tag(s: &str) -> Option<(TagKind, &str, usize)> {
    let s = s.strip_prefix('<')?;
    let (closing, s) = match s.strip_prefix('/') {
        Some(s) => (true, s),
        None => (false, s),
    };
    let name = harness_name(s)?;
    let after = &s[name.len()..];
    let lead = 1 + usize::from(closing) + name.len();
    if after.starts_with('>') {
        let kind = if closing {
            TagKind::Close
        } else {
            TagKind::Open
        };
        Some((kind, name, lead + 1))
    } else if !closing && after.starts_with("/>") {
        Some((TagKind::SelfClosing, name, lead + 2))
    } else {
        None
    }
}

const PREAMBLE_HEADER: &str = "[SYSTEM NOTIFICATION";

/// A line that is a whole `[SYSTEM NOTIFICATION ...]` header: trimmed, it is
/// `[SYSTEM NOTIFICATION` followed by a space, `-` or `]`, it ends with `]`,
/// and it holds no `<`. A mention mid-sentence or with text after it is not one.
fn is_preamble_header(line: &str) -> bool {
    let line = line.trim();
    line.ends_with(']')
        && !line.contains('<')
        && line
            .strip_prefix(PREAMBLE_HEADER)
            .is_some_and(|rest| rest.starts_with([' ', '-', ']']))
}

/// Drop each notification preamble: its header line and the prose under it,
/// up to the first blank line or line holding a `<`. The harness writes these
/// above a `<task-notification>`; the human never typed them. A preamble with
/// no blank line under it ends with its paragraph, so it can never reach past
/// the next blank line, and it never eats a tag line such as a paste closer.
fn strip_notification_preambles(prompt: &str) -> std::borrow::Cow<'_, str> {
    if !prompt.contains(PREAMBLE_HEADER) {
        return std::borrow::Cow::Borrowed(prompt);
    }
    let mut out = String::with_capacity(prompt.len());
    let mut lines = prompt.split_inclusive('\n').peekable();
    while let Some(line) = lines.next() {
        if !is_preamble_header(line) {
            out.push_str(line);
            continue;
        }
        while lines
            .next_if(|l| !l.trim().is_empty() && !l.contains('<'))
            .is_some()
        {}
    }
    std::borrow::Cow::Owned(out)
}

/// Remove harness-injected blocks, body included: `<task-notification>`,
/// `<system-reminder>` and every `<local-command-*>` (closed by the same name).
///
/// Claude Code puts these in the prompt the hook receives, but the human never
/// typed them. A trigger word inside a subagent report or a CLI echo would open
/// a door, burn its per-session dedup slot and eat the prompt's budget.
/// A `[SYSTEM NOTIFICATION ...]` preamble above such a block goes first (see
/// `strip_notification_preambles`).
///
/// Only bare tags count (`<name>`, `<name/>`, `</name>`; the harness never
/// writes attributes). A tag quoted in markdown is literal text: an opener or
/// self-closing tag right after a backtick, or a closer right before one, is
/// left alone and takes no part in pairing, so a report saying
/// `` `<task-notification>` `` does not open a block. A closer pairs with the
/// latest unclosed opener of its name, in linear time. An opener nothing pairs
/// with (no closer after it, or displaced by a later opener of the same name)
/// and a stray closer each lose only the tag. Each removed block or tag becomes
/// one space, so the text on either side stays separate tokens.
///
/// Known edges: (1) a body that quotes a tag WITHOUT backticks can pair wrongly
/// and leak part of that block's text, and nested blocks of the same name leak
/// the outer block's text; (2) when the next unbackticked tag after an
/// unbackticked opener with the same name is a closer, the text between them
/// is removed whoever wrote them (unless the opener already sits inside an
/// earlier removed block), including when that closer is quoted inside a
/// different block.
pub fn strip_harness_blocks(prompt: &str) -> String {
    let prompt = &strip_notification_preambles(prompt);
    let bytes = prompt.as_bytes();
    let tags: Vec<Tag<'_>> = prompt
        .match_indices('<')
        .filter_map(|(start, _)| {
            let (kind, name, len) = bare_tag(&prompt[start..])?;
            let end = start + len;
            let quoted = match kind {
                TagKind::Open | TagKind::SelfClosing => start > 0 && bytes[start - 1] == b'`',
                TagKind::Close => bytes.get(end) == Some(&b'`'),
            };
            (!quoted).then_some(Tag {
                start,
                end,
                kind,
                name,
            })
        })
        .collect();

    // block_end[i]: where the block opened by tag i ends. A closer pairs with
    // the latest unclosed opener of its name; an earlier one it displaced
    // stays unpaired, so an opener quoted inside a block of its own name closes
    // no later than that block's closer.
    let mut block_end: Vec<Option<usize>> = vec![None; tags.len()];
    let mut open: HashMap<&str, usize> = HashMap::new();
    for (i, tag) in tags.iter().enumerate() {
        match tag.kind {
            TagKind::Open => {
                open.insert(tag.name, i);
            }
            TagKind::Close => {
                if let Some(o) = open.remove(tag.name) {
                    block_end[o] = Some(tag.end);
                }
            }
            TagKind::SelfClosing => {}
        }
    }

    let mut out = String::with_capacity(prompt.len());
    let mut pos = 0;
    for (i, tag) in tags.iter().enumerate() {
        if tag.start < pos {
            continue;
        }
        out.push_str(&prompt[pos..tag.start]);
        out.push(' ');
        pos = match tag.kind {
            TagKind::Open => block_end[i].unwrap_or(tag.end),
            TagKind::SelfClosing | TagKind::Close => tag.end,
        };
    }
    out.push_str(&prompt[pos..]);
    out
}

/// The one-line fragment for an entry.
///
/// An authored fragment is returned verbatim, however long. Otherwise the
/// entry's `value` up to its first newline, trimmed, cut at
/// `DERIVED_FRAGMENT_MAX` scalar values with an ellipsis. Cutting by `chars`
/// keeps the boundary valid, so a multi-byte character is never split.
pub fn derive_fragment(value: &str, fragment: Option<&str>) -> String {
    if let Some(f) = fragment {
        let f = f.trim();
        if !f.is_empty() {
            return f.to_string();
        }
    }
    let first_line = value.split('\n').next().unwrap_or("").trim();
    if first_line.chars().count() > DERIVED_FRAGMENT_MAX {
        let kept: String = first_line.chars().take(DERIVED_FRAGMENT_MAX - 1).collect();
        format!("{}\u{2026}", kept)
    } else {
        first_line.to_string()
    }
}

/// The pointer a reader follows to the full fact: always `<key>/kv-<id>`, plus
/// the kn- link when the entry carries one. Printed, never resolved.
pub fn dig_pointer(key: &str, id: &str, memory: Option<&str>) -> String {
    match memory {
        Some(m) if !m.trim().is_empty() => format!("{}/kv-{}, {}", key, id, m.trim()),
        _ => format!("{}/kv-{}", key, id),
    }
}

/// Shortest single-token trigger that is not flagged as dangerously broad.
const MIN_TRIGGER_TOKEN_CHARS: usize = 3;

/// What a trigger will actually match on, and whether that is a problem.
///
/// Matching tokenizes on runs of non-alphanumeric characters, so a name carrying
/// punctuation collapses in ways the author does not expect: `c++`, `c#` and
/// `F#` all match as the bare token `c` or `f`, and `🦊` matches as nothing at
/// all. A trigger that matches nothing is a dead door — it sits in the audit
/// view at `fires=0` forever and looks like a door nobody has said the word for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TriggerVerdict {
    /// No alphanumeric content survives tokenization; it can never fire.
    Dead,
    /// Fires, but as a single very short token, so it will fire constantly.
    Broad { matched_as: String },
    /// Fires as `matched_as`, which may still differ from what was typed.
    Fine { matched_as: String },
    /// Breaks a match-grammar rule; `rule` says which. Never stored.
    Invalid { rule: String },
    /// A `p + q` trigger with a side that is one very short token. The other
    /// sides narrow it, so this warns rather than calling the trigger broad.
    BroadSide { matched_as: String, side: String },
}

/// The token sequence a trigger actually matches on, space-joined. This is what
/// the reader should be shown, because it is what the matcher sees — `ayo-`
/// matches as `ayo`, and `gerf_slips` as `gerf slips`. A grammar trigger shows
/// its sides joined with ` + `, wildcards keeping their `*`.
pub fn matched_form(trigger: &str) -> String {
    match triggers::parse_grammar(trigger) {
        Ok(Some(g)) => g.form(),
        _ => triggers::tokens(trigger, false).join(" "),
    }
}

/// Judge an authored trigger before it is stored.
pub fn inspect_trigger(trigger: &str) -> TriggerVerdict {
    match triggers::parse_grammar(trigger) {
        Err(e) => {
            let one_word =
                crate::knowledge::normalize_trigger(trigger).is_some_and(|n| !n.contains(' '));
            return TriggerVerdict::Invalid {
                rule: e.rule(!one_word),
            };
        }
        Ok(Some(g)) => return inspect_grammar(&g),
        Ok(None) => {}
    }
    let toks = triggers::tokens(trigger, false);
    if toks.is_empty() {
        return TriggerVerdict::Dead;
    }
    let matched_as = toks.join(" ");
    if toks.len() == 1 && toks[0].chars().count() < MIN_TRIGGER_TOKEN_CHARS {
        TriggerVerdict::Broad { matched_as }
    } else {
        TriggerVerdict::Fine { matched_as }
    }
}

fn inspect_grammar(g: &triggers::Grammar) -> TriggerVerdict {
    let forms = g.side_forms();
    if let Some(dead) = g.sides.iter().position(Vec::is_empty) {
        return TriggerVerdict::Invalid {
            rule: format!(
                "has side {} with no letters or digits to match on, so it could never fire",
                dead + 1
            ),
        };
    }
    let matched_as = g.form();
    let broad = g.sides.iter().zip(&forms).find(|(side, _)| {
        matches!(side.as_slice(), [triggers::Pat::Exact(t)] if t.chars().count() < MIN_TRIGGER_TOKEN_CHARS)
    });
    match broad {
        Some((_, side)) => TriggerVerdict::BroadSide {
            matched_as,
            side: side.clone(),
        },
        None => TriggerVerdict::Fine { matched_as },
    }
}

/// Judge an authored exclusion: the phrase/wildcard grammar, no ` + `.
pub fn inspect_exclusion(exclusion: &str) -> TriggerVerdict {
    if crate::knowledge::normalize_trigger(exclusion)
        .is_some_and(|n| n.split(' ').any(|w| w == "+"))
    {
        return TriggerVerdict::Invalid {
            rule: "has ` + `: an exclusion is one phrase (give several with repeated --exclude)"
                .to_string(),
        };
    }
    inspect_trigger(exclusion)
}

/// The ` + ` spelling of a trigger that reads like an AND but is a phrase: a
/// `+` glued to one side of a word (`study +australia`). `c++` and `c++ tips`
/// are left alone because their `+` follows another `+`.
pub fn lopsided_plus(trigger: &str) -> Option<String> {
    let words: Vec<&str> = trigger.split_whitespace().collect();
    let last = words.len().checked_sub(1)?;
    let mut changed = false;
    let fixed: Vec<String> = words
        .iter()
        .enumerate()
        .map(|(n, w)| {
            let mut w = (*w).to_string();
            let lead = n > 0
                && words[n - 1] != "+"
                && w.strip_prefix('+')
                    .and_then(|r| r.chars().next())
                    .is_some_and(char::is_alphanumeric);
            if lead {
                w = format!("+ {}", &w[1..]);
                changed = true;
            }
            let trail = n < last
                && words[n + 1] != "+"
                && w.strip_suffix('+')
                    .and_then(|r| r.chars().next_back())
                    .is_some_and(char::is_alphanumeric);
            if trail {
                w = format!("{} +", &w[..w.len() - 1]);
                changed = true;
            }
            w
        })
        .collect();
    changed.then(|| fixed.join(" "))
}

/// How specific a trigger is: how many message tokens it spans, then how many
/// characters. A longer span is a more precise statement about the message. A
/// grammar trigger spans the tokens of all its sides.
fn specificity(trigger: &str) -> (usize, usize) {
    let span = match triggers::parse_grammar(trigger) {
        Ok(Some(g)) => g.span(),
        _ => triggers::tokens(trigger, false).len(),
    };
    (span, trigger.chars().count())
}

/// Who wrote a stretch of the prompt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Origin {
    /// Typed into the prompt, or anything not otherwise marked.
    Typed,
    /// A terminal paste Claude Code wrapped in a `<pasted_content>` block.
    Paste,
    /// The body of a `<channel>` block. Only `user_id` is kept: display names
    /// are spoofable.
    Channel { user_id: String },
}

impl Origin {
    pub fn label(&self) -> &'static str {
        match self {
            Origin::Typed => "typed",
            Origin::Paste => "paste",
            Origin::Channel { .. } => "channel",
        }
    }
}

/// One stretch of a prompt with a single origin. Phrases never match across
/// segments.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RawSegment {
    pub origin: Origin,
    pub text: String,
}

const PASTE_OPEN: &str = "<pasted_content id=\"";
const PASTE_CLOSE: &str = "</pasted_content id=\"";
const CHANNEL_CLOSE: &str = "</channel>";

/// The id and full length of the paste tag `prefix` starts `s` with:
/// `<pasted_content id="X">` or `</pasted_content id="X">`.
fn paste_tag<'a>(s: &'a str, prefix: &str) -> Option<(&'a str, usize)> {
    let rest = s.strip_prefix(prefix)?;
    let n = rest
        .bytes()
        .take_while(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'-'))
        .count();
    (n > 0 && rest[n..].starts_with("\">")).then(|| (&rest[..n], prefix.len() + n + 2))
}

/// The value of attribute `name` in a channel opener's attribute text.
fn channel_attr(attrs: &str, name: &str) -> Option<String> {
    let mut rest = attrs;
    loop {
        rest = rest.trim_start();
        let eq = rest.find('=')?;
        let key = rest[..eq].trim();
        let after = rest[eq + 1..].trim_start();
        let (value, tail) = match after.strip_prefix('"') {
            Some(q) => {
                let close = q.find('"')?;
                (&q[..close], &q[close + 1..])
            }
            None => {
                let end = after.find(char::is_whitespace).unwrap_or(after.len());
                (&after[..end], &after[end..])
            }
        };
        // A key with spaces before it was a bare word; only its last token is
        // the attribute name.
        if key.rsplit(char::is_whitespace).next() == Some(name) {
            return Some(value.to_string());
        }
        rest = tail;
    }
}

fn push_typed(out: &mut Vec<RawSegment>, text: &str) {
    let text = strip_channel_tags(text);
    if !text.trim().is_empty() {
        out.push(RawSegment {
            origin: Origin::Typed,
            text,
        });
    }
}

/// Cut a prompt (already through `strip_harness_blocks`) into typed text,
/// terminal pastes and channel bodies.
///
/// Scanning left to right, whichever block opener comes first defines a block,
/// and its body is opaque to the other kind. A paste opens at
/// `<pasted_content id="X">` and closes at the first later
/// `</pasted_content id="X">` with the same X; the newline just inside each tag
/// belongs to the envelope. Channel tags inside a paste body are stripped and
/// its text stays in the paste. A channel block opens at `<channel …>`, keeps
/// only `user_id`, and runs to the next `</channel>`; paste tags inside it are
/// plain body text. Attribute text never becomes match text, and
/// whitespace-only typed fragments are dropped.
///
/// Unterminated openers never swallow the turn: a paste opener nothing closes
/// is ordinary text, and a channel opener with no `>` before the next paste is
/// text, as is every channel opener after it until that paste.
///
/// Known edges:
/// - A channel opener with `>` but no `</channel>` labels the rest of the text
///   `channel`. Routing is `{house}` either way; only the origin in telemetry
///   differs.
/// - A paste body that contains its own session's closer (same id) closes
///   early there, and the remainder becomes typed text (admitted).
pub fn segment(prompt: &str) -> Vec<RawSegment> {
    let mut closers: HashMap<&str, Vec<(usize, usize)>> = HashMap::new();
    for (i, _) in prompt.match_indices(PASTE_CLOSE) {
        if let Some((id, len)) = paste_tag(&prompt[i..], PASTE_CLOSE) {
            closers.entry(id).or_default().push((i, i + len));
        }
    }
    // (body start, closer start, closer end) of a paste opening at `i`.
    let paste_at = |i: usize| {
        let (id, len) = paste_tag(&prompt[i..], PASTE_OPEN)?;
        let body_start = i + len;
        let v = closers.get(id)?;
        let &(close_start, close_end) = v.get(v.partition_point(|&(s, _)| s < body_start))?;
        Some((body_start, close_start, close_end))
    };

    let mut out = Vec::new();
    let mut pos = 0;
    let mut at = 0;
    let mut channels = true;
    while let Some(off) = prompt[at..].find('<') {
        let i = at + off;
        at = i + 1;
        if let Some((body_start, close_start, close_end)) = paste_at(i) {
            push_typed(&mut out, &prompt[pos..i]);
            let body = &prompt[body_start..close_start];
            let body = body.strip_prefix('\n').unwrap_or(body);
            let body = body.strip_suffix('\n').unwrap_or(body);
            out.push(RawSegment {
                origin: Origin::Paste,
                text: strip_channel_tags(body),
            });
            pos = close_end;
            at = close_end;
            channels = true;
        } else if channels && is_channel_opener(&prompt[i..]) {
            // An opener with no `>` of its own must not borrow one from a
            // later paste tag and swallow that paste into its attributes.
            let next_paste = prompt[i..]
                .match_indices(PASTE_OPEN)
                .map(|(o, _)| i + o)
                .find(|&j| paste_at(j).is_some())
                .unwrap_or(prompt.len());
            let Some(tag_end) = channel_tag_end(&prompt[..next_paste], i) else {
                channels = false;
                continue;
            };
            push_typed(&mut out, &prompt[pos..i]);
            let user_id = channel_attr(&prompt[i + CHANNEL_OPEN.len()..tag_end - 1], "user_id")
                .unwrap_or_default();
            let (body_end, next) = match prompt[tag_end..].find(CHANNEL_CLOSE) {
                Some(o) => (tag_end + o, tag_end + o + CHANNEL_CLOSE.len()),
                None => (prompt.len(), prompt.len()),
            };
            out.push(RawSegment {
                origin: Origin::Channel { user_id },
                text: strip_channel_tags(&prompt[tag_end..body_end]),
            });
            pos = next;
            at = next;
        }
    }
    push_typed(&mut out, &prompt[pos..]);
    out
}

/// A segment after routing has placed it.
#[derive(Debug, Clone, PartialEq)]
pub struct Segment {
    pub origin: Origin,
    pub text: String,
    /// The classifier's judgement. Only pastes are judged.
    pub classified: Option<Classified>,
    /// Where doors may open in it. `∅` admits only pinned doors.
    pub places: Places,
}

/// Places for typed text. In book mode the user is talking about the book, so
/// typed text opens book doors and holds house doors; pinned still fires
/// (decision D1, which overrides design §5's typed row).
fn typed_places(mode: &Mode) -> Places {
    match mode {
        Mode::Book(b) => Places::book(&b.slug),
        _ => Places::house(),
    }
}

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

    /// D1: typed text places `{book:<slug>}` in book mode, `{house}` otherwise.
    #[test]
    fn d1_typed_text_follows_the_book() {
        let book = Mode::parse("book:walden@3").unwrap();
        assert_eq!(typed_places(&book), Places::book("walden"));
        assert_eq!(typed_places(&Mode::House), Places::house());
        assert_eq!(typed_places(&Mode::Ours), Places::house());
    }
}

/// The places one segment opens doors in under `mode` (the routing table).
fn places_for(origin: &Origin, classified: Option<&Classified>, mode: &Mode) -> Places {
    match origin {
        // P3: `person:<owner>` joins typed places here, in every mode (`doors_people`).
        Origin::Typed => typed_places(mode),
        // P3: `person:<user_id>` or `house?` for channel bodies here.
        // A mode never touches a channel body.
        Origin::Channel { .. } => Places::house(),
        Origin::Paste => {
            let verdict = classified.map(|c| c.verdict);
            match mode {
                Mode::House if verdict == Some(Verdict::ForeignProse) => Places::none(),
                Mode::Book(b) if verdict != Some(Verdict::Ours) => Places::book(&b.slug),
                _ => Places::house(),
            }
        }
    }
}

/// Segment, classify and route a raw prompt under `mode`.
///
/// Only tagged pastes are judged. House mode quarantines a paste that reads as
/// someone else's prose; a book mode routes every paste but an Ours one to the
/// book; `ours` mode never quarantines. Typed text goes through `typed_places`
/// and channel bodies always place `{house}`.
pub fn analyze(prompt: &str, mode: &Mode, names: &NamesUs) -> Vec<Segment> {
    segment(&strip_harness_blocks(prompt))
        .into_iter()
        .map(|s| {
            // Shelved: an untagged fallback that judges long typed and channel
            // text would go here. It held the user's own long typed messages.
            let classified = (s.origin == Origin::Paste).then(|| classify(&s.text, names));
            let places = places_for(&s.origin, classified.as_ref(), mode);
            Segment {
                origin: s.origin,
                text: s.text,
                classified,
                places,
            }
        })
        .collect()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum DoorStatus {
    Fired,
    /// Matched, lost the budget. Not recorded, so it stays eligible.
    Deferred,
    /// Matched only in segments its scope does not admit. Never fired,
    /// never recorded.
    Held,
}

impl DoorStatus {
    pub fn label(self) -> &'static str {
        match self {
            DoorStatus::Fired => "FIRED",
            DoorStatus::Deferred => "DEFERRED",
            DoorStatus::Held => "HELD",
        }
    }
}

/// One door that matched somewhere in the prompt, and what became of it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DoorMatch {
    pub door: FiredDoor,
    pub status: DoorStatus,
    /// 1-based index into the segments.
    pub segment: usize,
    /// The budget pool its winning hit spends.
    pub pool: Pool,
    /// For a held door: the exclusion that matched in its admitted segment.
    /// `None` for a scope hold.
    pub excluded_by: Option<String>,
}

/// Everything one prompt produced, for `check --explain`.
#[derive(Debug, Clone, PartialEq)]
pub struct Explanation {
    pub mode: Mode,
    pub segments: Vec<Segment>,
    pub doors: Vec<DoorMatch>,
}

impl Explanation {
    pub fn selection(&self) -> Selection {
        let count = |s| self.doors.iter().filter(|d| d.status == s).count();
        Selection {
            fired: self
                .doors
                .iter()
                .filter(|d| d.status == DoorStatus::Fired)
                .map(|d| d.door.clone())
                .collect(),
            deferred: count(DoorStatus::Deferred),
        }
    }
}

/// What a candidate matched across a run of segments.
#[derive(Debug, Default)]
struct Hits {
    /// The most specific trigger matched in a segment no exclusion matched,
    /// and that segment's index.
    clean: Option<(String, usize)>,
    /// The same for segments an exclusion held, with the first exclusion
    /// (stored order) that matched there.
    excluded: Option<(String, usize, String)>,
}

impl Hits {
    /// Any hit at all, held or not.
    fn any(self) -> Option<(String, usize)> {
        self.clean.or(self.excluded.map(|(t, n, _)| (t, n)))
    }
}

/// Each pattern compiled: grammar when it parses as grammar, else plain.
fn compile(patterns: &[String]) -> Vec<Option<triggers::Grammar>> {
    patterns
        .iter()
        .map(|t| triggers::parse_grammar(t).ok().flatten())
        .collect()
}

/// True when `pattern` (compiled as `grammar`) matches `toks`. A plain one
/// goes through the shared `match_triggers`, unstemmed.
fn pattern_hits(toks: &[String], pattern: &String, grammar: Option<&triggers::Grammar>) -> bool {
    match grammar {
        Some(g) => g.matches(toks),
        None => !triggers::match_triggers(toks, std::slice::from_ref(pattern), false).is_empty(),
    }
}

/// The most specific trigger a candidate matches across `segs`, and the index
/// of the segment it matched in. Ties go to the stored order within a
/// segment, then to the earlier segment. A segment where one of the entry's
/// exclusions matches never yields a clean hit.
fn best_hit<'s>(
    cand: &TriggeredRef<'_>,
    segs: impl Iterator<Item = (usize, &'s [String])>,
) -> Hits {
    let grammar = compile(cand.triggers);
    let all_plain = grammar.iter().all(Option::is_none);
    let exclude = cand.exclude.unwrap_or_default();
    let exclude_grammar = compile(exclude);
    let mut out = Hits::default();
    for (n, toks) in segs {
        // A plain trigger keeps the exact pre-grammar call; only grammar
        // triggers take the new matcher.
        let hits = if all_plain {
            triggers::match_triggers(toks, cand.triggers, false)
        } else {
            cand.triggers
                .iter()
                .zip(&grammar)
                .filter(|(t, g)| pattern_hits(toks, t, g.as_ref()))
                .map(|(t, _)| t.clone())
                .collect()
        };
        // Report the MOST SPECIFIC trigger, not whichever was stored first.
        // An entry carrying both `gerf` and `gerf_slips` should say
        // `gerf_slips` fired on "gerf_slips is permanent" — the longer match
        // covers more of the message and is what the reader needs to see.
        let Some(t) = hits.into_iter().reduce(|best, t| {
            if specificity(&t) > specificity(&best) {
                t
            } else {
                best
            }
        }) else {
            continue;
        };
        let held_by = exclude
            .iter()
            .zip(&exclude_grammar)
            .find(|(e, g)| pattern_hits(toks, e, g.as_ref()))
            .map(|(e, _)| e.clone());
        match held_by {
            None => {
                if out
                    .clean
                    .as_ref()
                    .is_none_or(|(b, _)| specificity(&t) > specificity(b))
                {
                    out.clean = Some((t, n));
                }
            }
            Some(e) => {
                if out
                    .excluded
                    .as_ref()
                    .is_none_or(|(b, _, _)| specificity(&t) > specificity(b))
                {
                    out.excluded = Some((t, n, e));
                }
            }
        }
    }
    out
}

/// Decide which doors open for one prompt, and say why, held doors included.
///
/// `already_fired` holds the `(key, entry id)` pairs this session has seen, and
/// `fire_counts` the all-time count per pair. Ordering is fewest all-time fires
/// first, then oldest `ts` — a door nobody has opened yet outranks a familiar
/// one, so the budget goes to what the reader is least likely to already hold.
///
/// Only human text is matched: harness blocks are removed whole, then the
/// prompt is segmented and each segment is matched on its own. A door matches
/// in the segments its scope admits (pinned admits every segment, `∅`
/// included). A door matching in several admitted segments fires once; one
/// matching only in segments it is not admitted to is held.
///
/// Two pools of `budget` each, `house` and `book`: a door spends the pool of
/// the segment its winning hit came from. Within a pool pinned doors go first.
pub fn explain(
    prompt: &str,
    mode: &Mode,
    names: &NamesUs,
    candidates: &[TriggeredRef<'_>],
    already_fired: &HashSet<(String, String)>,
    fire_counts: &HashMap<(String, String), u64>,
    budget: usize,
) -> Explanation {
    run(
        prompt,
        mode,
        names,
        candidates,
        (already_fired, fire_counts),
        budget,
        true,
    )
}

/// `explain`, reduced to what fires and how many deferred. Held doors are
/// never computed: the hook never prints them, and quarantined segments are
/// not even tokenized.
pub fn select(
    prompt: &str,
    mode: &Mode,
    names: &NamesUs,
    candidates: &[TriggeredRef<'_>],
    already_fired: &HashSet<(String, String)>,
    fire_counts: &HashMap<(String, String), u64>,
    budget: usize,
) -> Selection {
    route(
        prompt,
        mode,
        names,
        candidates,
        already_fired,
        fire_counts,
        budget,
    )
    .selection()
}

/// `select`, keeping the routed segments the hook reads its hints from. Held
/// doors are not computed.
pub fn route(
    prompt: &str,
    mode: &Mode,
    names: &NamesUs,
    candidates: &[TriggeredRef<'_>],
    already_fired: &HashSet<(String, String)>,
    fire_counts: &HashMap<(String, String), u64>,
    budget: usize,
) -> Explanation {
    run(
        prompt,
        mode,
        names,
        candidates,
        (already_fired, fire_counts),
        budget,
        false,
    )
}

/// This session's dedup set and the all-time fire counts.
type FireState<'a> = (
    &'a HashSet<(String, String)>,
    &'a HashMap<(String, String), u64>,
);

fn run(
    prompt: &str,
    mode: &Mode,
    names: &NamesUs,
    candidates: &[TriggeredRef<'_>],
    (already_fired, fire_counts): FireState<'_>,
    budget: usize,
    with_held: bool,
) -> Explanation {
    let segments = analyze(prompt, mode, names);
    let any_pinned = candidates.iter().any(|c| route::is_pinned(c.scope));
    // Stemming OFF: doors are proper nouns, and the English stemmer folds
    // Tagalog "ayos" onto "ayo". Morphology is the enemy here.
    let tokens: Vec<Vec<String>> = segments
        .iter()
        .map(|s| {
            if with_held || any_pinned || !s.places.is_empty() {
                triggers::tokens(&s.text, false)
            } else {
                Vec::new()
            }
        })
        .collect();

    // (pinned first, fires, ts, match)
    let mut matched: Vec<(bool, u64, &str, DoorMatch)> = Vec::new();
    let mut held: Vec<(bool, u64, &str, DoorMatch)> = Vec::new();
    for cand in candidates {
        let pair = (cand.key.to_string(), cand.id.to_string());
        if already_fired.contains(&pair) {
            continue;
        }
        let pinned = route::is_pinned(cand.scope);
        let through = |n: usize| -> Option<String> {
            if pinned {
                return Some("pinned".to_string());
            }
            route::admitting_place(cand.scope, &segments[n].places, mode).map(|p| p.to_string())
        };
        let segs = |admitted: bool| {
            let through = &through;
            tokens
                .iter()
                .enumerate()
                .filter(move |(n, t)| !t.is_empty() && through(*n).is_some() == admitted)
                .map(|(n, t)| (n, t.as_slice()))
        };
        let (hit, status, excluded_by) = match best_hit(cand, segs(true)) {
            Hits { clean: Some(h), .. } => (h, DoorStatus::Fired, None),
            _ if !with_held => continue,
            Hits {
                excluded: Some((t, n, e)),
                ..
            } => ((t, n), DoorStatus::Held, Some(e)),
            _ => match best_hit(cand, segs(false)).any() {
                Some(h) => (h, DoorStatus::Held, None),
                None => continue,
            },
        };
        let (trigger, n) = hit;
        let count = fire_counts.get(&pair).copied().unwrap_or(0);
        let entry = (
            !pinned,
            count,
            cand.ts,
            DoorMatch {
                door: FiredDoor {
                    key: pair.0,
                    id: pair.1,
                    trigger,
                    fragment: derive_fragment(cand.value, cand.fragment),
                    dig: dig_pointer(cand.key, cand.id, cand.memory),
                    origin: segments[n].origin.label(),
                    place: if status == DoorStatus::Held {
                        String::new()
                    } else {
                        through(n).unwrap_or_default()
                    },
                },
                status,
                segment: n + 1,
                pool: segments[n].places.pool(),
                excluded_by,
            },
        );
        match status {
            DoorStatus::Held => held.push(entry),
            _ => matched.push(entry),
        }
    }

    type Ranked<'t> = (bool, u64, &'t str, DoorMatch);
    let order = |a: &Ranked<'_>, b: &Ranked<'_>| {
        a.0.cmp(&b.0)
            .then_with(|| a.1.cmp(&b.1))
            .then_with(|| a.2.cmp(b.2))
            .then_with(|| a.3.door.key.cmp(&b.3.door.key))
            .then_with(|| a.3.door.id.cmp(&b.3.door.id))
    };
    matched.sort_by(order);
    held.sort_by(order);
    let mut spent: HashMap<Pool, usize> = HashMap::new();
    let doors = matched
        .into_iter()
        .map(|(_, _, _, mut m)| {
            let used = spent.entry(m.pool).or_insert(0);
            if *used >= budget {
                m.status = DoorStatus::Deferred;
            } else {
                *used += 1;
            }
            m
        })
        .chain(held.into_iter().map(|h| h.3))
        .collect();
    Explanation {
        mode: mode.clone(),
        segments,
        doors,
    }
}

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

    const CHANNEL: &str = concat!(
        r#"<channel source="matrix" chat_id="!r:s" message_id="$e" user="tester" "#,
        r#"user_id="@j:s" room_name="delta">"#,
        "\ngood morning widget\n</channel>"
    );

    fn cand<'a>(
        key: &'a str,
        id: &'a str,
        value: &'a str,
        ts: &'a str,
        triggers: &'a [String],
    ) -> TriggeredRef<'a> {
        TriggeredRef {
            key,
            id,
            value,
            ts,
            triggers,
            fragment: None,
            memory: None,
            scope: None,
            exclude: None,
        }
    }

    // ---- strip_channel_tags ----

    #[test]
    fn strip_channel_removes_tag_and_keeps_body() {
        let out = strip_channel_tags(CHANNEL);
        assert!(out.contains("good morning widget"));
        assert!(
            !out.contains("tester"),
            "attributes must not survive: {out}"
        );
        assert!(!out.contains("delta"));
        assert!(!out.contains("channel"));
    }

    #[test]
    fn strip_channel_attribute_alone_does_not_fire_a_door() {
        let trig = vec!["tester".to_string()];
        let cands = [cand("facts", "aaa", "x", "2026-01-01T00:00:00Z", &trig)];
        let sel = select(
            CHANNEL,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert!(
            sel.fired.is_empty(),
            "user=\"tester\" must not open a tester door"
        );
    }

    #[test]
    fn strip_channel_tolerates_gt_inside_an_attribute() {
        let out = strip_channel_tags(r#"<channel room_name="a > b">hi</channel>"#);
        assert_eq!(out.trim(), "hi");
    }

    #[test]
    fn unterminated_channel_tag_does_not_swallow_the_turn() {
        // A stray "<channel" with no closing bracket must not eat the rest of
        // the prompt -- that would cost every door for the turn.
        let out = strip_channel_tags("<channel source=\"matrix\" oops widget is here");
        assert!(out.contains("widget"), "body survived: {out}");

        // Same with an unbalanced quote, which is how the scan runs off the end.
        let out = strip_channel_tags("<channel user=\"unclosed widget");
        assert!(out.contains("widget"), "body survived: {out}");
    }

    #[test]
    fn unterminated_channel_tag_still_fires_doors() {
        let trig = vec!["widget".to_string()];
        let cands = [cand("facts", "aaa", "v", "2026-01-01T00:00:00Z", &trig)];
        let sel = select(
            "<channel user=\"unclosed good morning widget",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired.len(), 1, "a malformed tag must not lose the door");
    }

    #[test]
    fn most_specific_trigger_is_reported() {
        // Stored order puts the SHORT trigger first, so first-match would
        // report `gerf` for a message that actually said `gerf_slips`.
        let trig = vec!["gerf".to_string(), "gerf_slips".to_string()];
        let cands = [cand(
            "doors",
            "aaa",
            "Gerf is GEOFF",
            "2026-01-01T00:00:00Z",
            &trig,
        )];
        let sel = select(
            "gerf_slips is permanent",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired[0].trigger, "gerf_slips");

        // And a message with only the short form still reports the short form.
        let sel = select(
            "ask gerf",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired[0].trigger, "gerf");
    }

    #[test]
    fn dead_triggers_are_recognised() {
        // No alphanumeric content survives tokenization.
        assert_eq!(inspect_trigger("\u{1f98a}"), TriggerVerdict::Dead);
        assert_eq!(inspect_trigger("!!!"), TriggerVerdict::Dead);
        assert_eq!(inspect_trigger("---"), TriggerVerdict::Dead);
    }

    #[test]
    fn punctuation_names_collapse_to_a_broad_single_token() {
        // The whole point: the author types a language name, the matcher sees a
        // single letter.
        for (raw, becomes) in [("c++", "c"), ("c#", "c"), ("F#", "f")] {
            assert_eq!(
                inspect_trigger(raw),
                TriggerVerdict::Broad {
                    matched_as: becomes.to_string()
                },
                "{raw} must be flagged"
            );
        }
    }

    #[test]
    fn ordinary_triggers_are_fine_and_report_what_they_match() {
        assert_eq!(
            inspect_trigger("widget"),
            TriggerVerdict::Fine {
                matched_as: "widget".to_string()
            }
        );
        // Fine, but the matched form differs from the stored text -- the caller
        // surfaces that so `ayo-` is not a surprise.
        assert_eq!(
            inspect_trigger("ayo-"),
            TriggerVerdict::Fine {
                matched_as: "ayo".to_string()
            }
        );
        assert_eq!(matched_form("gerf_slips"), "gerf slips");
        assert_eq!(matched_form(".NET"), "net");
    }

    #[test]
    fn lenient_string_accepts_a_numeric_session_id() {
        // A strict String field would reject the whole payload and the hook
        // would go silent for that prompt.
        let input: HookInput =
            serde_json::from_str(r#"{"session_id": 12345, "prompt": "hi widget"}"#).unwrap();
        assert_eq!(input.session_id, "12345");
        assert_eq!(input.prompt, "hi widget");
    }

    #[test]
    fn hook_input_tolerates_missing_null_and_unknown_fields() {
        let input: HookInput = serde_json::from_str(
            r#"{"prompt": "hi", "session_id": null, "something_new": {"a": 1}}"#,
        )
        .unwrap();
        assert_eq!(input.session_id, "");
        assert_eq!(input.prompt, "hi");

        let bare: HookInput = serde_json::from_str("{}").unwrap();
        assert_eq!(bare.prompt, "");
    }

    #[test]
    fn specificity_prefers_more_tokens_then_more_characters() {
        assert!(specificity("kon kon") > specificity("widget"));
        assert!(specificity("gerf_slips") > specificity("gerf"));
        // Equal triggers tie, so stored order decides and output stays stable.
        assert_eq!(specificity("alpha"), specificity("bravo"));
    }

    #[test]
    fn strip_channel_leaves_ordinary_angle_brackets() {
        let out = strip_channel_tags("if a < b and c > d");
        assert_eq!(out, "if a < b and c > d");
    }

    // ---- strip_harness_blocks ----

    /// The triggers that opened a door on `prompt`, one candidate per trigger.
    fn fired_on(prompt: &str, triggers: &[&str]) -> Vec<String> {
        let owned: Vec<Vec<String>> = triggers.iter().map(|t| vec![t.to_string()]).collect();
        let cands: Vec<TriggeredRef<'_>> = owned
            .iter()
            .enumerate()
            .map(|(n, t)| TriggeredRef {
                key: "d",
                id: triggers[n],
                value: "v",
                ts: "2026-01-01T00:00:00Z",
                triggers: t,
                fragment: None,
                memory: None,
                scope: None,
                exclude: None,
            })
            .collect();
        let mut fired: Vec<String> = select(
            prompt,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            triggers.len(),
        )
        .fired
        .into_iter()
        .map(|f| f.trigger)
        .collect();
        fired.sort();
        fired
    }

    #[test]
    fn harness_blocks_are_removed_with_their_body() {
        for (prompt, gone) in [
            (
                "a <task-notification>\n<status>done</status> secret\n</task-notification> b",
                "secret",
            ),
            ("a <system-reminder>secret</system-reminder> b", "secret"),
            (
                "a <local-command-stdout>secret</local-command-stdout> b",
                "secret",
            ),
            (
                "a <local-command-stderr>secret</local-command-stderr> b",
                "secret",
            ),
            (
                "a <local-command-caveat>secret</local-command-caveat> b",
                "secret",
            ),
        ] {
            let out = strip_harness_blocks(prompt);
            assert!(!out.contains(gone), "body must go: {out:?}");
            assert!(!out.contains('<'), "tags must go: {out:?}");
            assert_eq!(triggers::tokens(&out, false), vec!["a", "b"], "{out:?}");
        }
    }

    #[test]
    fn trigger_inside_a_harness_block_does_not_fire_but_human_text_does() {
        let prompt = concat!(
            "<task-notification>agent quoted widget and gizmo</task-notification>",
            "<system-reminder>gizmo widget sprocket</system-reminder>",
            "<local-command-stdout>sprocket</local-command-stdout>",
            "\nwhat about the widget?"
        );
        assert_eq!(
            fired_on(prompt, &["widget", "gizmo", "sprocket"]),
            vec!["widget"]
        );
    }

    #[test]
    fn tag_name_trigger_does_not_fire_off_the_tag() {
        assert!(
            fired_on(
                "<system-reminder>note</system-reminder> hi",
                &["system-reminder", "task-notification"]
            )
            .is_empty()
        );
        // A stray closer and a self-closing tag are tags too.
        assert!(
            fired_on(
                "hi </system-reminder> <system-reminder/>",
                &["system-reminder"]
            )
            .is_empty()
        );
    }

    #[test]
    fn near_miss_names_are_not_harness_tags() {
        let prompt = "<system-reminderz>keep</system-reminderz> <System-Reminder>keep2</System-Reminder> <local-command->keep3</local-command-> <local-command-Stdout>keep4</local-command-Stdout>";
        let out = strip_harness_blocks(prompt);
        assert_eq!(out, prompt, "only exact lowercase names are stripped");
    }

    #[test]
    fn unclosed_opener_keeps_the_rest_as_text() {
        let out = strip_harness_blocks("hi <system-reminder oops widget");
        assert!(out.contains("widget"), "{out:?}");
        assert_eq!(
            fired_on("hi <system-reminder oops widget", &["widget"]),
            vec!["widget"]
        );
        // A later real block is still removed.
        assert_eq!(
            fired_on(
                "hi <system-reminder oops widget <system-reminder>gizmo</system-reminder>",
                &["widget", "gizmo"]
            ),
            vec!["widget"]
        );
    }

    #[test]
    fn only_bare_tags_are_harness_tags() {
        for prompt in [
            "<system-reminder note=\"x\">widget</task-notification-not>",
            "<system-reminder >widget",
            "<System-Reminder>widget</System-Reminder>",
            "<local-command-é>widget</local-command-é>",
            "<task-notification id=\"1\"/>widget",
        ] {
            assert_eq!(strip_harness_blocks(prompt), prompt);
            assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"], "{prompt:?}");
        }
    }

    #[test]
    fn prose_mention_of_a_tag_keeps_the_human_text() {
        let prompt = "the <system-reminder thing keeps opening keurig -> please fix";
        assert_eq!(strip_harness_blocks(prompt), prompt);
        assert_eq!(fired_on(prompt, &["keurig"]), vec!["keurig"]);
    }

    #[test]
    fn attributed_or_split_openers_are_literal_text() {
        let prompt = "<system-reminder a=\">\" b=\"<\">widget</system-reminder>\n<task-notification\n  id=\"1\"\n>widget</task-notification> gizmo";
        assert_eq!(
            strip_harness_blocks(prompt),
            "<system-reminder a=\">\" b=\"<\">widget \n<task-notification\n  id=\"1\"\n>widget  gizmo"
        );
        assert_eq!(
            fired_on(prompt, &["widget", "gizmo"]),
            vec!["gizmo", "widget"]
        );
        assert_eq!(
            fired_on("<system-\nreminder>widget</system-\nreminder>", &["widget"]),
            vec!["widget"]
        );
    }

    #[test]
    fn opener_with_no_closing_tag_loses_only_the_tag() {
        let prompt = "<system-reminder>so about the widget";
        let out = strip_harness_blocks(prompt);
        assert_eq!(out, " so about the widget");
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn report_quoting_its_own_opener_in_backticks_is_removed_whole() {
        let prompt = concat!(
            "<task-notification>\n<status>completed</status>\n",
            "<result>Ran kv update on keurig, then stripped `<task-notification>` blocks.</result>\n",
            "</task-notification>\nhi"
        );
        assert_eq!(strip_harness_blocks(prompt), " \nhi");
        assert!(fired_on(prompt, &["keurig"]).is_empty());
        assert_eq!(fired_on(prompt, &["keurig", "hi"]), vec!["hi"]);
    }

    #[test]
    fn unpaired_opener_loses_only_its_tag_between_blocks() {
        let prompt = "<system-reminder>a <system-reminder>b</system-reminder> widget <system-reminder>c</system-reminder>";
        assert_eq!(strip_harness_blocks(prompt), " a   widget  ");
    }

    #[test]
    fn backtick_quoted_closer_inside_a_report_is_literal() {
        let prompt =
            "<task-notification>the `</task-notification>` closer, sprocket</task-notification>";
        assert_eq!(strip_harness_blocks(prompt), " ");
        assert!(fired_on(prompt, &["sprocket"]).is_empty());
    }

    #[test]
    fn known_edge_unbackticked_quoted_closer_ends_the_block_early() {
        // Pinned: a body quoting its own closer without backticks ends there,
        // so the tail leaks. It leaks that block's text only.
        let prompt =
            "<task-notification>the </task-notification> closer, sprocket</task-notification>";
        assert_eq!(strip_harness_blocks(prompt), "  closer, sprocket ");
        assert_eq!(fired_on(prompt, &["sprocket"]), vec!["sprocket"]);
    }

    #[test]
    fn known_edge_human_bare_opener_and_later_bare_closer_remove_the_text_between() {
        // Pinned: an unbackticked opener and a later unbackticked closer of the
        // same name, whoever wrote them. Pairing cannot tell this from a
        // harness block, so the text between goes.
        let prompt = "my <system-reminder> said keurig, and that </system-reminder> was odd widget";
        assert_eq!(strip_harness_blocks(prompt), "my   was odd widget");
        assert_eq!(fired_on(prompt, &["keurig", "widget"]), vec!["widget"]);
    }

    #[test]
    fn known_edge_closer_quoted_in_another_block_pairs_with_a_human_opener() {
        // Pinned: cross-name. The human's bare opener pairs with a closer a
        // system-reminder body quotes, so the text between goes.
        let prompt = "I typed <task-notification> keurig <system-reminder>quote </task-notification> x</system-reminder>";
        assert_eq!(strip_harness_blocks(prompt), "I typed   x ");
        assert!(fired_on(prompt, &["keurig"]).is_empty());
    }

    #[test]
    fn unbackticked_quotes_in_two_reports_keep_the_human_between() {
        let prompt = "<task-notification>r1 stripped <task-notification> blocks</task-notification>\nHUMAN keurig\n<task-notification>r2 the </task-notification> closer</task-notification>";
        assert_eq!(
            strip_harness_blocks(prompt),
            " r1 stripped  \nHUMAN keurig\n  closer "
        );
        assert_eq!(fired_on(prompt, &["keurig"]), vec!["keurig"]);
    }

    #[test]
    fn bare_mention_before_a_report_quoting_a_closer_keeps_the_human_text() {
        let prompt = "I pasted <task-notification> earlier, keurig please <task-notification>report mentions </task-notification> lol</task-notification>";
        assert_eq!(
            strip_harness_blocks(prompt),
            "I pasted   earlier, keurig please   lol "
        );
        assert_eq!(fired_on(prompt, &["keurig"]), vec!["keurig"]);
    }

    #[test]
    fn human_bare_closer_after_an_unbackticked_report_keeps_the_human_text() {
        let prompt = "<task-notification>stripped <task-notification> blocks</task-notification>\nkeurig: the </task-notification> closer is weird";
        assert_eq!(fired_on(prompt, &["keurig"]), vec!["keurig"]);
    }

    #[test]
    fn backticks_inside_a_real_body_do_not_quote_its_tags() {
        let prompt = "<local-command-stdout>`widget`</local-command-stdout> gizmo";
        assert_eq!(strip_harness_blocks(prompt), "  gizmo");
        assert_eq!(fired_on(prompt, &["widget", "gizmo"]), vec!["gizmo"]);
    }

    #[test]
    fn backtick_adjacent_opener_is_literal_and_does_not_pair() {
        let prompt = "`<system-reminder>` widget</system-reminder> gizmo";
        assert_eq!(
            strip_harness_blocks(prompt),
            "`<system-reminder>` widget  gizmo"
        );
        assert_eq!(
            fired_on(prompt, &["widget", "gizmo"]),
            vec!["gizmo", "widget"]
        );
    }

    #[test]
    fn backtick_adjacent_closer_is_literal_and_does_not_pair() {
        let prompt = "<system-reminder>note `</system-reminder>` widget";
        assert_eq!(
            strip_harness_blocks(prompt),
            " note `</system-reminder>` widget"
        );
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn backtick_adjacent_self_closing_is_literal() {
        let prompt = "`<system-reminder/>` widget `<local-command-caveat/>`";
        assert_eq!(strip_harness_blocks(prompt), prompt);
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn human_bare_opener_before_a_real_block_keeps_the_human_text() {
        // Poppy P4.
        let prompt = "why does <system-reminder> keep firing keurig\n<system-reminder>harness note</system-reminder>";
        assert_eq!(
            strip_harness_blocks(prompt),
            "why does   keep firing keurig\n "
        );
        assert_eq!(fired_on(prompt, &["keurig", "harness"]), vec!["keurig"]);
    }

    #[test]
    fn quoted_opener_and_quoted_closer_in_two_reports_keep_the_human_between() {
        // Poppy P5.
        let prompt = concat!(
            "<task-notification>r1 stripped `<task-notification>` blocks</task-notification>",
            "\nHUMAN keurig\n",
            "<task-notification>r2 the `</task-notification>` closer</task-notification>"
        );
        assert_eq!(strip_harness_blocks(prompt), " \nHUMAN keurig\n ");
        assert_eq!(
            fired_on(prompt, &["keurig", "stripped", "closer"]),
            vec!["keurig"]
        );
    }

    #[test]
    fn human_bare_closer_after_a_report_loses_only_the_tag() {
        // Poppy P6.
        let prompt = "<task-notification>stripped `<task-notification>` blocks</task-notification>\nkeurig: the </task-notification> closer is weird";
        assert_eq!(
            strip_harness_blocks(prompt),
            " \nkeurig: the   closer is weird"
        );
        assert_eq!(fired_on(prompt, &["keurig", "stripped"]), vec!["keurig"]);
    }

    #[test]
    fn backticked_mention_before_a_real_block_keeps_the_human_text() {
        // Diffi F6.
        let prompt = "why does `<system-reminder>` keep firing keurig? <system-reminder>harness note</system-reminder>";
        let out = strip_harness_blocks(prompt);
        assert!(out.contains("keep firing keurig"), "{out:?}");
        assert!(!out.contains("harness note"), "{out:?}");
        assert_eq!(fired_on(prompt, &["keurig", "harness"]), vec!["keurig"]);
    }

    #[test]
    fn bare_mention_before_a_real_block_keeps_the_human_text() {
        // Diffi F6.
        let prompt = "I pasted <task-notification> earlier, keurig please <task-notification>report</task-notification>";
        let out = strip_harness_blocks(prompt);
        assert!(out.contains("keurig please"), "{out:?}");
        assert!(!out.contains("report"), "{out:?}");
        assert_eq!(fired_on(prompt, &["keurig", "report"]), vec!["keurig"]);
    }

    #[test]
    fn stray_closer_is_removed_and_text_survives() {
        let prompt = "the widget</task-notification>works";
        assert_eq!(strip_harness_blocks(prompt), "the widget works");
        assert_eq!(
            fired_on(prompt, &["widget", "works"]),
            vec!["widget", "works"]
        );
    }

    #[test]
    fn self_closing_tag_is_removed_alone() {
        let prompt = "the<system-reminder/>widget <local-command-caveat/>works";
        assert_eq!(strip_harness_blocks(prompt), "the widget  works");
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn self_closing_tag_does_not_open_a_block() {
        let prompt = "<system-reminder/> widget </system-reminder> gizmo";
        assert_eq!(strip_harness_blocks(prompt), "  widget   gizmo");
        assert_eq!(
            fired_on(prompt, &["widget", "gizmo"]),
            vec!["gizmo", "widget"]
        );
    }

    #[test]
    fn known_edge_nested_same_name_leaks_the_outer_text() {
        // Pinned: the inner opener displaces the outer one, so only the inner
        // block goes and the outer block's own text leaks. Agent text only.
        let prompt =
            "<system-reminder>a<system-reminder>b</system-reminder>c</system-reminder> widget";
        assert_eq!(strip_harness_blocks(prompt), " a c  widget");
        assert!(fired_on(prompt, &["b"]).is_empty());
    }

    #[test]
    fn nested_different_name_goes_with_the_outer_body() {
        let prompt = concat!(
            "<task-notification>report <system-reminder>inner</system-reminder> ",
            "<local-command-stdout>echo</local-command-stdout> tail</task-notification> widget"
        );
        assert_eq!(strip_harness_blocks(prompt), "  widget");
        assert_eq!(
            fired_on(prompt, &["widget", "inner", "echo", "tail"]),
            vec!["widget"]
        );
    }

    #[test]
    fn adjacent_blocks_each_go() {
        let prompt = "<system-reminder>a</system-reminder><system-reminder>b</system-reminder><task-notification>c</task-notification>widget";
        assert_eq!(strip_harness_blocks(prompt), "   widget");
    }

    #[test]
    fn removed_block_leaves_a_token_boundary() {
        let out = strip_harness_blocks("foo<system-reminder>x</system-reminder>bar");
        assert_eq!(out, "foo bar");
        assert_eq!(triggers::tokens(&out, false), vec!["foo", "bar"]);
        assert!(fired_on("foo<system-reminder>x</system-reminder>bar", &["foobar"]).is_empty());
    }

    #[test]
    fn mismatched_local_command_close_does_not_swallow_the_turn() {
        let prompt = "<local-command-stdout>out</local-command-stderr> widget";
        assert_eq!(strip_harness_blocks(prompt), " out  widget");
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn deep_nesting_balanced() {
        let n = 5_000;
        let prompt = format!(
            "{}widget{} gizmo",
            "<system-reminder>".repeat(n),
            "</system-reminder>".repeat(n)
        );
        assert_eq!(fired_on(&prompt, &["widget", "gizmo"]), vec!["gizmo"]);
    }

    #[test]
    fn multibyte_hugging_tags() {
        let prompt = "é<system-reminder>🦊</system-reminder>ß<local-command-stdout>\u{200b}</local-command-stdout>🦊widget";
        assert_eq!(strip_harness_blocks(prompt), "é ß 🦊widget");
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
        for literal in [
            "<system-reminder",
            "<system-reminder/",
            "<local-command-",
            "",
        ] {
            assert_eq!(strip_harness_blocks(literal), literal);
        }
        assert!(
            fired_on(
                "<system-reminder>widget</system-reminder><task-notification>widget</task-notification>",
                &["widget"]
            )
            .is_empty()
        );
    }

    #[test]
    fn fuzz_multibyte_around_tags_never_panics() {
        const PIECES: [&str; 26] = [
            "<",
            "</",
            ">",
            "/>",
            "\"",
            " ",
            "\n",
            "x",
            "é",
            "🦊",
            "\u{200b}",
            "ß",
            "system-reminder",
            "task-notification",
            "local-command-stdout",
            "local-command-",
            "local-command-é",
            "<system-reminder",
            "</system-reminder>",
            "<channel",
            "</channel>",
            "<task-notification>",
            "<pasted_content id=\"a\">",
            "</pasted_content id=\"a\">",
            "</pasted_content id=\"b\">",
            "<pasted_content id=\"",
        ];
        let mut seed: u64 = 0x5eed_b0bb;
        let mut next = || {
            seed = seed
                .wrapping_mul(6364136223846793005)
                .wrapping_add(1442695040888963407);
            seed >> 33
        };
        for _ in 0..20_000 {
            let len = next() % 24;
            let s: String = (0..len)
                .map(|_| PIECES[(next() % PIECES.len() as u64) as usize])
                .collect();
            let _ = strip_channel_tags(&strip_harness_blocks(&s));
            let _ = segment(&s);
            let _ = fired_on(&s, &["x", "system-reminder"]);
        }
    }

    #[test]
    fn many_unbalanced_openers_stay_linear() {
        use std::time::{Duration, Instant};
        for unit in ["<system-reminder>x ", "<local-command-stdout>x "] {
            let prompt = format!("{} widget", unit.repeat(60_000));
            let t = Instant::now();
            let out = strip_harness_blocks(&prompt);
            let took = t.elapsed();
            assert!(out.ends_with(" widget"));
            assert!(
                took < Duration::from_millis(500),
                "{} KB of {unit:?} took {took:?}",
                prompt.len() / 1024
            );
        }
    }

    #[test]
    fn many_unclosed_paste_openers_stay_linear() {
        use std::time::{Duration, Instant};
        // At this size quadratic pairing would take seconds, so the bound still bites.
        let prompt = format!(
            "{} widget {}",
            "<pasted_content id=\"aaaa\">x ".repeat(20_000),
            "</pasted_content id=\"bbbb\"> ".repeat(20_000)
        );
        let t = Instant::now();
        let segs = segment(&prompt);
        let took = t.elapsed();
        assert_eq!(segs.len(), 1);
        assert!(
            took < Duration::from_millis(500),
            "{} KB of unclosed paste openers took {took:?}",
            prompt.len() / 1024
        );
    }

    #[test]
    fn channel_body_still_fires_next_to_a_harness_block() {
        assert_eq!(fired_on(CHANNEL, &["widget", "tester"]), vec!["widget"]);
        let prompt = format!(
            "<system-reminder>gizmo tester</system-reminder>{CHANNEL}<task-notification>gizmo</task-notification>"
        );
        assert_eq!(
            fired_on(&prompt, &["widget", "gizmo", "tester"]),
            vec!["widget"]
        );
    }

    #[test]
    fn harness_blocks_are_stripped_before_channel_tags() {
        let prompt = concat!(
            "<system-reminder>quoted <channel oops</system-reminder>",
            r#"<channel source="matrix" user="tester">widget</channel>"#
        );
        assert_eq!(
            fired_on(prompt, &["widget", "quoted", "tester"]),
            vec!["widget"]
        );
    }

    // ---- fragment derivation ----

    #[test]
    fn authored_fragment_is_verbatim_however_long() {
        let long = "z".repeat(400);
        assert_eq!(derive_fragment("value", Some(&long)), long);
    }

    #[test]
    fn derived_fragment_is_the_first_line() {
        assert_eq!(
            derive_fragment("  first line  \nsecond line", None),
            "first line"
        );
    }

    #[test]
    fn derived_fragment_cuts_on_a_char_boundary() {
        // A multi-byte character sits exactly at the cut point.
        let mut line = "a".repeat(198);
        line.push('é');
        line.push_str(&"b".repeat(60));
        let out = derive_fragment(&line, None);
        assert_eq!(out.chars().count(), DERIVED_FRAGMENT_MAX);
        assert!(out.ends_with('\u{2026}'));
        assert!(out.contains('é'), "the boundary char must survive intact");
    }

    #[test]
    fn empty_authored_fragment_falls_back_to_first_line() {
        assert_eq!(derive_fragment("the value", Some("   ")), "the value");
    }

    // ---- dig pointer ----

    #[test]
    fn dig_pointer_shapes() {
        assert_eq!(dig_pointer("doors", "2gRwr9", None), "doors/kv-2gRwr9");
        assert_eq!(
            dig_pointer("doors", "2gRwr9", Some("kn-02e73234")),
            "doors/kv-2gRwr9, kn-02e73234"
        );
    }

    // ---- matching ----

    #[test]
    fn widget_fires_from_inside_a_channel_block() {
        let trig = vec!["widget".to_string()];
        let cands = [cand(
            "facts",
            "3gtR1J",
            "A sample fragment for the widget door.",
            "2026-01-01T00:00:00Z",
            &trig,
        )];
        let sel = select(
            CHANNEL,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(sel.fired[0].trigger, "widget");
        assert_eq!(sel.fired[0].dig, "facts/kv-3gtR1J");
        assert_eq!(
            sel.fired[0].render(),
            "\u{1f6aa} widget \u{2192} A sample fragment for the widget door. (dig: facts/kv-3gtR1J)"
        );
    }

    #[test]
    fn already_fired_entry_is_skipped() {
        let trig = vec!["widget".to_string()];
        let cands = [cand("facts", "aaa", "v", "2026-01-01T00:00:00Z", &trig)];
        let fired: HashSet<(String, String)> = [("facts".to_string(), "aaa".to_string())]
            .into_iter()
            .collect();
        let sel = select(
            "hi widget",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &fired,
            &HashMap::new(),
            2,
        );
        assert!(sel.fired.is_empty());
        assert_eq!(
            sel.deferred, 0,
            "a deduped door is not deferred, it is done"
        );
    }

    #[test]
    fn dedup_tuple_includes_the_key() {
        // Two entries in DIFFERENT keys sharing one 6-char id. Firing one must
        // not suppress the other.
        let trig = vec!["widget".to_string()];
        let cands = [
            cand("facts", "same01", "a", "2026-01-01T00:00:00Z", &trig),
            cand("doors", "same01", "b", "2026-01-02T00:00:00Z", &trig),
        ];
        let fired: HashSet<(String, String)> = [("facts".to_string(), "same01".to_string())]
            .into_iter()
            .collect();
        let sel = select(
            "widget",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &fired,
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(sel.fired[0].key, "doors");
    }

    #[test]
    fn budget_overflow_defers_the_most_fired() {
        let trig = vec!["widget".to_string()];
        let cands = [
            cand("d", "aaa", "a", "2026-01-01T00:00:00Z", &trig),
            cand("d", "bbb", "b", "2026-01-01T00:00:00Z", &trig),
            cand("d", "ccc", "c", "2026-01-01T00:00:00Z", &trig),
        ];
        let counts: HashMap<(String, String), u64> = [
            (("d".to_string(), "aaa".to_string()), 7),
            (("d".to_string(), "bbb".to_string()), 1),
            (("d".to_string(), "ccc".to_string()), 0),
        ]
        .into_iter()
        .collect();
        let sel = select(
            "widget",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &counts,
            2,
        );
        assert_eq!(sel.deferred, 1);
        let ids: Vec<&str> = sel.fired.iter().map(|f| f.id.as_str()).collect();
        assert_eq!(ids, vec!["ccc", "bbb"], "least-fired first");
    }

    #[test]
    fn tie_on_fire_count_breaks_to_oldest_ts() {
        let trig = vec!["widget".to_string()];
        let cands = [
            cand("d", "new", "n", "2026-06-01T00:00:00Z", &trig),
            cand("d", "old", "o", "2020-01-01T00:00:00Z", &trig),
        ];
        let sel = select(
            "widget",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            1,
        );
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(sel.fired[0].id, "old");
    }

    #[test]
    fn no_match_is_an_empty_selection() {
        let trig = vec!["widget".to_string()];
        let cands = [cand("d", "aaa", "a", "2026-01-01T00:00:00Z", &trig)];
        let sel = select(
            "hello there",
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert!(sel.fired.is_empty());
        assert_eq!(sel.deferred, 0);
    }

    #[test]
    fn stemming_is_off_so_tagalog_ayos_does_not_open_the_ayo_door() {
        let trig = vec!["ayo-".to_string()];
        let cands = [cand(
            "d",
            "aaa",
            "shell alias",
            "2026-01-01T00:00:00Z",
            &trig,
        )];
        assert!(
            select(
                "ayos lang",
                &Mode::House,
                &NamesUs::default(),
                &cands,
                &HashSet::new(),
                &HashMap::new(),
                2
            )
            .fired
            .is_empty()
        );
        assert_eq!(
            select(
                "switched to ayo-mirage",
                &Mode::House,
                &NamesUs::default(),
                &cands,
                &HashSet::new(),
                &HashMap::new(),
                2
            )
            .fired
            .len(),
            1
        );
    }

    // ---- segment ----

    const WALDEN: &str = include_str!("../tests/fixtures/doors/pd/walden.txt");
    const OPENER: &str = include_str!("../tests/fixtures/doors/syn/syn-chapter-opener.txt");
    const CV: &str = include_str!("../tests/fixtures/doors/syn/syn-cv.txt");

    fn seg(origin: Origin, text: &str) -> RawSegment {
        RawSegment {
            origin,
            text: text.to_string(),
        }
    }

    fn channel(user_id: &str) -> Origin {
        Origin::Channel {
            user_id: user_id.to_string(),
        }
    }

    /// A paste in Claude Code's envelope.
    fn paste(id: &str, body: &str) -> String {
        format!("<pasted_content id=\"{id}\">\n{body}\n</pasted_content id=\"{id}\">")
    }

    #[test]
    fn paste_envelope_is_cut_exactly() {
        // The Step 0 shape: typed, blank line, tagged paste, blank line, typed.
        let prompt = format!(
            "please read this: \n\n{}\n\n and say ok",
            paste("f23b", "line one\n\nline two\n")
        );
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "please read this: \n\n"),
                seg(Origin::Paste, "line one\n\nline two\n"),
                seg(Origin::Typed, "\n\n and say ok"),
            ]
        );
    }

    #[test]
    fn only_a_closer_with_the_same_id_closes_a_paste() {
        let prompt = "<pasted_content id=\"aaaa\">\nx\n</pasted_content id=\"bbbb\">\ny\n</pasted_content id=\"aaaa\">\n</pasted_content id=\"aaaa\">";
        assert_eq!(
            segment(prompt),
            vec![
                seg(Origin::Paste, "x\n</pasted_content id=\"bbbb\">\ny"),
                seg(Origin::Typed, "\n</pasted_content id=\"aaaa\">"),
            ],
            "the first matching closer ends it"
        );
    }

    #[test]
    fn unclosed_paste_opener_is_ordinary_text() {
        let prompt = "hi <pasted_content id=\"aaaa\">\nwidget";
        assert_eq!(segment(prompt), vec![seg(Origin::Typed, prompt)]);
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);

        // And it does not stop a later real paste from being cut out.
        let prompt = format!(
            "<pasted_content id=\"zz\">oops {} tail",
            paste("aa", "body")
        );
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "<pasted_content id=\"zz\">oops "),
                seg(Origin::Paste, "body"),
                seg(Origin::Typed, " tail"),
            ]
        );
    }

    #[test]
    fn malformed_paste_tags_are_text() {
        for prompt in [
            "<pasted_content id=\"\">\nx\n</pasted_content id=\"\">",
            "<pasted_content id=\"a b\">\nx\n</pasted_content id=\"a b\">",
            "<pasted_content id=aaaa>\nx\n</pasted_content id=aaaa>",
        ] {
            assert_eq!(
                segment(prompt),
                vec![seg(Origin::Typed, prompt)],
                "{prompt:?}"
            );
        }
    }

    #[test]
    fn a_pasted_transcript_stays_one_paste_and_loses_channel_attributes() {
        let body = format!("before\n{CHANNEL}\nafter");
        let segs = segment(&paste("aaaa", &body));
        assert_eq!(segs.len(), 1, "{segs:?}");
        assert_eq!(segs[0].origin, Origin::Paste);
        assert!(segs[0].text.contains("good morning widget"));
        assert!(!segs[0].text.contains("tester"), "{:?}", segs[0].text);
        assert!(!segs[0].text.contains("delta"));
    }

    #[test]
    fn paste_tags_inside_a_channel_body_are_plain_body_text() {
        let prompt = "<channel source=\"matrix\" user_id=\"@m:e\">\nhi\n<pasted_content id=\"ab12\">\nx\n</pasted_content id=\"ab12\">\nzephyrine\n</channel>";
        let segs = segment(prompt);
        assert_eq!(segs.len(), 1, "{segs:?}");
        assert_eq!(segs[0].origin, channel("@m:e"));
        assert!(segs[0].text.contains("zephyrine"));
        assert!(segs[0].text.contains("<pasted_content id=\"ab12\">"));
    }

    #[test]
    fn the_first_opener_wins() {
        // Channel first: its body runs to `</channel>`, even through a paste
        // whose closer lies beyond it.
        let prompt = "<channel user_id=\"u\">a <pasted_content id=\"x\">\nb\n</channel> c\n</pasted_content id=\"x\"> d";
        assert_eq!(
            segment(prompt),
            vec![
                seg(channel("u"), "a <pasted_content id=\"x\">\nb\n"),
                seg(Origin::Typed, " c\n</pasted_content id=\"x\"> d"),
            ]
        );
        // Paste first: a channel closer inside it is stripped, and a later one
        // in typed text goes too.
        let prompt = format!(
            "{} tail</channel>",
            paste("x", "a <channel user_id=\"u\">b")
        );
        assert_eq!(
            segment(&prompt),
            vec![seg(Origin::Paste, "a  b"), seg(Origin::Typed, " tail ")]
        );
    }

    #[test]
    fn known_edge_channel_without_a_closer_runs_to_the_end() {
        let prompt = format!("hi <channel user_id=\"u\">body {}", paste("x", "p"));
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "hi "),
                seg(
                    channel("u"),
                    "body <pasted_content id=\"x\">\np\n</pasted_content id=\"x\">"
                ),
            ]
        );
    }

    #[test]
    fn known_edge_a_paste_quoting_its_own_closer_ends_early() {
        let body = "a\n</pasted_content id=\"x\">\nb";
        assert_eq!(
            segment(&paste("x", body)),
            vec![
                seg(Origin::Paste, "a"),
                seg(Origin::Typed, "\nb\n</pasted_content id=\"x\">"),
            ]
        );
    }

    #[test]
    fn unterminated_channel_opener_does_not_stop_a_later_paste() {
        // One quote in the body makes the quote count even, so an unbounded
        // scan would find the paste closer's `>` outside any quote.
        let prompt = format!("<channel user_id=\"u {} tail", paste("x", "say \"p"));
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "<channel user_id=\"u "),
                seg(Origin::Paste, "say \"p"),
                seg(Origin::Typed, " tail"),
            ]
        );
    }

    #[test]
    fn a_bare_typed_channel_word_does_not_swallow_a_later_paste() {
        let prompt = format!("what does <channel do here?\n\n{}", paste("ab12", WALDEN));
        let segs = analyze(&prompt, &Mode::House, &NamesUs::default());
        assert_eq!(segs.len(), 2, "{segs:?}");
        assert_eq!(segs[0].origin, Origin::Typed);
        assert_eq!(segs[0].text, "what does <channel do here?\n\n");
        assert_eq!(segs[1].origin, Origin::Paste);
        assert!(segs[1].places.is_empty(), "a foreign paste is held");
    }

    #[test]
    fn an_unterminated_channel_attribute_does_not_swallow_a_later_paste() {
        let body = "she said \"go home and never come back to the old mill";
        let prompt = format!(
            "see <channel user_id=\"u \n\n{}\nthanks",
            paste("ab12", body)
        );
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "see <channel user_id=\"u \n\n"),
                seg(Origin::Paste, body),
                seg(Origin::Typed, "\nthanks"),
            ]
        );
    }

    #[test]
    fn a_channel_after_a_paste_is_a_channel_again() {
        let prompt = format!(
            "<channel oops {}\n<channel user_id=\"v\">hi</channel>",
            paste("ab12", "p")
        );
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "<channel oops "),
                seg(Origin::Paste, "p"),
                seg(channel("v"), "hi"),
            ]
        );
    }

    #[test]
    fn channel_body_is_its_own_segment_keyed_by_user_id() {
        let prompt = format!("hi {CHANNEL} bye");
        assert_eq!(
            segment(&prompt),
            vec![
                seg(Origin::Typed, "hi "),
                seg(channel("@j:s"), "\ngood morning widget\n"),
                seg(Origin::Typed, " bye"),
            ]
        );
        // A display name is not an identity; only user_id is read.
        let segs = segment(r#"<channel user="@spoof:s" xuser_id="@x:s">hi</channel>"#);
        assert_eq!(segs, vec![seg(channel(""), "hi")]);
        let segs = segment(r#"<channel room_name="a > b" user_id="@j:s">hi</channel>"#);
        assert_eq!(segs, vec![seg(channel("@j:s"), "hi")]);
    }

    #[test]
    fn channel_opener_without_a_bracket_is_text() {
        let prompt = "<channel user_id=\"unclosed widget";
        assert_eq!(segment(prompt), vec![seg(Origin::Typed, prompt)]);
        assert_eq!(fired_on(prompt, &["widget"]), vec!["widget"]);
    }

    #[test]
    fn whitespace_only_typed_fragments_are_dropped() {
        let prompt = "<channel user_id=\"u\">x</channel>\n\n<channel user_id=\"v\">y</channel>\n";
        assert_eq!(
            segment(prompt),
            vec![seg(channel("u"), "x"), seg(channel("v"), "y")]
        );
        assert!(segment("  \n ").is_empty());
    }

    #[test]
    fn phrases_never_match_across_a_segment_boundary() {
        let prompt = format!("fair\n\n{}", paste("aaaa", "haven"));
        assert!(fired_on(&prompt, &["fair haven"]).is_empty());
        assert_eq!(fired_on("fair haven", &["fair haven"]), vec!["fair haven"]);
    }

    /// What `main` fired before segmentation: one token stream for the whole
    /// prompt, harness blocks and channel tags stripped.
    fn legacy_fired(prompt: &str, trigs: &[&str]) -> Vec<String> {
        let toks = triggers::tokens(&strip_channel_tags(&strip_harness_blocks(prompt)), false);
        let mut out: Vec<String> = trigs
            .iter()
            .filter(|t| !triggers::match_triggers(&toks, &[t.to_string()], false).is_empty())
            .map(|t| t.to_string())
            .collect();
        out.sort();
        out
    }

    #[test]
    fn untagged_short_prompts_fire_exactly_as_before() {
        for (prompt, trigs) in [
            (
                "<task-notification>agent quoted widget and gizmo</task-notification><system-reminder>gizmo widget sprocket</system-reminder>\nwhat about the widget?",
                &["widget", "gizmo", "sprocket"][..],
            ),
            ("hi <system-reminder oops widget", &["widget"]),
            (
                "the <system-reminder thing keeps opening keurig -> please fix",
                &["keurig"],
            ),
            ("the widget</task-notification>works", &["widget", "works"]),
            (
                "the<system-reminder/>widget <local-command-caveat/>works",
                &["widget"],
            ),
            (
                "my <system-reminder> said keurig, and that </system-reminder> was odd widget",
                &["keurig", "widget"],
            ),
            ("gerf_slips is permanent", &["gerf", "gerf_slips"]),
            ("switched to ayo-mirage, ayos lang", &["ayo-", "ayos"]),
        ] {
            assert!(
                analyze(prompt, &Mode::House, &NamesUs::default())
                    .iter()
                    .all(|s| s.origin == Origin::Typed && s.classified.is_none()),
                "{prompt:?}"
            );
            assert_eq!(
                fired_on(prompt, trigs),
                legacy_fired(prompt, trigs),
                "{prompt:?}"
            );
            assert!(!legacy_fired(prompt, trigs).is_empty(), "{prompt:?}");
        }
    }

    // ---- routing ----

    fn explain_on(prompt: &str, trigs: &[&str], budget: usize) -> Explanation {
        let owned: Vec<Vec<String>> = trigs.iter().map(|t| vec![t.to_string()]).collect();
        let cands: Vec<TriggeredRef<'_>> = owned
            .iter()
            .enumerate()
            .map(|(n, t)| TriggeredRef {
                key: "d",
                id: trigs[n],
                value: "v",
                ts: "2026-01-01T00:00:00Z",
                triggers: t,
                fragment: None,
                memory: None,
                scope: None,
                exclude: None,
            })
            .collect();
        explain(
            prompt,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            budget,
        )
    }

    fn outcome(ex: &Explanation) -> Vec<(String, DoorStatus, &'static str, usize)> {
        ex.doors
            .iter()
            .map(|d| (d.door.trigger.clone(), d.status, d.door.origin, d.segment))
            .collect()
    }

    #[test]
    fn foreign_paste_is_quarantined_and_typed_text_still_fires() {
        let prompt = format!(
            "about huckleberries? \n\n{}\n\n keep it short",
            paste("aaaa", WALDEN)
        );
        let ex = explain_on(&prompt, &["huckleberries", "fair haven"], 2);
        assert_eq!(
            ex.segments[1].classified.as_ref().map(|c| c.verdict),
            Some(Verdict::ForeignProse)
        );
        assert!(ex.segments[1].places.is_empty());
        assert_eq!(
            outcome(&ex),
            vec![
                ("huckleberries".into(), DoorStatus::Fired, "typed", 1),
                ("fair haven".into(), DoorStatus::Held, "paste", 2),
            ]
        );
        let sel = ex.selection();
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(sel.fired[0].origin, "typed");
        assert_eq!(sel.deferred, 0, "a held door is not deferred");
    }

    #[test]
    fn held_doors_do_not_spend_the_budget() {
        let prompt = format!("widget\n\n{}", paste("aaaa", WALDEN));
        let ex = explain_on(&prompt, &["fair haven", "huckleberries", "widget"], 1);
        let sel = ex.selection();
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(sel.fired[0].trigger, "widget");
        assert_eq!(sel.deferred, 0);
    }

    #[test]
    fn short_and_ours_pastes_keep_todays_behaviour() {
        let prompt = paste("aaaa", "a short note about fair haven");
        assert_eq!(
            outcome(&explain_on(&prompt, &["fair haven"], 2)),
            vec![("fair haven".into(), DoorStatus::Fired, "paste", 1)]
        );
        let ex = explain_on(&paste("aaaa", CV), &["eurocodes"], 2);
        assert_eq!(
            ex.segments[0].classified.as_ref().map(|c| c.verdict),
            Some(Verdict::Ours)
        );
        assert_eq!(
            outcome(&ex),
            vec![("eurocodes".into(), DoorStatus::Fired, "paste", 1)]
        );
    }

    #[test]
    fn only_a_tagged_paste_is_ever_held() {
        assert!(WALDEN.chars().count() >= 600);
        let typed = explain_on(WALDEN, &["fair haven"], 2);
        assert_eq!(typed.segments.len(), 1);
        assert!(typed.segments[0].classified.is_none());
        assert_eq!(
            outcome(&typed),
            vec![("fair haven".into(), DoorStatus::Fired, "typed", 1)]
        );

        let body = format!("<channel source=\"matrix\" user_id=\"@j:s\">\n{WALDEN}\n</channel>");
        let ex = explain_on(&body, &["fair haven"], 2);
        assert_eq!(ex.segments[0].origin, channel("@j:s"));
        assert!(ex.segments[0].classified.is_none());
        assert_eq!(
            outcome(&ex),
            vec![("fair haven".into(), DoorStatus::Fired, "channel", 1)]
        );

        let ex = explain_on(&paste("aaaa", WALDEN), &["fair haven"], 2);
        assert_eq!(
            outcome(&ex),
            vec![("fair haven".into(), DoorStatus::Held, "paste", 1)]
        );
    }

    #[test]
    fn select_never_computes_held_doors() {
        let prompt = format!("widget\n\n{}", paste("aaaa", WALDEN));
        let trig = vec!["fair haven".to_string()];
        let wid = vec!["widget".to_string()];
        let cands = [
            cand("d", "aaa", "v", "2026-01-01T00:00:00Z", &trig),
            cand("d", "bbb", "v", "2026-01-01T00:00:00Z", &wid),
        ];
        let none = HashSet::new();
        let counts = HashMap::new();
        let names = NamesUs::default();
        let held = run(
            &prompt,
            &Mode::House,
            &names,
            &cands,
            (&none, &counts),
            2,
            false,
        );
        assert!(held.doors.iter().all(|d| d.status != DoorStatus::Held));
        assert_eq!(
            select(&prompt, &Mode::House, &names, &cands, &none, &counts, 2),
            explain(&prompt, &Mode::House, &names, &cands, &none, &counts, 2).selection()
        );
    }

    #[test]
    fn a_door_in_several_segments_fires_once_with_the_most_specific_trigger() {
        let trig = vec!["gerf".to_string(), "gerf_slips".to_string()];
        let cands = [cand("d", "aaa", "v", "2026-01-01T00:00:00Z", &trig)];
        let prompt = format!("ask gerf\n\n{}", paste("aaaa", "gerf_slips is permanent"));
        let sel = select(
            &prompt,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            2,
        );
        assert_eq!(sel.fired.len(), 1);
        assert_eq!(
            (sel.fired[0].trigger.as_str(), sel.fired[0].origin),
            ("gerf_slips", "paste")
        );

        // Equal specificity: the earlier segment wins.
        let ex = explain_on(
            &format!("widget\n\n{}", paste("aaaa", "widget")),
            &["widget"],
            2,
        );
        assert_eq!(
            outcome(&ex),
            vec![("widget".into(), DoorStatus::Fired, "typed", 1)]
        );
        let ex = explain_on(
            &format!("{}\n\nwidget", paste("aaaa", "widget")),
            &["widget"],
            2,
        );
        assert_eq!(
            outcome(&ex),
            vec![("widget".into(), DoorStatus::Fired, "paste", 1)]
        );
    }

    #[test]
    fn already_fired_doors_are_neither_fired_nor_held() {
        let trig = vec!["fair haven".to_string()];
        let cands = [cand("d", "aaa", "v", "2026-01-01T00:00:00Z", &trig)];
        let fired: HashSet<(String, String)> = [("d".to_string(), "aaa".to_string())].into();
        let ex = explain(
            &paste("aaaa", WALDEN),
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &fired,
            &HashMap::new(),
            2,
        );
        assert!(ex.doors.is_empty());
    }

    // ---- P2: scopes, modes, pools ----

    const PREAMBLE: &str =
        include_str!("../tests/fixtures/doors/syn/syn-notification-preamble.txt");

    /// A door `d/kv-<id>` with one trigger and an optional scope.
    struct Door {
        id: &'static str,
        trig: Vec<String>,
        scope: Option<Vec<String>>,
        ts: &'static str,
    }

    fn door(id: &'static str, trig: &str, scope: &[&str]) -> Door {
        Door {
            id,
            trig: vec![trig.to_string()],
            scope: (!scope.is_empty()).then(|| scope.iter().map(|s| s.to_string()).collect()),
            ts: "2026-01-01T00:00:00Z",
        }
    }

    fn refs(doors: &[Door]) -> Vec<TriggeredRef<'_>> {
        doors
            .iter()
            .map(|d| TriggeredRef {
                key: "d",
                id: d.id,
                value: "v",
                ts: d.ts,
                triggers: &d.trig,
                fragment: None,
                memory: None,
                scope: d.scope.as_deref(),
                exclude: None,
            })
            .collect()
    }

    fn explain_mode(
        prompt: &str,
        mode: &str,
        doors: &[Door],
        counts: &HashMap<(String, String), u64>,
        budget: usize,
    ) -> Explanation {
        explain(
            prompt,
            &Mode::parse(mode).unwrap(),
            &NamesUs::default(),
            &refs(doors),
            &HashSet::new(),
            counts,
            budget,
        )
    }

    /// `(id, status, place)` for every matched door.
    fn verdicts(ex: &Explanation) -> Vec<(String, DoorStatus, String)> {
        ex.doors
            .iter()
            .map(|d| (d.door.id.clone(), d.status, d.door.place.clone()))
            .collect()
    }

    fn fired_ids(prompt: &str, mode: &str, doors: &[Door], budget: usize) -> Vec<String> {
        explain_mode(prompt, mode, doors, &HashMap::new(), budget)
            .selection()
            .fired
            .into_iter()
            .map(|f| f.id)
            .collect()
    }

    /// 0.1.228's selection, frozen: house-only routing (a ForeignProse paste is
    /// quarantined, everything else admitted), one pool, fewest fires, oldest
    /// ts, key, id.
    fn legacy_select(
        prompt: &str,
        cands: &[TriggeredRef<'_>],
        counts: &HashMap<(String, String), u64>,
        budget: usize,
    ) -> (Vec<String>, usize) {
        let segs = analyze(prompt, &Mode::House, &NamesUs::default());
        let toks: Vec<Vec<String>> = segs
            .iter()
            .map(|s| triggers::tokens(&s.text, false))
            .collect();
        let mut m: Vec<(u64, &str, String, String, String)> = Vec::new();
        for c in cands {
            let admitted = segs
                .iter()
                .zip(&toks)
                .enumerate()
                .filter(|(_, (s, t))| {
                    !t.is_empty()
                        && !s
                            .classified
                            .as_ref()
                            .is_some_and(|c| c.verdict == Verdict::ForeignProse)
                })
                .map(|(n, (_, t))| (n, t.as_slice()));
            if let Some((trigger, _)) = best_hit(c, admitted).clean {
                let pair = (c.key.to_string(), c.id.to_string());
                let line = format!(
                    "\u{1f6aa} {} \u{2192} {} (dig: {})",
                    trigger,
                    derive_fragment(c.value, c.fragment),
                    dig_pointer(c.key, c.id, c.memory)
                );
                m.push((
                    counts.get(&pair).copied().unwrap_or(0),
                    c.ts,
                    pair.0,
                    pair.1,
                    line,
                ));
            }
        }
        m.sort_by(|a, b| {
            a.0.cmp(&b.0)
                .then_with(|| a.1.cmp(b.1))
                .then_with(|| a.2.cmp(&b.2))
                .then_with(|| a.3.cmp(&b.3))
        });
        let deferred = m.len().saturating_sub(budget);
        (m.into_iter().take(budget).map(|x| x.4).collect(), deferred)
    }

    #[test]
    fn back_compat_no_scopes_house_mode_is_0_1_228() {
        let mut doors = vec![
            door("aaa", "widget", &[]),
            door("bbb", "widget", &[]),
            door("ccc", "fair haven", &[]),
            door("ddd", "huckleberries", &[]),
            door("eee", "eurocodes", &[]),
            door("fff", "gizmo", &[]),
        ];
        doors[1].ts = "2020-01-01T00:00:00Z";
        let counts: HashMap<(String, String), u64> = [
            (("d".to_string(), "aaa".to_string()), 3),
            (("d".to_string(), "ddd".to_string()), 1),
        ]
        .into_iter()
        .collect();
        let prompts = [
            "widget and gizmo and huckleberries".to_string(),
            CHANNEL.to_string(),
            format!("huckleberries widget\n\n{}", paste("aaaa", WALDEN)),
            format!("{}\n\nwidget", paste("aaaa", CV)),
            paste("aaaa", "a short note about fair haven and gizmo"),
            "<system-reminder>widget</system-reminder> gizmo".to_string(),
            "nothing here".to_string(),
        ];
        let cands = refs(&doors);
        for prompt in &prompts {
            for budget in [0, 1, 2, 5] {
                let sel = select(
                    prompt,
                    &Mode::House,
                    &NamesUs::default(),
                    &cands,
                    &HashSet::new(),
                    &counts,
                    budget,
                );
                let lines: Vec<String> = sel.fired.iter().map(FiredDoor::render).collect();
                assert_eq!(
                    (lines, sel.deferred),
                    legacy_select(prompt, &cands, &counts, budget),
                    "{prompt:?} budget {budget}"
                );
            }
        }
    }

    #[test]
    fn book_door_fires_on_its_paste_only_in_its_book_mode() {
        let prompt = paste("aaaa", WALDEN);
        let doors = [door("wal", "fair haven", &["book:walden"])];
        assert_eq!(fired_ids(&prompt, "book:walden", &doors, 2), vec!["wal"]);
        let ex = explain_mode(&prompt, "book:walden", &doors, &HashMap::new(), 2);
        assert_eq!(ex.segments[0].places, Places::book("walden"));
        assert_eq!(ex.doors[0].door.place, "book:walden");
        assert_eq!(ex.doors[0].pool, Pool::Book);
        for mode in ["house", "book:prince", "ours"] {
            let ex = explain_mode(&prompt, mode, &doors, &HashMap::new(), 2);
            assert_eq!(
                verdicts(&ex),
                vec![("wal".to_string(), DoorStatus::Held, String::new())],
                "{mode}"
            );
        }
        // And a house door is held on that paste in book mode.
        let house = [door("hse", "fair haven", &[])];
        assert!(fired_ids(&prompt, "book:walden", &house, 2).is_empty());
    }

    #[test]
    fn spoiler_gate_holds_a_door_until_the_position_reaches_it() {
        let prompt = paste("aaaa", WALDEN);
        let doors = [door("wal", "fair haven", &["book:walden@5"])];
        for mode in ["book:walden@4", "book:walden"] {
            assert!(fired_ids(&prompt, mode, &doors, 2).is_empty(), "{mode}");
        }
        for mode in ["book:walden@5", "book:walden@9"] {
            assert_eq!(fired_ids(&prompt, mode, &doors, 2), vec!["wal"], "{mode}");
        }
    }

    #[test]
    fn ours_mode_never_quarantines_a_foreign_paste() {
        let prompt = paste("aaaa", WALDEN);
        let ex = explain_mode(
            &prompt,
            "ours",
            &[door("hse", "fair haven", &[])],
            &HashMap::new(),
            2,
        );
        assert_eq!(
            ex.segments[0].classified.as_ref().map(|c| c.verdict),
            Some(Verdict::ForeignProse),
            "the classifier still runs"
        );
        assert_eq!(ex.segments[0].places, Places::house());
        assert_eq!(
            verdicts(&ex),
            vec![("hse".to_string(), DoorStatus::Fired, "house".to_string())]
        );
    }

    #[test]
    fn book_mode_routes_an_ours_paste_to_house() {
        let ex = explain_mode(
            &paste("aaaa", CV),
            "book:walden",
            &[door("hse", "eurocodes", &[])],
            &HashMap::new(),
            2,
        );
        assert_eq!(ex.segments[0].places, Places::house());
        assert_eq!(ex.selection().fired.len(), 1);
    }

    #[test]
    fn channel_bodies_stay_house_in_every_mode() {
        for mode in ["house", "ours", "book:walden"] {
            let ex = explain_mode(
                CHANNEL,
                mode,
                &[door("w", "widget", &[])],
                &HashMap::new(),
                2,
            );
            assert_eq!(ex.segments[0].places, Places::house(), "{mode}");
            assert_eq!(ex.selection().fired.len(), 1, "{mode}");
        }
    }

    #[test]
    fn pinned_fires_in_a_quarantined_paste_and_sorts_first_in_its_pool() {
        let prompt = format!("widget\n\n{}", paste("aaaa", WALDEN));
        let pin = [door("pin", "fair haven", &["pinned"])];
        let ex = explain_mode(&prompt, "house", &pin, &HashMap::new(), 2);
        assert!(ex.segments[1].places.is_empty());
        assert_eq!(
            verdicts(&ex),
            vec![("pin".to_string(), DoorStatus::Fired, "pinned".to_string())]
        );
        assert_eq!(ex.doors[0].pool, Pool::House, "∅ spends the house pool");

        // Budget 1: a much-fired pinned door still beats a never-fired one.
        let doors = [
            door("new", "widget", &[]),
            door("pin", "widget", &["pinned"]),
        ];
        let counts: HashMap<(String, String), u64> = [(("d".to_string(), "pin".to_string()), 9)]
            .into_iter()
            .collect();
        let ex = explain_mode("widget", "house", &doors, &counts, 1);
        assert_eq!(
            verdicts(&ex),
            vec![
                ("pin".to_string(), DoorStatus::Fired, "pinned".to_string()),
                ("new".to_string(), DoorStatus::Deferred, "house".to_string()),
            ]
        );
    }

    #[test]
    fn typed_text_in_book_mode_holds_house_doors_but_not_pinned() {
        let doors = [
            door("hse", "widget", &[]),
            door("pin", "widget", &["pinned"]),
            door("wal", "widget", &["book:walden"]),
        ];
        let mut got: Vec<(String, DoorStatus)> =
            explain_mode("widget", "book:walden", &doors, &HashMap::new(), 2)
                .doors
                .into_iter()
                .map(|d| (d.door.id, d.status))
                .collect();
        got.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(
            got,
            vec![
                ("hse".to_string(), DoorStatus::Held),
                ("pin".to_string(), DoorStatus::Fired),
                ("wal".to_string(), DoorStatus::Fired),
            ]
        );
    }

    #[test]
    fn two_pools_each_get_the_budget() {
        // The house segment is a channel body: typed text follows the book (D1).
        let prompt = format!("{CHANNEL}\n\n{}", paste("aaaa", WALDEN));
        let doors = [
            door("hse", "widget", &[]),
            door("hs2", "widget", &[]),
            door("wal", "fair haven", &["book:walden"]),
            door("wa2", "huckleberries", &["book:walden"]),
        ];
        let ex = explain_mode(&prompt, "book:walden", &doors, &HashMap::new(), 1);
        let sel = ex.selection();
        let fired: Vec<(&str, &str)> = sel
            .fired
            .iter()
            .map(|f| (f.id.as_str(), f.place.as_str()))
            .collect();
        assert_eq!(fired, vec![("hs2", "house"), ("wa2", "book:walden")]);
        assert_eq!(sel.deferred, 2, "one overflow per pool");
        // Budget 0 is the kill switch for both pools.
        assert!(fired_ids(&prompt, "book:walden", &doors, 0).is_empty());
    }

    #[test]
    fn a_door_scoped_to_house_and_a_book_fires_once() {
        let prompt = format!(
            "<channel source=\"cli\" user_id=\"@j:s\">\nfair haven\n</channel>\n\n{}",
            paste("aaaa", WALDEN)
        );
        let doors = [door("two", "fair haven", &["house", "book:walden"])];
        let ex = explain_mode(&prompt, "book:walden", &doors, &HashMap::new(), 2);
        assert_eq!(
            verdicts(&ex),
            vec![("two".to_string(), DoorStatus::Fired, "house".to_string())],
            "equal specificity: the earlier segment wins"
        );
    }

    #[test]
    fn known_edge_paste_opener_in_a_channel_attribute_routes_no_further_than_a_paste() {
        // A paste opener inside a channel attribute plus a closer in the body
        // turns the rest into a paste. In book mode that segment must reach
        // only what any paste reaches: the book place, house, or nothing.
        let prompt = concat!(
            r#"<channel source="matrix" user_id="<pasted_content id="ab12">">"#,
            "\nsays fair haven twice, fair haven\n",
            r#"</pasted_content id="ab12">"#,
            "\ntail</channel>"
        );
        let ex = explain_mode(prompt, "book:walden", &[], &HashMap::new(), 2);
        let p = ex
            .segments
            .iter()
            .find(|s| s.origin == Origin::Paste)
            .expect("the edge yields a paste segment");
        assert!(
            [Places::house(), Places::book("walden"), Places::none()].contains(&p.places),
            "{:?}",
            p.places
        );
        assert!(ex.segments.iter().all(|s| s.places.0.len() <= 1));
    }

    /// A channel block shaped exactly like Claude Code 2.1.310's channel
    /// wrapper builds it: every attribute value escaped `&`, `<`, `>`, `"`, `'`
    /// in that order, the body passed through as given. The segmenter's safety
    /// against #485 (a paste forged from a channel attribute) depends on this
    /// escaping.
    fn cc_channel(source: &str, meta: &[(&str, &str)], body: &str) -> String {
        fn esc(v: &str) -> String {
            v.replace('&', "&amp;")
                .replace('<', "&lt;")
                .replace('>', "&gt;")
                .replace('"', "&quot;")
                .replace('\'', "&apos;")
        }
        let attrs: String = meta
            .iter()
            .map(|(k, v)| format!(" {k}=\"{}\"", esc(v)))
            .collect();
        format!(
            "<channel source=\"{}\"{attrs}>\n{body}\n</channel>",
            esc(source)
        )
    }

    // Escaped is inert here; raw still forges, see
    // known_edge_paste_opener_in_a_channel_attribute_routes_no_further_than_a_paste.
    #[test]
    fn cc_escaped_paste_opener_in_a_channel_attribute_is_inert() {
        let prompt = cc_channel(
            "matrix",
            &[
                ("user", r#"<pasted_content id="ab12">zephyrine"#),
                ("user_id", "@a:s"),
            ],
            "says fair haven twice, fair haven\n</pasted_content id=\"ab12\">\ntail",
        );
        let segs = segment(&prompt);
        assert_eq!(segs.iter().filter(|s| s.origin == Origin::Paste).count(), 0);
        assert_eq!(
            segs.iter().map(|s| &s.origin).collect::<Vec<_>>(),
            vec![&channel("@a:s")]
        );

        let book = [door("wa", "fair haven", &["book:walden"])];
        assert!(fired_ids(&prompt, "book:walden", &book, 2).is_empty());
        let attr = [door("ze", "zephyrine", &["house", "book:walden"])];
        assert!(fired_ids(&prompt, "house", &attr, 2).is_empty());
        assert!(fired_ids(&prompt, "book:walden", &attr, 2).is_empty());
    }

    // Escaped is inert here; raw still forges, see
    // known_edge_paste_opener_in_a_channel_attribute_routes_no_further_than_a_paste.
    #[test]
    fn cc_escaped_paste_opener_and_closer_in_two_channel_attributes_are_inert() {
        let prompt = cc_channel(
            "matrix",
            &[
                ("user", r#"<pasted_content id="ab12">"#),
                ("user_id", "@a:s"),
                ("room_name", r#"</pasted_content id="ab12">"#),
            ],
            "says fair haven",
        );
        let segs = segment(&prompt);
        assert_eq!(segs.iter().filter(|s| s.origin == Origin::Paste).count(), 0);
        assert_eq!(
            segs.iter().map(|s| &s.origin).collect::<Vec<_>>(),
            vec![&channel("@a:s")]
        );
    }

    #[test]
    fn notification_preamble_and_its_block_fire_nothing() {
        let trig = ["lighthouse keeper"];
        assert!(fired_on(PREAMBLE, &trig).is_empty());
        let prompt = format!("{PREAMBLE}\nthe lighthouse keeper again?");
        assert_eq!(fired_on(&prompt, &trig), vec!["lighthouse keeper"]);
        assert!(!strip_harness_blocks(PREAMBLE).contains("background helper"));
    }

    #[test]
    fn preamble_mention_mid_line_is_not_a_header() {
        let prompt = "someone said [SYSTEM NOTIFICATION] lol\nthe lighthouse keeper";
        assert_eq!(strip_harness_blocks(prompt), prompt);
        assert_eq!(
            fired_on(prompt, &["lighthouse keeper"]),
            vec!["lighthouse keeper"]
        );
        // An opener without its `]` on the same line is no header either.
        let prompt = "[SYSTEM NOTIFICATION\nwidget]";
        assert_eq!(strip_harness_blocks(prompt), prompt);
    }

    #[test]
    fn unterminated_preamble_ends_with_its_paragraph() {
        let prompt =
            "before widget\n  [SYSTEM NOTIFICATION - X]\nprose gizmo\nmore gizmo\n\nafter sprocket";
        assert_eq!(
            strip_harness_blocks(prompt),
            "before widget\n\nafter sprocket"
        );
        assert_eq!(
            fired_on(prompt, &["widget", "gizmo", "sprocket"]),
            vec!["sprocket", "widget"]
        );
        // With no blank line at all it stops at a harness opener, and the
        // block goes as usual.
        let prompt =
            "[SYSTEM NOTIFICATION]\ngizmo\n<system-reminder>gizmo</system-reminder>\nwidget";
        assert_eq!(fired_on(prompt, &["gizmo", "widget"]), vec!["widget"]);
    }

    #[test]
    fn preamble_at_the_end_of_a_paste_keeps_the_closer() {
        let body = format!("{WALDEN}\n\n[SYSTEM NOTIFICATION - copied log]\nwidget sprocket");
        let prompt = format!("{}\n\n gizmo", paste("aaaa", &body));
        let doors = [
            door("fh", "fair haven", &[]),
            door("wi", "widget", &[]),
            door("gz", "gizmo", &[]),
        ];
        let ex = explain_mode(&prompt, "house", &doors, &HashMap::new(), 3);
        let p = ex
            .segments
            .iter()
            .find(|s| s.origin == Origin::Paste)
            .expect("the paste survives the strip");
        assert_eq!(
            p.classified.as_ref().map(|c| c.verdict),
            Some(Verdict::ForeignProse)
        );
        assert!(p.places.is_empty(), "quarantined in house mode");
        assert_eq!(fired_ids(&prompt, "house", &doors, 3), vec!["gz"]);
    }

    #[test]
    fn preamble_at_the_end_of_a_harness_block_keeps_its_closer() {
        let prompt = concat!(
            "<task-notification>\nreport gizmo\n\n",
            "[SYSTEM NOTIFICATION - X]\ngizmo more\n",
            "</task-notification>\nthe widget"
        );
        assert_eq!(fired_on(prompt, &["gizmo", "widget"]), vec!["widget"]);
    }

    #[test]
    fn preamble_header_shape_is_exact() {
        let trig = ["lighthouse keeper"];
        for prompt in [
            "[SYSTEM NOTIFICATIONs suck] lighthouse keeper",
            "[SYSTEM NOTIFICATIONs suck]\nlighthouse keeper",
            "[SYSTEM NOTIFICATION] then text\nlighthouse keeper",
            "[SYSTEM NOTIFICATION - <x>]\nlighthouse keeper",
        ] {
            assert_eq!(strip_harness_blocks(prompt), prompt, "{prompt:?}");
            assert_eq!(fired_on(prompt, &trig), vec!["lighthouse keeper"]);
        }
        for prompt in [
            "[SYSTEM NOTIFICATION - NOT USER INPUT]\nlighthouse keeper",
            "  [SYSTEM NOTIFICATION]  \nlighthouse keeper",
            "[SYSTEM NOTIFICATION-x]\nlighthouse keeper",
        ] {
            assert!(fired_on(prompt, &trig).is_empty(), "{prompt:?}");
        }
    }

    // ---- match grammar (P4) ----

    /// `(id, triggers, exclusions)` doors explained in house mode, budget 9.
    fn explain_grammar(prompt: &str, doors: &[(&'static str, &[&str], &[&str])]) -> Explanation {
        let owned: Vec<(Vec<String>, Vec<String>)> = doors
            .iter()
            .map(|(_, t, e)| {
                (
                    t.iter().map(|s| s.to_string()).collect(),
                    e.iter().map(|s| s.to_string()).collect(),
                )
            })
            .collect();
        let cands: Vec<TriggeredRef<'_>> = doors
            .iter()
            .zip(&owned)
            .map(|((id, _, _), (t, e))| TriggeredRef {
                key: "d",
                id,
                value: "v",
                ts: "2026-01-01T00:00:00Z",
                triggers: t,
                fragment: None,
                memory: None,
                scope: None,
                exclude: (!e.is_empty()).then_some(e.as_slice()),
            })
            .collect();
        explain(
            prompt,
            &Mode::House,
            &NamesUs::default(),
            &cands,
            &HashSet::new(),
            &HashMap::new(),
            9,
        )
    }

    /// `(id, trigger, status, segment, excluded_by)` per matched door.
    fn grammar_outcome(
        ex: &Explanation,
    ) -> Vec<(String, String, DoorStatus, usize, Option<String>)> {
        ex.doors
            .iter()
            .map(|d| {
                (
                    d.door.id.clone(),
                    d.door.trigger.clone(),
                    d.status,
                    d.segment,
                    d.excluded_by.clone(),
                )
            })
            .collect()
    }

    #[test]
    fn grammar_and_fires_in_one_segment_in_any_order() {
        let doors = [("z", &["zorbel + quuxer"][..], &[][..])];
        for prompt in ["a quuxer and a zorbel", "zorbel, then quuxer"] {
            assert_eq!(
                grammar_outcome(&explain_grammar(prompt, &doors)),
                vec![(
                    "z".into(),
                    "zorbel + quuxer".into(),
                    DoorStatus::Fired,
                    1,
                    None
                )],
                "{prompt:?}"
            );
        }
    }

    #[test]
    fn grammar_and_split_across_segments_does_not_fire() {
        let doors = [("z", &["zorbel + quuxer"][..], &[][..])];
        let prompt = format!("about the zorbel\n\n{}", paste("aaaa", "one quuxer"));
        let ex = explain_grammar(&prompt, &doors);
        assert_eq!(ex.segments.len(), 2);
        assert!(ex.doors.is_empty(), "{:?}", grammar_outcome(&ex));
        // Both sides inside the paste fire from the paste.
        let prompt = format!("hm\n\n{}", paste("aaaa", "one quuxer, one zorbel"));
        assert_eq!(
            grammar_outcome(&explain_grammar(&prompt, &doors)),
            vec![(
                "z".into(),
                "zorbel + quuxer".into(),
                DoorStatus::Fired,
                2,
                None
            )]
        );
    }

    #[test]
    fn exclusion_holds_the_door_for_its_segment_and_says_why() {
        let doors = [("z", &["zorbel"][..], &["vintage zorbel", "glarp*"][..])];
        for (prompt, by) in [
            ("my vintage zorbel", "vintage zorbel"),
            ("a glarpish zorbel", "glarp*"),
        ] {
            let ex = explain_grammar(prompt, &doors);
            assert_eq!(
                grammar_outcome(&ex),
                vec![(
                    "z".into(),
                    "zorbel".into(),
                    DoorStatus::Held,
                    1,
                    Some(by.into())
                )],
                "{prompt:?}"
            );
            assert_eq!(ex.doors[0].door.place, "");
            assert!(ex.selection().fired.is_empty());
        }
        // Without an exclusion phrase present it fires.
        assert_eq!(
            explain_grammar("my zorbel", &doors).selection().fired.len(),
            1
        );
    }

    #[test]
    fn exclusion_in_one_segment_and_a_clean_hit_in_another_still_fires() {
        let doors = [("z", &["zorbel"][..], &["vintage"][..])];
        let prompt = format!("vintage zorbel\n\n{}", paste("aaaa", "zorbel again"));
        assert_eq!(
            grammar_outcome(&explain_grammar(&prompt, &doors)),
            vec![("z".into(), "zorbel".into(), DoorStatus::Fired, 2, None)]
        );
        // An exclusion only holds the segment it matched in.
        let prompt = format!("zorbel\n\n{}", paste("aaaa", "vintage stuff"));
        assert_eq!(
            grammar_outcome(&explain_grammar(&prompt, &doors)),
            vec![("z".into(), "zorbel".into(), DoorStatus::Fired, 1, None)]
        );
    }

    #[test]
    fn exclusion_hold_is_distinct_from_a_scope_hold() {
        let doors = [door("b", "zorbel", &["book:walden"])];
        let ex = explain_mode("a zorbel", "house", &doors, &HashMap::new(), 2);
        assert_eq!(ex.doors[0].status, DoorStatus::Held);
        assert_eq!(ex.doors[0].excluded_by, None);
    }

    #[test]
    fn grammar_specificity_counts_tokens_across_sides() {
        assert_eq!(specificity("zorbel + quuxer pod"), (3, 19));
        assert_eq!(specificity("quuxer*"), (1, 7));
        // Plain triggers keep today's measure exactly.
        assert_eq!(specificity("c++ tips"), (2, 8));
        assert_eq!(specificity("study +blarnia"), (2, 14));
        let doors = [(
            "z",
            &["zorbel", "zorbel + quuxer", "quuxer pod"][..],
            &[][..],
        )];
        assert_eq!(
            explain_grammar("quuxer pod zorbel", &doors).doors[0]
                .door
                .trigger,
            "zorbel + quuxer"
        );
        let doors = [("z", &["zorbel + quuxer", "zorbel quuxer pod"][..], &[][..])];
        assert_eq!(
            explain_grammar("zorbel quuxer pod", &doors).doors[0]
                .door
                .trigger,
            "zorbel quuxer pod"
        );
    }

    #[test]
    fn grammar_rejection_names_the_word_once() {
        let rule = |t: &str| match inspect_trigger(t) {
            TriggerVerdict::Invalid { rule } => rule,
            other => panic!("{t:?}: {other:?}"),
        };
        assert_eq!(
            rule("  Fo*O "),
            "has `*` mid-word: a wildcard goes at the start or the end of a word"
        );
        assert_eq!(
            rule("zorbel fo*o"),
            "has \"fo*o\" with `*` mid-word: a wildcard goes at the start or the end of a word"
        );
        assert_eq!(
            rule("quuxer + *flim"),
            "has \"*flim\" with 4 literal characters: a wildcard needs at least 5"
        );
    }

    #[test]
    fn grammar_triggers_are_judged_before_they_are_stored() {
        let invalid = |t: &str| matches!(inspect_trigger(t), TriggerVerdict::Invalid { .. });
        for bad in [
            "zorbel +",
            "+",
            "zor*bel",
            "*zorb",
            "**zorbel",
            "*zorb-el",
            "--- + zorbel",
        ] {
            assert!(invalid(bad), "{bad:?}");
        }
        assert_eq!(
            inspect_trigger("zorbel + quuxer*"),
            TriggerVerdict::Fine {
                matched_as: "zorbel + quuxer*".into()
            }
        );
        assert_eq!(
            inspect_trigger("c++ + zorbel"),
            TriggerVerdict::BroadSide {
                matched_as: "c + zorbel".into(),
                side: "c".into()
            }
        );
        assert_eq!(matched_form("frim_bo + *flimbing"), "frim bo + *flimbing");
        // Exclusions: phrase/wildcard only, and Dead/Broad as for triggers.
        assert!(matches!(
            inspect_exclusion("zorbel + quuxer"),
            TriggerVerdict::Invalid { .. }
        ));
        assert_eq!(inspect_exclusion("!!!"), TriggerVerdict::Dead);
        assert_eq!(
            inspect_exclusion("c#"),
            TriggerVerdict::Broad {
                matched_as: "c".into()
            }
        );
        assert!(matches!(
            inspect_exclusion("glarp*"),
            TriggerVerdict::Fine { .. }
        ));
    }

    #[test]
    fn a_glued_plus_is_flagged_with_its_and_spelling() {
        assert_eq!(
            lopsided_plus("study +blarnia").as_deref(),
            Some("study + blarnia")
        );
        assert_eq!(
            lopsided_plus("study+ blarnia").as_deref(),
            Some("study + blarnia")
        );
        for fine in [
            "c++",
            "c++ tips",
            "zim & zam",
            "+blarnia",
            "study+",
            "a + b",
            "x+y",
            "zorbel + +blarnia",
            "zorbel+ + quuxer",
        ] {
            assert_eq!(lopsided_plus(fine), None, "{fine:?}");
        }
    }

    /// Back-compat pin: every plain trigger shape fires through the doors path
    /// exactly what the pre-grammar matcher fires, and none is parsed as grammar.
    #[test]
    fn plain_triggers_fire_exactly_as_legacy_through_the_doors_path() {
        let trigs = [
            "zorbel",
            "zorbel quuxer",
            "c++",
            "c++ tips",
            "c#",
            "zim & zam",
            "blip-blop",
            "frim_bo",
            "snorp-",
            ".grimnet",
            "a+ grade",
            "study +blarnia",
            "q",
            "caf\u{00e9}",
            "\u{00fc}berfrob stra\u{00df}e",
            "na\u{00ef}ve plan",
            "x2",
            "mr. snorkel",
        ];
        for t in trigs {
            assert_eq!(
                triggers::parse_grammar(t),
                Ok(None),
                "{t:?} must stay plain"
            );
        }
        let prompts = [
            "the zorbel quuxer is out",
            "quuxer then zorbel",
            "I write C++ tips, and c# too",
            "ZIM & ZAM, zim and zam",
            "blip blop; blip-blop; blipblop",
            "frim_bo frim-bo frimbo",
            "snorp-light and snorpy",
            "the .GRIMNET stack",
            "an A+ grade, a grade",
            "study blarnia, study +blarnia",
            "q? Q! queue",
            "cafe\u{0301} au lait",
            "UBERFROB strasse vs \u{00fc}berfrob stra\u{00df}e",
            "a naive plan, a na\u{00ef}ve plan",
            "x2 and x 2",
            "ask Mr Snorkel",
            "<system-reminder>zorbel</system-reminder> blip-blop",
            "nothing at all",
        ];
        let mut any = 0;
        for prompt in prompts {
            let legacy = legacy_fired(prompt, &trigs);
            assert_eq!(fired_on(prompt, &trigs), legacy, "{prompt:?}");
            any += legacy.len();
        }
        assert!(any >= 15, "fixture must actually fire things ({any})");
    }

    /// A ` + ` or `*` trigger takes the grammar path: the legacy matcher reads
    /// it as a contiguous phrase of its bare tokens and would answer otherwise.
    #[test]
    fn grammar_triggers_take_the_new_path_and_plain_ones_do_not() {
        for (trig, prompt) in [
            ("zorbel + quuxer", "quuxer, later zorbel"),
            ("*flimbing", "much reflimbing"),
            ("quuxer* pod", "quuxering pod"),
        ] {
            assert!(triggers::parse_grammar(trig).unwrap().is_some());
            assert!(legacy_fired(prompt, &[trig]).is_empty(), "{trig:?}");
            assert_eq!(fired_on(prompt, &[trig]), vec![trig], "{trig:?}");
        }
        // A grammar trigger next to plain ones on the same entry: the plain
        // ones still answer exactly as before.
        let doors = [("m", &["zorbel quuxer", "*flimbing"][..], &[][..])];
        assert!(explain_grammar("quuxer zorbel", &doors).doors.is_empty());
        assert_eq!(
            explain_grammar("zorbel quuxer", &doors).doors[0]
                .door
                .trigger,
            "zorbel quuxer"
        );
    }
}